@oracle/oraclejet-audit 17.0.4 → 17.1.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 +1 -1
- package/lib/Components.js +1 -1
- package/lib/ConfigEx.js +1 -1
- package/lib/HtmlUtils.js +1 -1
- package/lib/Registry.js +1 -1
- package/lib/RuleSet.js +1 -1
- package/lib/Rules.js +1 -1
- package/lib/TsxUtils.js +1 -1
- package/lib/checkage.js +1 -1
- package/lib/defaults.js +1 -1
- package/lib/manual.js +1 -1
- package/lib/migrator.js +1 -1
- package/lib/sublib/precomp/Precompiler.js +1 -1
- package/libext/expparser.js +1 -1
- package/meta/17.0.0/jetauditmeta.js +2 -2
- package/meta/17.1.0/jetauditmeta.js +9 -0
- package/meta/metaverlist.json +1 -1
- package/package.json +2 -2
- package/rules/jaf/jaf-sys-rule-disable.js +6 -0
- package/rules/jaf/jaf-sys-rule-opt.js +1 -1
- package/rules/jaf/jaf-sys-rule-pack-disable.js +6 -0
- package/rules/jaf/jaf-ts-loader.js +6 -0
- package/rules/jaf/msgid.json +1 -1
- package/rules/jaf/rules.json +1 -1
- package/rules/jet/helpers/vartrack.js +1 -1
- package/rules/jet/oj-acc-aria-prop.js +1 -1
- package/rules/jet/oj-acc-input-aria-label.js +1 -1
- package/rules/jet/oj-css-style-override.js +1 -1
- package/rules/jet/rules.json +1 -1
- package/schema/component-schema.json +1 -1
- package/src/JafCore.js +1 -1
package/lib/Components.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
|
-
"use strict";const COMPONENT_JSON="component.json";const PROPERTIES="properties";const PROP_SLOTS="slots";const PROP_DYNAMIC_SLOTS="dynamicSlots";const PROP_PROPS="props";const PROP_EVENTS="events";const PROP_STYLECLASSES="styleClasses";const PROP_IMPLEMENTS="implements";const PROP_REQUIRED="required";const PROP_FOLDER="folder";const PROP_VERSION="version";const PROP_UNSUP_THEME="unsupTheme";const PROP_STATUS="status";const PROP_SUBCOMPONENT_TYPE="subcomponentType";const PROP_DEPENDENCIES="dependencies";const PROP_TYPE="type";const PROP_PACK="pack";const PROPERTY_VALUE="propertyValue";const PROPERTY_TYPE="propertyType";const PACK_PRIVATE="packPrivate";const DEPRECATED="deprecated";const MAINTENANCE="maintenance";const SUPERSEDES="supersedes";const ANTIPATTERN="antiPattern";const DYNAMIC_FORM_ELEM="DynamicFormElement";const DYNAMIC_TABLE_ELEM="DynamicTableElement";const VB_FRAGMENT_ELEM="VbFragmentElement";const CUSTOM_ELEMENT="@customElement";const REGISTER_CUSTOM_ELEMENT="registerCustomElement";const OJ_C="oj-c";const DOT=".";const CHANGED="Changed";const FT_HTML="html";const FT_TSX="tsx";const REGXPR=/string|number|object|array|boolean|[\|.<>]/gi;function Components(nd,runMode,cwd,compSvcs,urlBase,urls,filePaths,metaLib,ojcPack,jetCore,runOpts,msgCtx,appCtx){this._nd=nd;this._tagLookup={};this._jetTagLookup={};this._VCompLookup={};this._styleLookup={};this._ignored={};this._maintenance=null;this._supersedes=null;this._antiPattern=null;this._meta={};this._path=null;this._reqAttrs=null;this._metaLib=metaLib;this._ojcPack=ojcPack;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._tsUtils=appCtx.tsUtils;this._curFileType=null;this._oConfig=appCtx.config;this._VFilesInspected=null;this._VTypes=null;this._compSvcs=compSvcs;this._isAMD=runMode==="amd";this._cwd=cwd;this._error=msgCtx.error;this._warn=msgCtx.warn;this._debug=msgCtx.debug;this._info=msgCtx.info;this._msg=msgCtx.msg;this._console=msgCtx.console;this._jafMsg=msgCtx.jafMsg;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._count=0;this._isOk=true;this._runOpts=runOpts;this._init(urlBase,urls,filePaths,jetCore);if(this._tsUtils){this._initVComponents()}};Components.prototype.isUserTag=function(tagName){var tag=_removeChevrons(tagName);return!!(this._tagLookup[tag]||this._VCompLookup[tag])};Components.prototype.isJetCoreTag=function(tagName){return!!this._jetTagLookup[_removeChevrons(tagName)]};Components.prototype.isVComponentTag=function(tagName){return!!this._VCompLookup[_removeChevrons(tagName)]};Components.prototype.isKnownTag=function(tagName){return!!this._lookupTag(tagName)};Components.prototype._lookupTag=function(tagName){tagName=_removeChevrons(tagName);return this._jetTagLookup[tagName]||this._tagLookup[tagName]||this._VCompLookup[tagName]};Components.prototype.isTagAttr=function(tagName,attrName){return this.isTagProp(tagName,attrName)||this.isJetTagProp(tagName,attrName)};Components.prototype.isJetTagAttr=function(tagName,attrName){return this.isJetTagProp(tagName,attrName)};Components.prototype.isTagDeprecated=function(tag){var comp,stats,status,ret=null;if(comp=this._lookupTag(_removeChevrons(tag))){if(stats=comp.status){for(status of stats){if((!status.type||status.type===DEPRECATED)&&!status.hasOwnProperty("target")){ret=status;if(ret.description){ret.description=this._utils.removeLink(ret.description)}break}}}}return ret};Components.prototype.isTagAttrDeprecated=function(tagName,attrName){var prop,status,stats,o,ret=null;if((prop=this.getAnyTagProp(tagName,attrName))&&(stats=prop.status)){ret=[];for(status of stats){if(!status.type||status.type===DEPRECATED){o={type:DEPRECATED};if(status.hasOwnProperty("target")){o.target=status.target}if(status.hasOwnProperty("description")){o.description=status.description}if(status.hasOwnProperty("since")){o.since=status.since}if(status.hasOwnProperty("value")){o.value=status.value}ret.push(o)}}ret=ret.length?ret:null}return ret};Components.prototype.isTagEventDeprecated=function(tagName,eventName){var event,stats,ret=null;if(event=this.getAnyTagEvent(tagName,eventName)){if(stats=event.status){stats.forEach(stat=>{if(!stat.type||stat.type===DEPRECATED){if(!ret){ret=[]}ret.push(stat)}})}}return ret};Components.prototype.getTagPropertyFromEvent=function(tagName,eventName){var o,ret;if(o=this.getTagEventName(tagName,eventName)){ret=o.name}return ret?ret:null};Components.prototype.isTagAttrTranslatable=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.translatable};Components.prototype.isTagAttrReadOnly=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.readonly};Components.prototype.isTagAttrWriteback=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.writeback};Components.prototype.isTagProp=function(tagName,propName){return!!this.getTagProp(tagName,propName)};Components.prototype.isJetTagProp=function(tagName,propName){return!!this.getJetTagProp(tagName,propName)};Components.prototype.getTagProp=function(tagName,propName){var ret;if(this.isUserTag(tagName)){ret=this._getTagProp(tagName,propName,false)}return ret?ret:null};Components.prototype.getJetTagProp=function(tagName,propName){var ret;if(this.isJetCoreTag(tagName)){ret=this._getTagProp(tagName,propName,true)}return ret?ret:null};Components.prototype.getAnyTagProp=function(tagName,propName){return this._getTagProp(tagName,propName,true)||this._getTagProp(tagName,propName,false)};Components.prototype._getTagProp=function(tagName,propName,isOJC){var tag,props,list;tagName=_removeChevrons(tagName);if(isOJC){tag=this._jetTagLookup[tagName]}else{tag=this._tagLookup[tagName]||this._VCompLookup[tagName]};props=tag?tag[PROP_PROPS]:null;if(props){propName=propName.charAt(0)===":"?propName.substring(1):propName;if(this._curFileType!=="tsx"){propName=_propToCamelCase(propName)}}return props?props[propName]:null};Components.prototype.getTagPropType=function(tagName,propName){var prop,ret;if(prop=this.getTagProp(tagName,propName)){ret=prop?prop.type:undefined}return ret};Components.prototype.getAnyTagEvent=function(tag,event){return this._getTagEvent(tag,event,true)||this._getTagEvent(tag,event,false)};Components.prototype._getTagEvent=function(tagName,eventName,isOJC){var tagObj,events,event;if(!eventName.startsWith("on")){return null}tagName=_removeChevrons(tagName);if(isOJC){tagObj=this._jetTagLookup[tagName]}else{tagObj=this._tagLookup[tagName]||this._VCompLookup[tagName]}if(!tagObj){return null}if(!(events=tagObj[PROP_EVENTS])){return null}if(eventName.includes("-")){eventName=eventName.substring(3);eventName=_propToCamelCase(eventName)}else{eventName=eventName.substring(2)}event=events[eventName];return event?event:null};Components.prototype.getComponentPropMetadata=function(tagName,propName){var comp,sofar,props;tagName=_removeChevrons(tagName);if(!(comp=this._meta[tagName])||!(props=comp.properties)){return null}let subprops=propName.split(DOT);if(this._curFileType===FT_HTML){subprops.forEach((subprop,i,ar)=>{ar[i]=_propToCamelCase(subprop)})}if(subprops.length===1){return props[propName]||null}sofar=comp;let nextprop,i;for(i=0;i<subprops.length;i++){nextprop=subprops[i];if(sofar.hasOwnProperty(PROPERTIES)){sofar=sofar.properties[nextprop]||null;if(!sofar){break}}else{sofar=null;break}}return sofar};Components.prototype.getComponentMetadata=function(tag){return this._meta[tag]||null};Components.prototype.getAllCustomMetadata=function(){var name,comp,obj;var ret={};var i=2;var lookup=this._tagLookup;while(i){for(name in lookup){ret[name]=obj={};comp=lookup[name];obj.folder=comp.folder;obj.json=this.getComponentMetadata(name);if(i===1){obj.VCType=this._VTypes[name]}}i--;lookup=this._VCompLookup}return ret};Components.prototype.getJetTag=function(tag){var o;return(o=this._jetTagLookup[tag])?o:null};Components.prototype.getMaintenanceTags=function(){return this._maintenance};Components.prototype.isTagEvent=function(tagName,eventName){return!!this.getTagEventName(tagName,eventName)};Components.prototype.getTagEventName=function(tagName,eventName){var propName,tagObj,events,impls;tagObj=this._lookupTag(_removeChevrons(tagName));if(!tagObj||!eventName.startsWith("on")){return null}if(eventName.includes("-")){eventName=eventName.substring(3);eventName=_propToCamelCase(eventName)}else{eventName=eventName.substring(2)}if(tagObj.events&&tagObj.events[eventName]){return{type:"event",name:eventName}}if((impls=tagObj.implements)&&(impls.includes(DYNAMIC_FORM_ELEM)||impls.includes(DYNAMIC_TABLE_ELEM)||impls.includes(VB_FRAGMENT_ELEM))){return{type:"dynamic",name:eventName}}if(eventName.endsWith(CHANGED)&&tagObj.props){propName=eventName.replace(CHANGED,"");if(tagObj.props[propName]){return{type:"property",name:propName}};}return null};Components.prototype.isTagStyle=function(tag,style){var tagObj,ret=false;if(tagObj=this._lookupTag(_removeChevrons(tag))){let styles;if(styles=tagObj.styleClasses){ret=!!styles[style]}}return ret};Components.prototype.isJetStyle=function(style){var tag,ret=false;if(tag=this._styleLookup[style]){ret=!!this._jetTagLookup[tag]}return ret};Components.prototype.isStyle=function(style){return!!this._styleLookup[style]};Components.prototype.getStyleMetadata=function(style){var tag,styles,sc,ret=null;if(tag=this._styleLookup[style]){if(styles=this._tagLookup[tag].styleClasses){if(sc=styles[style]){ret={tag:tag,meta:sc}}}}return ret};Components.prototype.getStyleSelector=function(style){var sm=this.getStyleMetadata(style);return sm&&sm.meta?sm.meta.styleSelector:null};Components.prototype.hasTagSlotName=function(tagName,slotName){var o=this._lookupTag(_removeChevrons(tagName));return!!(o&&o.slots&&o.slots[slotName])};Components.prototype.getPreferredSlotContent=function(tag,slotName,impls){var o,slot,prefContent=null,comps=null,content;if(this._utils.hasAnyProps(impls)){if(o=this._lookupTag(_removeChevrons(tag))){if(o.slots){slotName=slotName?slotName:"";if(slot=o.slots[slotName]){if((prefContent=slot.preferredContent)&&prefContent.length){prefContent.forEach(impl=>{if(content=impls[impl]){if(!comps){comps=[]}comps.push(...content)}})}else{prefContent=null}}}}}return prefContent||comps?{interfaces:prefContent,components:comps}:null};Components.prototype.getTagSlotMetadata=function(tag,slot){var o,ret;if(o=this._lookupTag(_removeChevrons(tag))){if(o.slots){slot=slot?slot:"";if(slot=o.slots[slot]){ret=slot}}}return ret};Components.prototype.hasTagDynamicSlot=function(tag){var o,ret=false;if(o=this._lookupTag(_removeChevrons(tag))){ret=o.hasOwnProperty(PROP_DYNAMIC_SLOTS)}return ret};Components.prototype.hasTagAttrValues=function(tagName,attrName){var prop,ret=false;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){ret=!!prop.enumValues}return ret};Components.prototype.isTagAttrValue=function(tagName,attrName,value){var prop,ret;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){if(prop&&prop.enumValues){ret=prop.enumValues.indexOf(value)>=0}}return!!ret};Components.prototype.isTagAttrEnumDeprecated=function(tag,attr,val){var prop,stats,status,ret=null;if(prop=this.getAnyTagProp(tag,attr)){if(stats=prop.status){for(status of stats){if((!status.type||status.type===DEPRECATED)&&status.target===PROPERTY_VALUE){if(status.value&&status.value.includes(val)){ret={type:DEPRECATED};if(status.hasOwnProperty("target")){ret.target=status.target}if(status.hasOwnProperty("description")){ret.description=status.description}if(status.hasOwnProperty("since")){ret.since=status.since}if(status.hasOwnProperty("value")){ret.value=status.value}break}}}}}return ret};Components.prototype.isTagSupportedInTheme=function(tag,theme){var o,unsup,ret=true;if(o=this._lookupTag(tag)){if(unsup=o[PROP_UNSUP_THEME]){ret=!unsup.includes(theme)}}return ret};Components.prototype.isAttrSupportedInTheme=function(tag,attr,theme){var prop,unsup,ret=true;if(prop=this.getAnyTagProp(tag,attr)){if(unsup=prop[PROP_UNSUP_THEME]){ret=!unsup.includes(theme)}}return ret};Components.prototype.isTagPackPrivate=function(tag){var o,ret;if(o=this._lookupTag(_removeChevrons(tag))){ret=o[PROP_SUBCOMPONENT_TYPE]===PACK_PRIVATE}return ret};Components.prototype.getSubcomponentType=function(tag){var o,ret;if(o=this._lookupTag(_removeChevrons(tag))){ret=o[PROP_SUBCOMPONENT_TYPE]}return ret||null};Components.prototype.getRequiredProps=function(tagName){var tag,props,prop,propName,obj,ret=null;tagName=_removeChevrons(tagName);if(this._reqAttrs){let r=this._reqAttrs[tagName];if(r){return typeof r==="boolean"?null:r}}tag=this._lookupTag(tagName);if(tag&&tag.props){if(!this._reqAttrs){this._reqAttrs={}}if(!this._reqAttrs[tagName]){this._reqAttrs[tagName]=true}props=tag.props;for(propName in props){prop=props[propName];if(prop.required){if(!obj){obj=[]}obj.push(propName)}}}if(obj&&obj.length){let i,j,p;for(i=0;i<obj.length;i++){if(p=obj[i]){p+=".";for(j=i+1;j<obj.length;j++){if(obj[j].startsWith(p)){obj.splice(i,1);i--;break}}}}this._reqAttrs[tagName]=obj;ret=obj}return ret};Components.prototype.getRequiredAttrs=function(tagName){return this.getRequiredProps(tagName)};Components.prototype.getInterfaces=function(tag){var o,ret;if(o=this._lookupTag(_removeChevrons(tag))){ret=o.implements}return ret?ret:null};Components.prototype.getCount=function(){return this._count};Components.prototype.isTagStatus=function(tag,statType){return!!this._getTagStatus(tag,statType)};Components.prototype.getTagStatus=function(tag,statType){var ret=null,omitted=statType===undefined;var comp,arStat,stat,stType,i;if(comp=this._lookupTag(_removeChevrons(tag))){if(arStat=comp.status){for(i=0;i<arStat.length;i++){stat=arStat[i];stType=stat.type||DEPRECATED;if(omitted||stType===statType){if(!ret){ret=[]}ret.push(stat)}}}}return ret};Components.prototype.getPropStatus=function(tagName,propName,statType){let comp,arStat,ret;if(comp=this._lookupTag(_removeChevrons(tagName))){if(comp.props&&(arStat=comp.props[propName]?.status)){let stat,stType,i,omitted=statType===undefined;for(i=0;i<arStat.length;i++){stat=arStat[i];stType=stat.type||DEPRECATED;if(omitted||stType===statType){if(!ret){ret=[]}ret.push(stat)}}}}return ret?ret:null};Components.prototype.isRuleIgnored=function(compName,ruleName){var ret,ar;if(ar=this._ignored[compName]){ret=ar.includes(ruleName)}return!!ret};Components.prototype.isOk=function(){return this._isOk};Components.prototype.setCurFileType=function(ft){this._curFileType=ft};Components.prototype._init=function(base,urls,filePaths,jetCore){if(this._isAMD){this._processJetCorePack();return}if(base){base=base.trim();if(base.charAt(base.length-1)!=="/"){base=base+"/"}}else{base=""}this._processFilePaths(filePaths);this._processUrls(base,urls);this._processJetCorePack();this._createStyleLookup();this._processJetCore(jetCore)};Components.prototype._processFilePaths=function(filePaths){var obj,compEntry,fpath,i,j;if(!filePaths){return}this._console("\nPre-processing user-declared web component metadata...");for(i=0;i<filePaths.length;i++){compEntry=filePaths[i];var dirStack=this._nd.glob.sync(compEntry);for(j=0;j<dirStack.length;j++){fpath=dirStack[j];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg="-".repeat(70)+"\n"+(this._runOpts.isDryRun?"* ":"")+"processing component path '"+fpath+"' ...";if(this._runOpts.isDryRun){console.log(msg)}else{this._debug(msg)}}if(fpath.toLowerCase().endsWith(".zip")){obj=this._compSvcs._extractComponentJsonFromZip(fpath);if(obj.obj){this.processComponentJson(obj.obj,fpath)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+fpath)}else if(obj.error){this._error("Failed to unzip '"+fpath+"'")}continue}if(this._isComponentJsonPath(fpath)){if(obj=this._readComponentJson(fpath)){if(obj.type&&obj.type==="pack"){continue}this.processComponentJson(obj,this._nd.path.dirname(fpath))}continue}this._recurse(fpath)}}if(this._isDebug){this._debug("-".repeat(70))}};Components.prototype._recurse=function(fpath){var dirs,inFile,obj,i;try{dirs=this._nd.fs.readdirSync(fpath);if(this._isDebug){this._debug(` processing ${fpath} ${dirs.length} component dirs ...`)}for(i=0;i<dirs.length;i++){inFile=dirs[i];if(inFile===COMPONENT_JSON){inFile=this._nd.path.join(fpath,COMPONENT_JSON);if(this._isDebug){this._debug(" processing "+inFile+"...")}obj=this._readComponentJson(inFile);if(obj){if(!obj.type||obj.type==="composite"){this.processComponentJson(obj,fpath)}}else{return}}var curPath=this._nd.path.join(fpath,inFile);if(this._fsUtils.getFileType(curPath)==="d"){this._recurse(curPath)}}}catch(e){this._error("Component check failed - "+e);this._isOk=false}};Components.prototype._processUrls=function(base,urls){var url,i;if(!urls){return}for(i=0;i<urls.length;i++){url=urls[i];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg;msg="-".repeat(70)+"\nprocessing URL '"+url+"'";if(this._runOpts.isDryRun){console.log(msg);continue}else{this._debug(msg)}}if(_isRelativeUrl(url)){url=base+url;if(_isRelativeUrl(url)){this._error("component URL incomplete - '"+url+"'");continue}}this._processUrl(url)}};Components.prototype._processUrl=function(url){var resp,obj,rc,tempFile,tmp;try{resp=this._compSvcs.loadUrl(url);if(resp.eCode==="ETIMEDOUT"){this._error("config.componentUrls - request timed-out for '"+url+"'");this._isOk=false;return}try{if(resp.type==="json"){if(resp.body){obj=JSON.parse(resp.body);if(!this.processComponentJson(obj,url)){this._isOk=false}}else{this._error("Server responded with "+resp.statusCode+" URL: '"+url+"'")}}else if(resp.type=="zip"){rc=this._compSvcs.writeZipBufferToFile(resp.body);if(typeof rc==="boolean"&&rc){tempFile=this._compSvcs.getLastZipFilePath();obj=this._compSvcs.extractComponentJsonFromZip(tempFile);if(obj.obj){this.processComponentJson(obj.obj,url)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+url)}else if(obj.error){this._error("Failed to unzip '"+url+"'")}this._compSvcs.deleteZipFile(tempFile)}else{this._error("Failed to create local temp zip file from URL '"+url+"' : rc.message");this._isOk=false}}else{tmp=typeof resp.type==="string"?resp.type:"?";this._error("Server responded with unexpected data ('"+tmp+"') : '"+url+"'");this._isOk=false}}catch(e){this._error("Invalid JSON - URL '"+url+"' : "+e);this._isOk=false}}catch(e1){this._error("URL access failed "+(e1.message.includes("ENOTFOUND")?"(NOT FOUND)":"")+" - URL '"+url+"'");this._isOk=false}};Components.prototype._processJetCorePack=function(){var comps,comp;if(comps=this._ojcPack.getComponents()){for(comp in comps){this.processComponentJson(comps[comp],"oj-c")}}};Components.prototype.processComponentJson=function(obj,fromLocation,vcomp){var comp,props,events,event,eventName,compName,metaObj;var isOJC;compName=obj.pack?obj.pack+"-"+obj.name:obj.name;isOJC=obj.pack===OJ_C;if(!this._isAMD){if(this._runOpts.isDryRun){console.log(" Would have processed '"+fromLocation+"'");return}if(obj.type&&obj.type==="pack"){return this._processJetPack(obj,fromLocation)}if(!isOJC&&!vcomp){if(!this._compSvcs.validateComponentJson(obj,fromLocation)){this._isOk=false;return false}}}if(this._lookupTag(compName)){this._jafMsg("jaf-sys-dup-component",`Ignoring duplicate component '${compName}' at '${fromLocation}'`,"W");return true}this._meta[compName]=obj;(isOJC?this._jetTagLookup:vcomp?this._VCompLookup:this._tagLookup)[compName]=comp={};comp[PROP_FOLDER]=fromLocation;comp[PROP_VERSION]=obj.version;if(obj.extension&&obj.extension.audit&&obj.extension.audit.ignore){let ar;if((ar=obj.extension.audit.ignore)&&ar.length){this._ignored[compName]=[...ar]}}if(obj.hasOwnProperty(PROP_SLOTS)){comp[PROP_SLOTS]=obj[PROP_SLOTS]}if(obj.hasOwnProperty(PROP_DYNAMIC_SLOTS)){comp[PROP_DYNAMIC_SLOTS]=obj[PROP_DYNAMIC_SLOTS]}if(obj.properties){comp[PROP_PROPS]=props={};this._extractProps(props,null,obj.properties,obj.name)}if(obj.events){comp[PROP_EVENTS]=events={};for(event in obj.events){events[event]=obj.events[event];metaObj=obj.events}}if(obj.implements){comp[PROP_IMPLEMENTS]=obj.implements;this._metaLib.processImplements(compName,obj.implements)}if(obj.status){let status,i;metaObj=obj.status;for(i=0;i<metaObj.length;i++){status=metaObj[i];if(status.type===MAINTENANCE){if(!this._maintenance){this._maintenance=new Set}this._maintenance.add(compName)}else if(status.type===SUPERSEDES){if(!this._supercedes){this._supersedes=new Set}this._supersedes.add(compName)}else if(status.type===ANTIPATTERN){if(!this._antiPattern){this._antiPattern=new Set}this._antiPattern.add(compName)}}}if(obj.extension&&obj.extension.theme&&obj.extension.theme.unsupportedThemes){comp[PROP_UNSUP_THEME]=obj.extension.theme.unsupportedThemes}if(obj.hasOwnProperty(PROP_SUBCOMPONENT_TYPE)){comp[PROP_SUBCOMPONENT_TYPE]=obj[PROP_SUBCOMPONENT_TYPE]}if(obj.hasOwnProperty(PROP_DEPENDENCIES)){comp[PROP_DEPENDENCIES]=obj[PROP_DEPENDENCIES]}if(obj.type){comp[PROP_TYPE]=obj.type}if(obj.pack){comp[PROP_PACK]=obj.pack}if(obj.hasOwnProperty("required")){comp[PROP_REQUIRED]=obj.required}if(obj.status){comp[PROP_STATUS]=obj.status}if(obj.styleClasses){comp[PROP_STYLECLASSES]=this._extractStyles(obj.styleClasses)}this._count++;return true};Components.prototype._extractProps=function(propObj,propSoFar,properties,name,rdonly){var prop,thisProp,soFar,obj;for(prop in properties){soFar=(propSoFar?propSoFar+DOT:"")+prop;propObj[soFar]=obj={};thisProp=properties[prop];if(thisProp.hasOwnProperty("enumValues")){if(Array.isArray(thisProp.enumValues)){obj.enumValues=thisProp.enumValues}else{this._error(`Web component '${name}' property '${soFar}' has invalid 'enumValues' in component.json`)}}if(thisProp.hasOwnProperty("status")){obj.status=thisProp.status}if(thisProp.hasOwnProperty("type")){obj.type=thisProp.type}if(thisProp.required){obj.required=true}if(thisProp.extension&&thisProp.extension.theme&&thisProp.extension.theme.unsupportedThemes){obj[PROP_UNSUP_THEME]=thisProp.extension.theme.unsupportedThemes}if(thisProp.hasOwnProperty("translatable")){obj.translatable=true}if(typeof thisProp.readOnly==="boolean"){obj.readOnly=thisProp.readOnly}else{if(rdonly){obj.readOnly=true}}if(thisProp.hasOwnProperty("writeback")){obj.writeback=thisProp.writeback}if(thisProp.hasOwnProperty("properties")){obj.properties=true;this._extractProps(propObj,soFar,thisProp.properties,name,obj.readOnly)}}};Components.prototype._extractStyles=function(styleClasses){var so,si,obj,ret={},i,j;if(!Array.isArray(styleClasses)){return ret}for(i=0;i<styleClasses.length;i++){so=styleClasses[i];if(so.kind==="class"){ret[so.name]=this._extractStyleClass(so)}else if(so.kind==="set"&&so.styleItems&&Array.isArray(so.styleItems)){ret[so.name]=obj={kind:"set"};if(so.status){obj.status=so.status}obj.styleClasses={};for(j=0;j<so.styleItems.length;j++){si=so.styleItems[j];obj.styleClasses[si.name]=this._extractStyleClass(si)}}else if(so.kind==="template"){}}return ret};Components.prototype._extractStyleClass=function(so){var obj={};if(so.styleSelector){obj.styleSelector=so.styleSelector}if(so.status){obj.status=so.status}return obj};Components.prototype._processJetPack=function(obj,fromLocation){var deps,dep,urlKey,depUrl,msg,i;if(this._runOpts.isDryRun||this._runOpts.isDebug){msg="processing JET Pack "+obj.name+" (version: "+obj.version+") : '"+fromLocation+"'";if(this._runOpts.isDryRun){console.log("* "+msg);return}else{this._debug(msg)}}if(!fromLocation.includes("http")){this._error("JET packs loaded via config 'components' property (file based) are currently not supported");return false}i=fromLocation.indexOf(obj.name);if(i>=0){urlKey=fromLocation.substring(0,i)}else{this._error("Cannot handle Jet Pack URL format to load dependencies : "+fromLocation)}deps=obj.dependencies;if(deps){for(dep in deps){depUrl=urlKey+dep+"/versions/"+obj.dependencies[dep]+"/content/component.json";if(this._isDebug){this._debug(` processing dependency ${dep} ${obj.dependencies[dep]}`)}this._processUrls("",[depUrl])}}return false};Components.prototype._processJetCore=function(jetCorePath){var files,file,obj,i;if(!jetCorePath){return}this._console("-".repeat(70)+"\nPerforming schema analysis on JET Core components (dt) using '"+this._compSvcs.getSchemaName()+"'...");try{files=this._nd.fs.readdirSync(jetCorePath);this._console(` processing ${files.length} $jetCore components...`);for(i=0;i<files.length;i++){file=files[i];if(file.endsWith(".json")){file=this._nd.path.join(jetCorePath,file);try{obj=this._readComponentJson(file);if(obj){this._compSvcs.validateComponentJson(obj,file)}}catch(e){}}}}catch(e1){this._error("!!! $JetCore Component check failed - "+e1)}this._console(" processing "+(files?files.length+" ":"")+"$jetCore components completed");this._console("-".repeat(70))};Components.prototype._initVComponents=function(){let precompileCache,tscript;const preComp=this._tsUtils.getPreCompiler();const preCompUtils=this._tsUtils.getUtils();const auditBase=this._fsUtils.toJAFPath(this._oConfig.getBase());const projectPathInfo=preCompUtils.getKeyPathInfo(auditBase);if((tscript=this._oConfig.getTypescript())&&tscript.compile&&projectPathInfo.tsSource){this._console("Pre-processing VComponents...");if(!(precompileCache=preComp.getPrecompileCache(auditBase,projectPathInfo.tsSource,projectPathInfo.componentRootFolder))){return}if(!this._fsUtils.pathExistsSync(precompileCache)){this._debug(`VComponents: precompileCache not created - ${precompileCache}`)}else{this._getVComponentJson(precompileCache)}}};Components.prototype._getVComponentJson=function(jsonDir){var contents;if(contents=this._fsUtils.readDirSync(jsonDir)){let json;this._VFilesInspected=[];this._VTypes={};contents.forEach(file=>{if(file.isFile){json=this._fsUtils.readJsonSync(this._nd.path.join(jsonDir,file.name),false,false);if(typeof json==="string"){this._error(`Compiled metadata for x - ${json}`)}else{if(this._isDebug){this._debug(`Post compilation VComponent found : ${json.name}`)}this.processComponentJson(json,this._getVCompFolder(json.name),true)}}});this._VFilesInspected=null}};Components.prototype._getVCompFolder=function(name){var files,file,folder,ret=null,x,_self=this;const preComp=this._tsUtils.getPreCompiler();const srcFiles=preComp.getVFiles();if(srcFiles){for(file of srcFiles){if(this._VFilesInspected.includes(file)){continue}let src,VType;function _fail(errMsg){_self._warn(`Unexpected read error of '${file}'`)}if(!(src=this._fsUtils.readFileSync(file,_fail))){continue}if(!(VType=this._isVCompSrc(src,name))){continue}this._VFilesInspected.push(file);this._VTypes[name]=VType;ret=this._nd.path.dirname(file);break}}return ret};Components.prototype._isVCompSrc=function(src,name){var ret,start=0,utils=this._utils;function _extractCompName(data,x,closeDelim){let x2,comp,match=false;if((x=utils.eatWhitespace(data,x))>=0){if(data.charAt(x)==="("){if((x=utils.eatWhitespace(data,x+1))>=0){if((x2=data.indexOf(closeDelim,x))>=0){comp=data.substring(x,x2).trim();comp=comp.substring(1,comp.length-1);match=comp===name}}}}return match}while(start<src.length){let i;if((i=src.indexOf(CUSTOM_ELEMENT,start))>=0){start=i+=CUSTOM_ELEMENT.length;if(ret=_extractCompName(src,i,")")){return"class"}continue}else if((i=src.indexOf(REGISTER_CUSTOM_ELEMENT,start))>=0){start=i+=REGISTER_CUSTOM_ELEMENT.length;if(ret=_extractCompName(src,i,",")){return"func"}continue}break}return null};Components.prototype._createStyleLookup=function(){var tag,o,scl,st;for(tag in this._tagLookup){o=this._tagLookup[tag];if(scl=o.styleClasses){for(st in scl){this._styleLookup[st]=tag}}}};Components.prototype._readComponentJson=function(inFile){var obj=null;if(this._isDebug){this._debug(` loading '${inFile}'`)}obj=this._nd.jsonLoader.load(inFile,this._nd,this._error,false,this._utils);if(!obj){this._isOk=false}return obj};Components.prototype._isComponentJsonPath=function(filePath){return filePath.toLowerCase().endsWith(COMPONENT_JSON)};Components.prototype.dumpComponentNames=function(){var names,keys;this._dumpComponentNames(this._tagLookup,"--------- Declared Web Components ---------","No valid user (non-VComponent) components declared!","-------- End Declared Web Components ---------");this._dumpComponentNames(this._VCompLookup,"--------- Discovered VComponents ---------","No VComponents found!","-------- End Discovered VComponents ---------");this._dumpComponentNames(this._jetTagLookup,"--------- Declared JET OJ-C Pack Web Components ---------","No valid user JET Core Pack components declared!","-------- End Declared OJ-C Pack Web Components ---------")};Components.prototype._dumpComponentNames=function(lookup,start,none,end){var keys,meta,impls;const INFO="[info]";keys=Object.keys(lookup);if(!keys.length){this._console(`${INFO} ${none}\n`,"I");return}this._console(`${INFO} ${start}`,"I");keys.forEach(key=>{meta=lookup[key];this._console(`${INFO} ${key} (${meta.version})`,"I");impls=meta.implements&&meta.implements.length?meta.implements.join(", "):"none declared";this._console(`${INFO} Impls: ${impls}`)});this._console(`${INFO} ${end}\n`,"I")};function _isTagStatusType(statType){return type===SUPERSEDES||type===MAINTENANCE||type===DEPRECATED||type===ANTIPATTERN};function _propToKebabCase(str){return str.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase()};function _propToCamelCase(str){var parts,i;function _camelCase(str){return str.replace(/(?:^\w|[A-Z]|\b\w)/g,function(word,index){return index==0?word.toLowerCase():word.toUpperCase()}).replace(/-|\s+/g,"")};parts=str.split(DOT);for(i=0;i<parts.length;i++){parts[i]=_camelCase(parts[i])}return parts.join(DOT)};function _isRelativeUrl(url){url=url.toLowerCase();return!(url.indexOf("http://")===0||url.indexOf("https://")===0)};function _removeChevrons(tagName){if(tagName){let len=tagName.length-1;let start=tagName.charAt(0)==="<"?1:0;let end=tagName.charAt(len)===">"?len:++len;tagName=tagName.substring(start,end)}return tagName};module.exports=Components;
|
|
6
|
+
"use strict";const COMPONENT_JSON="component.json";const PROPERTIES="properties";const PROP_SLOTS="slots";const PROP_DYNAMIC_SLOTS="dynamicSlots";const PROP_PROPS="props";const PROP_EVENTS="events";const PROP_STYLECLASSES="styleClasses";const PROP_IMPLEMENTS="implements";const PROP_REQUIRED="required";const PROP_FOLDER="folder";const PROP_VERSION="version";const PROP_UNSUP_THEME="unsupTheme";const PROP_STATUS="status";const PROP_SUBCOMPONENT_TYPE="subcomponentType";const PROP_DEPENDENCIES="dependencies";const PROP_TYPE="type";const PROP_PACK="pack";const PROPERTY_VALUE="propertyValue";const PROPERTY_TYPE="propertyType";const PACK_PRIVATE="packPrivate";const DEPRECATED="deprecated";const MAINTENANCE="maintenance";const SUPERSEDES="supersedes";const ANTIPATTERN="antiPattern";const DYNAMIC_FORM_ELEM="DynamicFormElement";const DYNAMIC_TABLE_ELEM="DynamicTableElement";const VB_FRAGMENT_ELEM="VbFragmentElement";const CUSTOM_ELEMENT="@customElement";const REGISTER_CUSTOM_ELEMENT="registerCustomElement";const OJ_C="oj-c";const DOT=".";const CHANGED="Changed";const FT_HTML="html";const FT_TSX="tsx";const REGXPR=/string|number|object|array|boolean|[\|.<>]/gi;function Components(nd,runMode,cwd,compSvcs,urlBase,urls,filePaths,metaLib,ojcPack,jetCore,runOpts,msgCtx,appCtx){this._nd=nd;this._tagLookup={};this._jetTagLookup={};this._VCompLookup={};this._styleLookup={};this._ignored={};this._maintenance=null;this._supersedes=null;this._antiPattern=null;this._meta={};this._path=null;this._reqAttrs=null;this._metaLib=metaLib;this._ojcPack=ojcPack;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._tsUtils=appCtx.tsUtils;this._curFileType=null;this._oConfig=appCtx.config;this._VFilesInspected=null;this._VTypes=null;this._compSvcs=compSvcs;this._isAMD=runMode==="amd";this._cwd=cwd;this._error=msgCtx.error;this._warn=msgCtx.warn;this._debug=msgCtx.debug;this._info=msgCtx.info;this._msg=msgCtx.msg;this._console=msgCtx.console;this._jafMsg=msgCtx.jafMsg;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._count=0;this._isOk=true;this._runOpts=runOpts;this._init(urlBase,urls,filePaths,jetCore);if(this._tsUtils){this._initVComponents()}};Components.prototype.isUserTag=function(tagName){var tag=_removeChevrons(tagName);return!!(this._tagLookup[tag]||this._VCompLookup[tag])};Components.prototype.isJetCoreTag=function(tagName){return!!this._jetTagLookup[_removeChevrons(tagName)]};Components.prototype.isVComponentTag=function(tagName){return!!this._VCompLookup[_removeChevrons(tagName)]};Components.prototype.isKnownTag=function(tagName){return!!this._lookupTag(tagName)};Components.prototype._lookupTag=function(tagName){tagName=_removeChevrons(tagName);return this._jetTagLookup[tagName]||this._tagLookup[tagName]||this._VCompLookup[tagName]};Components.prototype.isTagAttr=function(tagName,attrName){return this.isTagProp(tagName,attrName)||this.isJetTagProp(tagName,attrName)};Components.prototype.isJetTagAttr=function(tagName,attrName){return this.isJetTagProp(tagName,attrName)};Components.prototype.isTagDeprecated=function(tag){var comp,stats,status,ret=null;if(comp=this._lookupTag(_removeChevrons(tag))){if(stats=comp.status){for(status of stats){if((!status.type||status.type===DEPRECATED)&&!status.hasOwnProperty("target")){ret=status;if(ret.description){ret.description=this._utils.removeLink(ret.description)}break}}}}return ret};Components.prototype.isTagAttrDeprecated=function(tagName,attrName){var prop,status,stats,o,ret=null;if((prop=this.getAnyTagProp(tagName,attrName))&&(stats=prop.status)){ret=[];for(status of stats){if(!status.type||status.type===DEPRECATED){o={type:DEPRECATED};if(status.hasOwnProperty("target")){o.target=status.target}if(status.hasOwnProperty("description")){o.description=status.description}if(status.hasOwnProperty("since")){o.since=status.since}if(status.hasOwnProperty("value")){o.value=status.value}ret.push(o)}}ret=ret.length?ret:null}return ret};Components.prototype.isTagEventDeprecated=function(tagName,eventName){var event,stats,ret=null;if(event=this.getAnyTagEvent(tagName,eventName)){if(stats=event.status){stats.forEach(stat=>{if(!stat.type||stat.type===DEPRECATED){if(!ret){ret=[]}ret.push(stat)}})}}return ret};Components.prototype.getTagPropertyFromEvent=function(tagName,eventName){var o,ret;if(o=this.getTagEventName(tagName,eventName)){ret=o.name}return ret?ret:null};Components.prototype.isTagAttrTranslatable=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.translatable};Components.prototype.isTagAttrReadOnly=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.readonly};Components.prototype.isTagAttrWriteback=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.writeback};Components.prototype.isTagProp=function(tagName,propName){return!!this.getTagProp(tagName,propName)};Components.prototype.isJetTagProp=function(tagName,propName){return!!this.getJetTagProp(tagName,propName)};Components.prototype.getTagProp=function(tagName,propName){var ret;if(this.isUserTag(tagName)){ret=this._getTagProp(tagName,propName,false)}return ret?ret:null};Components.prototype.getJetTagProp=function(tagName,propName){var ret;if(this.isJetCoreTag(tagName)){ret=this._getTagProp(tagName,propName,true)}return ret?ret:null};Components.prototype.getAnyTagProp=function(tagName,propName){return this._getTagProp(tagName,propName,true)||this._getTagProp(tagName,propName,false)};Components.prototype._getTagProp=function(tagName,propName,isOJC){var tag,props,list;tagName=_removeChevrons(tagName);if(isOJC){tag=this._jetTagLookup[tagName]}else{tag=this._tagLookup[tagName]||this._VCompLookup[tagName]};props=tag?tag[PROP_PROPS]:null;if(props){propName=propName.charAt(0)===":"?propName.substring(1):propName;if(this._curFileType!=="tsx"){propName=_propToCamelCase(propName)}}return props?props[propName]:null};Components.prototype.getTagPropType=function(tagName,propName){var prop,ret;if(prop=this.getTagProp(tagName,propName)){ret=prop?prop.type:undefined}return ret};Components.prototype.getAnyTagEvent=function(tag,event){return this._getTagEvent(tag,event,true)||this._getTagEvent(tag,event,false)};Components.prototype._getTagEvent=function(tagName,eventName,isOJC){var tagObj,events,event;if(!eventName.startsWith("on")){return null}tagName=_removeChevrons(tagName);if(isOJC){tagObj=this._jetTagLookup[tagName]}else{tagObj=this._tagLookup[tagName]||this._VCompLookup[tagName]}if(!tagObj){return null}if(!(events=tagObj[PROP_EVENTS])){return null}if(eventName.includes("-")){eventName=eventName.substring(3);eventName=_propToCamelCase(eventName)}else{eventName=eventName.substring(2)}event=events[eventName];return event?event:null};Components.prototype.getComponentPropMetadata=function(tagName,propName){var comp,sofar,props;tagName=_removeChevrons(tagName);if(!(comp=this._meta[tagName])||!(props=comp.properties)){return null}let subprops=propName.split(DOT);if(this._curFileType===FT_HTML){subprops.forEach((subprop,i,ar)=>{ar[i]=_propToCamelCase(subprop)})}if(subprops.length===1){return props[propName]||null}sofar=comp;let nextprop,i;for(i=0;i<subprops.length;i++){nextprop=subprops[i];if(sofar.hasOwnProperty(PROPERTIES)){sofar=sofar.properties[nextprop]||null;if(!sofar){break}}else{sofar=null;break}}return sofar};Components.prototype.getComponentMetadata=function(tag){return this._meta[tag]||null};Components.prototype.getAllCustomMetadata=function(){var name,comp,obj;var ret={};var i=2;var lookup=this._tagLookup;while(i){for(name in lookup){ret[name]=obj={};comp=lookup[name];obj.folder=comp.folder;obj.json=this.getComponentMetadata(name);if(i===1){obj.VCType=this._VTypes[name]}}i--;lookup=this._VCompLookup}return ret};Components.prototype.getJetTag=function(tag){var o;return(o=this._jetTagLookup[tag])?o:null};Components.prototype.getMaintenanceTags=function(){return this._maintenance};Components.prototype.isTagEvent=function(tagName,eventName){return!!this.getTagEventName(tagName,eventName)};Components.prototype.getTagEventName=function(tagName,eventName){var propName,tagObj,events,impls;tagObj=this._lookupTag(_removeChevrons(tagName));if(!tagObj||!eventName.startsWith("on")){return null}if(eventName.includes("-")){eventName=eventName.substring(3);eventName=_propToCamelCase(eventName)}else{eventName=eventName.substring(2)}if(tagObj.events&&tagObj.events[eventName]){return{type:"event",name:eventName}}if((impls=tagObj.implements)&&(impls.includes(DYNAMIC_FORM_ELEM)||impls.includes(DYNAMIC_TABLE_ELEM)||impls.includes(VB_FRAGMENT_ELEM))){return{type:"dynamic",name:eventName}}if(eventName.endsWith(CHANGED)&&tagObj.props){propName=eventName.replace(CHANGED,"");if(tagObj.props[propName]){return{type:"property",name:propName}};}return null};Components.prototype.isTagStyle=function(tag,style){var tagObj,ret=false;if(tagObj=this._lookupTag(_removeChevrons(tag))){let styles;if(styles=tagObj.styleClasses){ret=!!styles[style]}}return ret};Components.prototype.isJetStyle=function(style){var tag,ret=false;if(tag=this._styleLookup[style]){ret=!!this._jetTagLookup[tag]}return ret};Components.prototype.isStyle=function(style){return!!this._styleLookup[style]};Components.prototype.getStyleMetadata=function(style){var tag,styles,sc,ret=null;if(tag=this._styleLookup[style]){if(styles=this._tagLookup[tag].styleClasses){if(sc=styles[style]){ret={tag:tag,meta:sc}}}}return ret};Components.prototype.getStyleSelector=function(style){var sm=this.getStyleMetadata(style);return sm&&sm.meta?sm.meta.styleSelector:null};Components.prototype.hasTagSlotName=function(tagName,slotName){var o=this._lookupTag(_removeChevrons(tagName));return!!(o&&o.slots&&o.slots[slotName])};Components.prototype.getPreferredSlotContent=function(tag,slotName,impls){var o,slot,prefContent=null,comps=null,content;if(this._utils.hasAnyProps(impls)){if(o=this._lookupTag(_removeChevrons(tag))){if(o.slots){slotName=slotName?slotName:"";if(slot=o.slots[slotName]){if((prefContent=slot.preferredContent)&&prefContent.length){prefContent.forEach(impl=>{if(content=impls[impl]){if(!comps){comps=[]}comps.push(...content)}})}else{prefContent=null}}}}}return prefContent||comps?{interfaces:prefContent,components:comps}:null};Components.prototype.getTagSlotMetadata=function(tag,slot){var o,ret;if(o=this._lookupTag(_removeChevrons(tag))){if(o.slots){slot=slot?slot:"";if(slot=o.slots[slot]){ret=slot}}}return ret};Components.prototype.hasTagDynamicSlot=function(tag){var o,ret=false;if(o=this._lookupTag(_removeChevrons(tag))){ret=o.hasOwnProperty(PROP_DYNAMIC_SLOTS)}return ret};Components.prototype.hasTagAttrValues=function(tagName,attrName){var prop,ret=false;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){ret=!!prop.enumValues}return ret};Components.prototype.isTagAttrValue=function(tagName,attrName,value){var prop,ret;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){if(prop&&prop.enumValues){ret=prop.enumValues.indexOf(value)>=0}}return!!ret};Components.prototype.isTagAttrEnumDeprecated=function(tag,attr,val){var prop,stats,status,ret=null;if(prop=this.getAnyTagProp(tag,attr)){if(stats=prop.status){for(status of stats){if((!status.type||status.type===DEPRECATED)&&status.target===PROPERTY_VALUE){if(status.value&&status.value.includes(val)){ret={type:DEPRECATED};if(status.hasOwnProperty("target")){ret.target=status.target}if(status.hasOwnProperty("description")){ret.description=status.description}if(status.hasOwnProperty("since")){ret.since=status.since}if(status.hasOwnProperty("value")){ret.value=status.value}break}}}}}return ret};Components.prototype.isTagSupportedInTheme=function(tag,theme){var o,unsup,ret=true;if(o=this._lookupTag(tag)){if(unsup=o[PROP_UNSUP_THEME]){ret=!unsup.includes(theme)}}return ret};Components.prototype.isAttrSupportedInTheme=function(tag,attr,theme){var prop,unsup,ret=true;if(prop=this.getAnyTagProp(tag,attr)){if(unsup=prop[PROP_UNSUP_THEME]){ret=!unsup.includes(theme)}}return ret};Components.prototype.isTagPackPrivate=function(tag){var o,ret;if(o=this._lookupTag(_removeChevrons(tag))){ret=o[PROP_SUBCOMPONENT_TYPE]===PACK_PRIVATE}return ret};Components.prototype.getSubcomponentType=function(tag){var o,ret;if(o=this._lookupTag(_removeChevrons(tag))){ret=o[PROP_SUBCOMPONENT_TYPE]}return ret||null};Components.prototype.getRequiredProps=function(tagName){var tag,props,prop,propName,obj,ret=null;tagName=_removeChevrons(tagName);if(this._reqAttrs){let r=this._reqAttrs[tagName];if(r){return typeof r==="boolean"?null:r}}tag=this._lookupTag(tagName);if(tag&&tag.props){if(!this._reqAttrs){this._reqAttrs={}}if(!this._reqAttrs[tagName]){this._reqAttrs[tagName]=true}props=tag.props;for(propName in props){prop=props[propName];if(prop.required){if(!obj){obj=[]}obj.push(propName)}}}if(obj&&obj.length){let i,j,p;for(i=0;i<obj.length;i++){if(p=obj[i]){p+=".";for(j=i+1;j<obj.length;j++){if(obj[j].startsWith(p)){obj.splice(i,1);i--;break}}}}this._reqAttrs[tagName]=obj;ret=obj}return ret};Components.prototype.getRequiredAttrs=function(tagName){return this.getRequiredProps(tagName)};Components.prototype.getInterfaces=function(tag){var o,ret;if(o=this._lookupTag(_removeChevrons(tag))){ret=o.implements}return ret?ret:null};Components.prototype.getCount=function(){return this._count};Components.prototype.isTagStatus=function(tag,statType){return!!this._getTagStatus(tag,statType)};Components.prototype.getTagStatus=function(tag,statType){var ret=null,omitted=statType===undefined;var comp,arStat,stat,stType,i;if(comp=this._lookupTag(_removeChevrons(tag))){if(arStat=comp.status){for(i=0;i<arStat.length;i++){stat=arStat[i];stType=stat.type||DEPRECATED;if(omitted||stType===statType){if(!ret){ret=[]}ret.push(stat)}}}}return ret};Components.prototype.getPropStatus=function(tagName,propName,statType){let comp,arStat,ret;if(comp=this._lookupTag(_removeChevrons(tagName))){if(comp.props&&(arStat=comp.props[propName]?.status)){let stat,stType,i,omitted=statType===undefined;for(i=0;i<arStat.length;i++){stat=arStat[i];stType=stat.type||DEPRECATED;if(omitted||stType===statType){if(!ret){ret=[]}ret.push(stat)}}}}return ret?ret:null};Components.prototype.isRuleIgnored=function(compName,ruleName){var ret,ar;if(ar=this._ignored[compName]){ret=ar.includes(ruleName)}return!!ret};Components.prototype.isOk=function(){return this._isOk};Components.prototype.setCurFileType=function(ft){this._curFileType=ft};Components.prototype._init=function(base,urls,filePaths,jetCore){if(this._isAMD){this._processJetCorePack();return}if(base){base=base.trim();if(base.charAt(base.length-1)!=="/"){base=base+"/"}}else{base=""}this._processFilePaths(filePaths);this._processUrls(base,urls);this._processJetCorePack();this._createStyleLookup();this._processJetCore(jetCore)};Components.prototype._processFilePaths=function(filePaths){var obj,compEntry,fpath,i,j;if(!filePaths){return}this._console("\nPre-processing user-declared web component metadata...");for(i=0;i<filePaths.length;i++){compEntry=filePaths[i];var dirStack=this._nd.glob.sync(compEntry);for(j=0;j<dirStack.length;j++){fpath=dirStack[j];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg="-".repeat(70)+"\n"+(this._runOpts.isDryRun?"* ":"")+"processing component path '"+fpath+"' ...";if(this._runOpts.isDryRun){console.log(msg)}else{this._debug(msg)}}if(fpath.toLowerCase().endsWith(".zip")){obj=this._compSvcs._extractComponentJsonFromZip(fpath);if(obj.obj){this.processComponentJson(obj.obj,fpath)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+fpath)}else if(obj.error){this._error("Failed to unzip '"+fpath+"'")}continue}if(this._isComponentJsonPath(fpath)){if(obj=this._readComponentJson(fpath)){if(obj.type&&obj.type==="pack"){continue}this.processComponentJson(obj,this._nd.path.dirname(fpath))}continue}this._recurse(fpath)}}if(this._isDebug){this._debug("-".repeat(70))}};Components.prototype._recurse=function(fpath){var dirs,inFile,obj,i;try{dirs=this._nd.fs.readdirSync(fpath);if(this._isDebug){this._debug(` processing ${fpath} ${dirs.length} component dirs ...`)}for(i=0;i<dirs.length;i++){inFile=dirs[i];if(inFile===COMPONENT_JSON){inFile=this._nd.path.join(fpath,COMPONENT_JSON);if(this._isDebug){this._debug(" processing "+inFile+"...")}obj=this._readComponentJson(inFile);if(obj){if(!obj.type||obj.type==="composite"){this.processComponentJson(obj,fpath)}}else{return}}var curPath=this._nd.path.join(fpath,inFile);if(this._fsUtils.getFileType(curPath)==="d"){this._recurse(curPath)}}}catch(e){this._error("Component check failed - "+e);this._isOk=false}};Components.prototype._processUrls=function(base,urls){var url,i;if(!urls){return}for(i=0;i<urls.length;i++){url=urls[i];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg;msg="-".repeat(70)+"\nprocessing URL '"+url+"'";if(this._runOpts.isDryRun){console.log(msg);continue}else{this._debug(msg)}}if(_isRelativeUrl(url)){url=base+url;if(_isRelativeUrl(url)){this._error("component URL incomplete - '"+url+"'");continue}}this._processUrl(url)}};Components.prototype._processUrl=function(url){var resp,obj,rc,tempFile,tmp;try{resp=this._compSvcs.loadUrl(url);if(resp.eCode==="ETIMEDOUT"){this._error("config.componentUrls - request timed-out for '"+url+"'");this._isOk=false;return}try{if(resp.type==="json"){if(resp.body){obj=JSON.parse(resp.body);if(!this.processComponentJson(obj,url)){this._isOk=false}}else{this._error("Server responded with "+resp.statusCode+" URL: '"+url+"'")}}else if(resp.type=="zip"){rc=this._compSvcs.writeZipBufferToFile(resp.body);if(typeof rc==="boolean"&&rc){tempFile=this._compSvcs.getLastZipFilePath();obj=this._compSvcs.extractComponentJsonFromZip(tempFile);if(obj.obj){this.processComponentJson(obj.obj,url)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+url)}else if(obj.error){this._error("Failed to unzip '"+url+"'")}this._compSvcs.deleteZipFile(tempFile)}else{this._error("Failed to create local temp zip file from URL '"+url+"' : rc.message");this._isOk=false}}else{tmp=typeof resp.type==="string"?resp.type:"?";this._error("Server responded with unexpected data ('"+tmp+"') : '"+url+"'");this._isOk=false}}catch(e){this._error("Invalid JSON - URL '"+url+"' : "+e);this._isOk=false}}catch(e1){this._error("URL access failed "+(e1.message.includes("ENOTFOUND")?"(NOT FOUND)":"")+" - URL '"+url+"'");this._isOk=false}};Components.prototype._processJetCorePack=function(){var comps,comp;if(comps=this._ojcPack.getComponents()){for(comp in comps){this.processComponentJson(comps[comp],"oj-c")}}};Components.prototype.processComponentJson=function(obj,fromLocation,vcomp){var comp,props,events,event,eventName,compName,metaObj;var isOJC;compName=obj.pack?obj.pack+"-"+obj.name:obj.name;isOJC=obj.pack===OJ_C;if(!this._isAMD){if(this._runOpts.isDryRun){console.log(" Would have processed '"+fromLocation+"'");return}if(obj.type&&obj.type==="pack"){return this._processJetPack(obj,fromLocation)}if(!isOJC&&!vcomp){if(!this._compSvcs.validateComponentJson(obj,fromLocation)){this._isOk=false;return false}}}if(this._lookupTag(compName)){this._jafMsg("jaf-sys-dup-component",`Ignoring duplicate component '${compName}' at '${fromLocation}'`,"W");return true}this._meta[compName]=obj;(isOJC?this._jetTagLookup:vcomp?this._VCompLookup:this._tagLookup)[compName]=comp={};comp[PROP_FOLDER]=fromLocation;comp[PROP_VERSION]=obj.version;if(obj.extension&&obj.extension.audit&&obj.extension.audit.ignore){let ar;if((ar=obj.extension.audit.ignore)&&ar.length){this._ignored[compName]=[...ar]}}if(obj.hasOwnProperty(PROP_SLOTS)){comp[PROP_SLOTS]=obj[PROP_SLOTS]}if(obj.hasOwnProperty(PROP_DYNAMIC_SLOTS)){comp[PROP_DYNAMIC_SLOTS]=obj[PROP_DYNAMIC_SLOTS]}if(obj.properties){comp[PROP_PROPS]=props={};this._extractProps(props,null,obj.properties,obj.name)}if(obj.events){comp[PROP_EVENTS]=events={};for(event in obj.events){events[event]=obj.events[event];metaObj=obj.events}}if(obj.implements){comp[PROP_IMPLEMENTS]=obj.implements;this._metaLib.processImplements(compName,obj.implements)}if(obj.status){let status,i;metaObj=obj.status;for(i=0;i<metaObj.length;i++){status=metaObj[i];if(status.type===MAINTENANCE){if(!this._maintenance){this._maintenance=new Set}this._maintenance.add(compName)}else if(status.type===SUPERSEDES){if(!this._supercedes){this._supersedes=new Set}this._supersedes.add(compName)}else if(status.type===ANTIPATTERN){if(!this._antiPattern){this._antiPattern=new Set}this._antiPattern.add(compName)}}}if(obj.extension&&obj.extension.theme&&obj.extension.theme.unsupportedThemes){comp[PROP_UNSUP_THEME]=obj.extension.theme.unsupportedThemes}if(obj.hasOwnProperty(PROP_SUBCOMPONENT_TYPE)){comp[PROP_SUBCOMPONENT_TYPE]=obj[PROP_SUBCOMPONENT_TYPE]}if(obj.hasOwnProperty(PROP_DEPENDENCIES)){comp[PROP_DEPENDENCIES]=obj[PROP_DEPENDENCIES]}if(obj.type){comp[PROP_TYPE]=obj.type}if(obj.pack){comp[PROP_PACK]=obj.pack}if(obj.hasOwnProperty("required")){comp[PROP_REQUIRED]=obj.required}if(obj.status){comp[PROP_STATUS]=obj.status}if(obj.styleClasses){comp[PROP_STYLECLASSES]=this._extractStyles(obj.styleClasses)}this._count++;return true};Components.prototype._extractProps=function(propObj,propSoFar,properties,name,rdonly){var prop,thisProp,soFar,obj;for(prop in properties){soFar=(propSoFar?propSoFar+DOT:"")+prop;propObj[soFar]=obj={};thisProp=properties[prop];if(thisProp.hasOwnProperty("enumValues")){if(Array.isArray(thisProp.enumValues)){obj.enumValues=thisProp.enumValues}else{this._error(`Web component '${name}' property '${soFar}' has invalid 'enumValues' in component.json`)}}if(thisProp.hasOwnProperty("status")){obj.status=thisProp.status}if(thisProp.hasOwnProperty("type")){obj.type=thisProp.type}if(thisProp.required){obj.required=true}if(thisProp.extension&&thisProp.extension.theme&&thisProp.extension.theme.unsupportedThemes){obj[PROP_UNSUP_THEME]=thisProp.extension.theme.unsupportedThemes}if(thisProp.hasOwnProperty("translatable")){obj.translatable=true}if(typeof thisProp.readOnly==="boolean"){obj.readOnly=thisProp.readOnly}else{if(rdonly){obj.readOnly=true}}if(thisProp.hasOwnProperty("writeback")){obj.writeback=thisProp.writeback}if(thisProp.hasOwnProperty("properties")){obj.properties=true;this._extractProps(propObj,soFar,thisProp.properties,name,obj.readOnly)}}};Components.prototype._extractStyles=function(styleClasses){var so,si,obj,ret={},i,j;if(!Array.isArray(styleClasses)){return ret}for(i=0;i<styleClasses.length;i++){so=styleClasses[i];if(so.kind==="class"){ret[so.name]=this._extractStyleClass(so)}else if(so.kind==="set"&&so.styleItems&&Array.isArray(so.styleItems)){ret[so.name]=obj={kind:"set"};if(so.status){obj.status=so.status}obj.styleClasses={};for(j=0;j<so.styleItems.length;j++){si=so.styleItems[j];obj.styleClasses[si.name]=this._extractStyleClass(si)}}else if(so.kind==="template"){}}return ret};Components.prototype._extractStyleClass=function(so){var obj={};if(so.styleSelector){obj.styleSelector=so.styleSelector}if(so.status){obj.status=so.status}return obj};Components.prototype._processJetPack=function(obj,fromLocation){var deps,dep,urlKey,depUrl,msg,i;if(this._runOpts.isDryRun||this._runOpts.isDebug){msg="processing JET Pack "+obj.name+" (version: "+obj.version+") : '"+fromLocation+"'";if(this._runOpts.isDryRun){console.log("* "+msg);return}else{this._debug(msg)}}if(!fromLocation.includes("http")){this._error("JET packs loaded via config 'components' property (file based) are currently not supported");return false}i=fromLocation.indexOf(obj.name);if(i>=0){urlKey=fromLocation.substring(0,i)}else{this._error("Cannot handle Jet Pack URL format to load dependencies : "+fromLocation)}deps=obj.dependencies;if(deps){for(dep in deps){depUrl=urlKey+dep+"/versions/"+obj.dependencies[dep]+"/content/component.json";if(this._isDebug){this._debug(` processing dependency ${dep} ${obj.dependencies[dep]}`)}this._processUrls("",[depUrl])}}return false};Components.prototype._processJetCore=function(jetCorePath){var files,file,obj,i;if(!jetCorePath){return}this._console("-".repeat(70)+"\nPerforming schema analysis on JET Core components (dt) using '"+this._compSvcs.getSchemaName()+"'...");try{files=this._nd.fs.readdirSync(jetCorePath);this._console(` processing ${files.length} $jetCore components...`);for(i=0;i<files.length;i++){file=files[i];if(file.endsWith(".json")){file=this._nd.path.join(jetCorePath,file);try{obj=this._readComponentJson(file);if(obj){this._compSvcs.validateComponentJson(obj,file)}}catch(e){}}}}catch(e1){this._error("!!! $JetCore Component check failed - "+e1)}this._console(" processing "+(files?files.length+" ":"")+"$jetCore components completed");this._console("-".repeat(70))};Components.prototype._initVComponents=function(){let precompileCache,tscript;const preComp=this._tsUtils.getPreCompiler();const preCompUtils=this._tsUtils.getUtils();const auditBase=this._fsUtils.toJAFPath(this._oConfig.getBase());const projectPathInfo=preCompUtils.getKeyPathInfo(auditBase);if((tscript=this._oConfig.getTypescript())&&tscript.compile&&projectPathInfo.tsSource){this._console("Pre-processing VComponents...");if(!(precompileCache=preComp.getPrecompileCache(auditBase,projectPathInfo.tsSource,projectPathInfo.componentRootFolder))){return}if(!this._fsUtils.pathExistsSync(precompileCache)){this._debug(`VComponents: precompileCache not created - ${precompileCache}`)}else{this._getVComponentJson(precompileCache)}}};Components.prototype._getVComponentJson=function(jsonDir){var contents;if(contents=this._fsUtils.readDirSync(jsonDir)){let json;this._VFilesInspected=[];this._VTypes={};contents.forEach(file=>{if(file.isFile){json=this._fsUtils.readJsonSync(this._nd.path.join(jsonDir,file.name),false,false);if(typeof json==="string"){this._error(`Compiled metadata for x - ${json}`)}else{if(this._isDebug){this._debug(`Post compilation VComponent found : ${json.name}`)}this.processComponentJson(json,this._getVCompFolder(json.name),true)}}});this._VFilesInspected=null}};Components.prototype._getVCompFolder=function(name){var files,file,folder,ret=null,x,_self=this;const preComp=this._tsUtils.getPreCompiler();const srcFiles=preComp.getVFiles();if(srcFiles){for(file of srcFiles){if(this._VFilesInspected.includes(file)){continue}let src,VType;function _fail(errMsg){_self._warn(`Unexpected read error of '${file}'`)}if(!(src=this._fsUtils.readFileSync(file,_fail))){continue}if(!(VType=this._isVCompSrc(src,name))){continue}this._VFilesInspected.push(file);this._VTypes[name]=VType;ret=this._nd.path.dirname(file);break}}return ret};Components.prototype._isVCompSrc=function(src,name){var ret,start=0,utils=this._utils;function _extractCompName(data,x,closeDelim){let x2,comp,match=false;if((x=utils.eatWhitespace(data,x))>=0){if(data.charAt(x)==="("){if((x=utils.eatWhitespace(data,x+1))>=0){if((x2=data.indexOf(closeDelim,x))>=0){comp=data.substring(x,x2).trim();comp=comp.substring(1,comp.length-1);match=comp===name}}}}return match}while(start<src.length){let i;if((i=src.indexOf(CUSTOM_ELEMENT,start))>=0){start=i+=CUSTOM_ELEMENT.length;if(ret=_extractCompName(src,i,")")){return"class"}continue}else if((i=src.indexOf(REGISTER_CUSTOM_ELEMENT,start))>=0){start=i+=REGISTER_CUSTOM_ELEMENT.length;if(ret=_extractCompName(src,i,",")){return"func"}continue}break}return null};Components.prototype._createStyleLookup=function(){var tag,o,scl,st;for(tag in this._tagLookup){o=this._tagLookup[tag];if(scl=o.styleClasses){for(st in scl){this._styleLookup[st]=tag}}}};Components.prototype._readComponentJson=function(inFile){var obj=null;if(this._isDebug){this._debug(` loading '${inFile}'`)}obj=this._nd.jsonLoader.load(inFile,this._nd,this._error,false,this._utils);if(!obj){this._isOk=false}return obj};Components.prototype._isComponentJsonPath=function(filePath){return filePath.toLowerCase().endsWith(COMPONENT_JSON)};Components.prototype.dumpComponentNames=function(){var names,keys;this._dumpComponentNames(this._tagLookup,"--------- Declared Web Components ---------","No valid user (non-VComponent) components declared!","-------- End Declared Web Components ---------");this._dumpComponentNames(this._VCompLookup,"--------- Discovered VComponents ---------","No VComponents found!","-------- End Discovered VComponents ---------");this._dumpComponentNames(this._jetTagLookup,"--------- Declared JET OJ-C Pack Web Components ---------","No valid user JET Core Pack components declared!","-------- End Declared OJ-C Pack Web Components ---------")};Components.prototype._dumpComponentNames=function(lookup,start,none,end){var keys,meta,impls,isOJC=start.includes("OJ-C");const INFO="[info]";keys=Object.keys(lookup);if(!keys.length){this._console(`${INFO} ${none}\n`,"I");return}this._console(`${INFO} ${start}`,"I");if(isOJC&&this._isVerbose){this._console(`${INFO} ${keys.length} JET CorePack components loaded`,"I")}else{keys.forEach(key=>{meta=lookup[key];this._console(`${INFO} ${key} (${meta.version})`,"I");impls=meta.implements&&meta.implements.length?meta.implements.join(", "):"none declared";this._console(`${INFO} Impls: ${impls}`)})}this._console(`${INFO} ${end}\n`,"I")};function _isTagStatusType(statType){return type===SUPERSEDES||type===MAINTENANCE||type===DEPRECATED||type===ANTIPATTERN};function _propToKebabCase(str){return str.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase()};function _propToCamelCase(str){var parts,i;function _camelCase(str){return str.replace(/(?:^\w|[A-Z]|\b\w)/g,function(word,index){return index==0?word.toLowerCase():word.toUpperCase()}).replace(/-|\s+/g,"")};parts=str.split(DOT);for(i=0;i<parts.length;i++){parts[i]=_camelCase(parts[i])}return parts.join(DOT)};function _isRelativeUrl(url){url=url.toLowerCase();return!(url.indexOf("http://")===0||url.indexOf("https://")===0)};function _removeChevrons(tagName){if(tagName){let len=tagName.length-1;let start=tagName.charAt(0)==="<"?1:0;let end=tagName.charAt(len)===">"?len:++len;tagName=tagName.substring(start,end)}return tagName};module.exports=Components;
|
package/lib/ConfigEx.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 GROUPS=require("./groups");const DEFAULTS=require("./defaults");const SemVer=require("semver");const COMPOSITES="jet-composites";const TYPE_STRING="string";const TYPE_BOOLEAN="boolean";const AUTO="auto";const ERRORS="errors";const UNDEF="undefined";const NUMBER="number";const TOP_PROPS=["rulePacks","ruleMods","ruleDiscriminant","builtinJetRules","builtinCspRules","builtinSpocRules","builtinJetWcRules","builtinJetWcOracleRules","builtinOjcMigrationRules","builtinWebDriverTestRules","severity","groups","defGroups","ruleNames","base","files","exclude","typescript","jetPagesOnly","format","proseFormat","lineFormat","outPath","tabs","messages","addFileList","title","jetVer","components","componentUrls","componentOptions","jetCorePack","markdownOptions","stylesets","ecmaVer","ruleDescriptions","rulesFired","userDefs","options","comments","extends","extendOptions","nameSpaces","followLinks","tempDir","tokens","common","$JetCore","sevMap","theme","ojet","appendFileList"];const NOT_AMD=["addFileList","base","builtinJetWcRules","builtinJetWcOracleRules","builtinOjcMigrationRules","builtinWebDriverTestRules","components","componentOptions","componentUrls","extendOptions","files","exclude","followLinks","outPath","rulePacks","tempDir","tokens","typescript"];const OPTIONS_PROPS=["debug","verbose","color","msgid","ruleName","retCode","rc","ojetUpdate","experimental","$unittest"];const THEMES=["redwood","alta","stable","none"];const DEF_COMMENTS=false;const DEF_RULE_DESCRIPT="none";const DEF_GROUPS=["all"];const DEF_RETCODE="auto";const ISSUE_TAG="issueTag";const ECMA_VER=[5,6,7,8,9,10,11,12,13,14];const ECMA_YEAR=[-1,2015,2016,2017,2018,2019,2020,2021,2022,2023];function CfgEx(oConfig,nodeDeps,sevLib,utils,fsUtils,msgCtx,modeCtx){this._oConfig=oConfig;this._config=null;this._dir=null;this._sevLib=sevLib;this._extends=null;this._utils=utils;this._fsUtils=fsUtils;this._nd=nodeDeps;this._msgCtx=msgCtx;this._modeCtx=modeCtx;this._isVerbose=msgCtx.isVerbose;this._isCLI=modeCtx.isCLI||modeCtx.isOJETCLI;this._error=msgCtx.error;this._warn=msgCtx.warn;this._info=msgCtx.info};CfgEx.prototype.setDebugStatus=function(verbose,debug){this._isVerbose=this._msgCtx.isVerbose=verbose};CfgEx.prototype.processWebComponents=function(){var dir,o,t,i;var config=this._config;if(config.componentUrlBase){if(!typeof config.componentUrlBase===TYPE_STRING){this._error("Config entry 'componentUrlBase' must be a string!");return false}}if(config.componentUrls){if(typeof config.componentUrls===TYPE_STRING){config.componentUrls=[config.componentUrls]}else if(!Array.isArray(config.componentUrls)){this._error("Config entry 'componentUrls' must be a string or an aray of strings!");return false}for(i=0;i<this._config.componentUrls.length;i++){config.componentUrls[i]=config.componentUrls[i].trim();if(config.componentUrls[i].length===0){config.componentUrls.splice(i,1);i--}}}if(!config.components){if(this._isCLI&&!this._isOJET&&this._experimentalSet){dir=this._findCompositesDir(config.base);if(dir){config.components=[];config.components.push(this._nd.path.join(dir,COMPOSITES))}}}if(config.components){if(typeof config.components===TYPE_STRING){config.components=[config.components]}else if(!Array.isArray(config.components)){this._error("Config entry 'components' must be a string or an array of strings!");return false}for(i=0;i<config.components.length;i++){config.components[i]=config.components[i].trim();if(config.components[i].length===0){config.components.splice(i,1);i--}}}if(config.components&&config.components.length||config.componentUrls&&config.componentUrls.length){o=config.componentOptions;if(o){if(!this._utils.isObject(o)){this._error("Config 'components' sub-property 'componentOptions' must be an Object!");return false}t=typeof o.applySchema;if(t==="undefined"){o.applySchema=true}else if(t!=="boolean"){this._error("Config 'components' sub-property 'componentOptions' must be an Object!");return false}}}return true};CfgEx.prototype.processJetCorePack=function(){var config=this._config;var ret=true;if(!config.hasOwnProperty("jetCorePack")){return ret}let t=typeof config.jetCorePack;if(t===TYPE_BOOLEAN){if(config.jetCorePack){this._error("Config 'jetCorePack' property value cannot be boolean true!");ret=false}return ret}if(SemVer.lt(config.jetVer,"13.0.0")){this._error("Config 'jetCorePack' is valid for 'jetVer' values >= 13.0.0 only");ret=false}if(t!==TYPE_STRING){this._error("Config 'jetCorePack' property is not a string or a boolean!");ret=false}return ret};CfgEx.prototype.processTypeScript=function(){var ts,ret=true;if(this._config.hasOwnProperty("typescript")){ts=this._config.typescript;if(!this._utils.isObject(ts)){this._error("Config 'typescript' property is not an object!");ret=false}if(ts.hasOwnProperty("compile")){if(typeof ts.compile!=="boolean"){this._error("Config 'typescript' sub-property 'compile' is not a boolean!");ret=false}}if(ts.hasOwnProperty("tsconfig")){if(typeof ts.tsconfig!=="string"){this._error("Config 'typescript' sub-property 'tsconfig' must be a directory string!");ret=false}}}return ret};CfgEx.prototype.processRulePacks=function(){var packs,pack,i;var config=this._config;if(config.rulePacks){packs=this._config.rulePacks;if(!Array.isArray(packs)){this._error("Config entry 'rulePacks' is not an array!");return false}for(i=0;i<packs.length;i++){pack=packs[i];if(typeof pack!==TYPE_BOOLEAN){pack.enabled=true}if(!pack.path){this._error(`Config entry 'rulePacks' (entry ${i+1}) does not have a 'path' entry!`);return false}else{pack.path=pack.path.trim()}if(pack.status&&!Array.isArray(pack)){this._error(`Config entry 'rulePacks' (entry ${i+1}) 'status' property is not an array!`);return false}}}else{config.rulePacks=[]}return true};CfgEx.prototype.processRuleMods=function(cfg,fp){var mods,mod,val,rule;var config=cfg?cfg:this._config;const MSG="Config 'ruleMods' sub-property '${mod}' is not an array of rule names or group names";var self=this,b;if(!config.ruleMods){return true}function _emitRMError(s){s+=fp?` - in ${fp}`:"";self._error(s);b=true}mods=config.ruleMods;if(!this._utils.isObject(mods)){_emitRMError("Configuration property 'ruleMods' is not an object");return false}for(mod in mods){if(mod==="enabled"){_emitRMError("Config 'ruleMods' : invalid sub-property 'enabled' - did you mean 'enable'?")}else if(mod==="disabled"){_emitRMError("Config 'ruleMods' : invalid sub-property 'disabled' - did you mean 'disable'?")}if(b){return!b}val=mods[mod];if(mod==="enable"||mod==="disable"){if(!Array.isArray(val)){_emitRMError(this._utils.format(MSG,{mod:mod}))}if(!this._utils.isArrayContentsType(val,"string")){_emitRMError(this._utils.format(MSG,{mod:mod}))}}else{if(!this._utils.isObject(val)){_emitRMError(`Config 'ruleMods' sub-property '${mod}' is not an object!`)}else{for(rule in val){let o=val[rule];if(o.hasOwnProperty(ISSUE_TAG)){if(typeof o.issueTag!=="string"){_emitRMError(`Config 'ruleMods' for '${mod}' rule '${rule}' : '${ISSUE_TAG}' is not a string`)}}};}}}if(!b&&mods.enable&&mods.disable){mods.enable.forEach(function(r){if(mods.disable.includes(r)){_emitRMError(`Config 'ruleMods': 'enable' & 'disable' conflicting entry '${r}'`)}})}return!b};CfgEx.prototype.processFormat=function(){var config=this._config;if(config.format){if(config.format!=="json"&&config.format!=="prose"&&config.format!=="line"){this._error(`Config entry 'format' '${config.format}' not valid. Must be 'json', 'prose' or 'line'!`);return false}}return true};CfgEx.prototype.processProseFormat=function(){var config=this._config;if(config.proseFormat){if(typeof config.proseFormat==="string"){if(config.format!=="prose"){this._warn("Config entry 'proseFormat' ignored - not applicable if 'format is not 'prose'!")}}else{this._error(`Config entry 'proseFormat' '${config.proseFormat}' is not valid!`);return false}}return true};CfgEx.prototype.processLineFormat=function(){var config=this._config;if(config.lineFormat){if(typeof config.lineFormat==="string"){if(config.format!=="line"){this._warn("Config entry 'lineFormat' ignored - not applicable if 'format is not 'line'!")}}else{this._error(`Config entry 'lineFormat' '${config.lineFormat}' is not valid!`);return false}}return true};CfgEx.prototype.processRuleDescriptions=function(){var val,valType;var config=this._config;if(config.ruleDescriptions){val=config.ruleDescriptions;valType=typeof val;if(valType!=="string"||val!="all"&&val!=="short"&&val!=="long"&&val!=="none"){this._error(`Config entry 'ruleDescriptions' '${val}' is not valid!`);return false}}else{config.ruleDescriptions=DEF_RULE_DESCRIPT}return true};CfgEx.prototype.processRulesFired=function(){var config=this._config;if(config.rulesFired){if(!this._modeCtx.isAPI&&!this._modeCtx.isAMD&&(!config.format||config.format!=="json")){this._error(`Config entry 'rulesFired' - API/AMD mode required, or 'format' property set to 'json' for CLI mode!`);return false}}return true};CfgEx.prototype.processSevMap=function(){var config=this._config;var set,sev,msgs,inv,mapped,val,b,error;if(!config.sevMap){return true}set=config.sevMap.sevSet;if(set){b=error=false;for(val in set){if(!this._sevLib.isValidConfigSeverity(val)){this._error(`Config entry 'sevMap' sub-property 'sevSet' value '${val}' is not 'blocker/critical/major/minor/info'!`);error=true;continue}if(val==="all"){this._error("Config entry 'sevMap' sub-property 'sevSet' - pseudo severity 'all' cannot be remapped!");error=true;continue}if(typeof set[val]!=="string"){this._error(`Config entry 'sevMap' sub-property 'sevSet' value '${val}' is not a string!`);error=true;continue}b=true}if(error){return false}if(b){inv={};for(sev in set){mapped=set[sev];if(inv[mapped]){if(!Array.isArray(inv[mapped])){inv[mapped]=[inv[mapped]]}inv[mapped].push(sev)}else{inv[mapped]=sev}}this._sevLib.setSevMap(config.sevMap,inv)}else{config.sevMap.sevSet=null}}msgs=config.sevMap.sevMsg;if(msgs){if(!this._utils.isObject(msgs)){this._error("Config entry 'sevMap' sub-property 'sevMsg' is not an object!");return false}b=error=false;for(val in msgs){sev=msgs[val];if(typeof sev!=="string"){this._error(`Config entry 'sevMap' sub-property 'sevMsg' : '${val}' is not a string!`);error=true;continue}if(!this._sevLib.isSev(sev)){this._error(`Config entry 'sevMap' sub-property 'sevMsg' : '${sev}' is ${UNDEF}!`);error=true;continue}b=true}if(error){return false}if(b){this._sevLib.setSevMsg(msgs)}else{config.sevMap.sevMsg=null}}else{b=true;for(val in config.sevMap){if(val!=="sevSet"&&val!=="sevMsg"){this._error(`Config entry 'sevMap' unknown sub-property '${val}'!`);b=false}}if(!b){return false}}return true};CfgEx.prototype.processSeverity=function(cliSev){var config=this._config;var val,se,i;if(cliSev){config.severity=cliSev}if(config.severity){val=config.severity;if(typeof val==="string"){se=this._sevLib.getSevExpr(val);if(!this._sevLib.isValidConfigSeverity(val)){if(se.op&&se.sev==="all"){this._error(`Config entry 'severity' ('${val}') : 'all' cannot be used with a severity expression !`)}else if(cliSev){this._error(`command line --severity '${val}' is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`)}else{this._error(`Config entry 'severity' ('${val}') is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`)}return false}this._sevLib.setSevExpr(se)}else if(Array.isArray(val)&&this._utils.isArrayContentsType(val,"string")){for(i=0;i<val.length;i++){if(!this._sevLib.isValidConfigSeverity(val[i])){this._error(`Config entry 'severity' ('${val[i]}') is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`);return false}}}else{this._error("Config entry 'severity' is invalid!");return false}}else{config.severity=this._sevLib.ALL;this._sevLib.setSevExpr(this._sevLib.getSevExpr(this._sevLib.ALL))}return true};CfgEx.prototype.processGroups=function(cliGroups){var group,i;var config=this._config;if(cliGroups){config.groups=cliGroups}if(!config.groups){config.groups=DEF_GROUPS;return true}if(!Array.isArray(config.groups)){config.groups=[config.groups]}if(config.groups.length===0){config.groups.push("all")}else{for(i=0;i<config.groups.length;i++){group=config.groups[i];if(!GROUPS.isGroup(group)){if(group.startsWith("jet-")||group.startsWith("htm")){this._error(`Config 'groups' entry '${group}' is not defined!`);return false}}}}return true};CfgEx.prototype.processDefGroups=function(){var config=this._config;if(config.defGroups){if(!this._utils.isObject(config.defGroups)){this._error("Config entry 'defGroups' is not an object!");return false}}else{config.defGroups=null}return true};CfgEx.prototype.processRuleNames=function(){var config=this._config;if(config.ruleNames){if(!Array.isArray(config.ruleNames)){this._error("Config entry 'ruleNames' is not an array!");return false}}return true};CfgEx.prototype.processTheme=function(){var t,config=this._config;t=config.theme;if(t){t=t.toLowerCase();if(typeof t==="string"){if(!THEMES.includes(t)){this._error(`Invalid config theme '${t}' : must be 'Redwood', 'Alta', 'Stable' or 'none'`);return false}}else{this._error("Config entry 'theme' is not a string!");return false}if(t==="stable"){t="redwood"};config.theme=t.charAt(0).toUpperCase()+t.substring(1)}else{config.theme=SemVer.gte(config.jetVer,"12.0.0")?"Redwood":DEFAULTS.THEME;if(this._isVerbose){this._info(`[Info]: Default theme '${config.theme}' applied for jetVer ${config.jetVer}`)}}return true};CfgEx.prototype.processComments=function(){var t,config=this._config;t=typeof config.comments;if(t===UNDEF){config.comments=DEF_COMMENTS}else if(t!=="boolean"){this._error("Invalid 'comments' property - expected a boolean");return false}return true};CfgEx.prototype.processMarkdownOpts=function(){var config=this._config;var val=config.markdownOptions;var t=typeof val;if(t===UNDEF){config.markdownOptions={linkify:true}}else if(Array.isArray(val)||t!=="object"){this._error("Invalid 'markdownOptions' property - expected an object");return false}else{t=typeof val.linkify;if(t==="undefined"){val.linkify=true}else if(typeof val.linkify!=="boolean"){this._error("Invalid 'markdownOptions.linkify' - expected a boolean");return false}let n=Object.keys(val);if(!val.hasOwnProperty("linkify")){if(n.length){this._error("Invalid 'markdownOptions.linkify' - expected a boolean");return false}else{val.linkify=true}}else if(n.length>1){this._error("Invalid 'markdownOptions' properties found");return false}}return true};CfgEx.prototype.processEcmaVer=function(){var val,config=this._config;if(config.ecmaVer){val=config.ecmaVer;if(typeof val==="string"){if(val.substring(0,2).toLowerCase()==="es"){val=val.substring(2)}val=parseInt(val);if(isNaN(val)){val=0}}if(typeof val===NUMBER){if(!(ECMA_VER.includes(val)||ECMA_YEAR.includes(val))){this._error(`Config 'ecmaVer: ${config.ecmaVer}' is not in the version range ${ECMA_VER[0]}-${ECMA_VER[ECMA_VER.length-1]} or the year range ${ECMA_YEAR[1]}-${ECMA_YEAR[ECMA_YEAR.length-1]}!`);return false}}if(val>=2015){val=ECMA_YEAR.indexOf(val);config.ecmaVer=ECMA_VER[val]}else{config.ecmaVer=val}}else{config.ecmaVer=DEFAULTS.ECMAVER}return true};CfgEx.prototype.processMessages=function(){var val,config=this._config;if(config.messages){val=config.messages;if(!this._utils.isObject(val)){this._error("Config entry 'messages' is not an object!");return false}if(val.accept&&val.reject){this._error("Config entry 'messages' - 'accept' and 'reject' are mutually exclusive!");return false}if(val.accept){if(!Array.isArray(val.accept)){this._error("Config entry 'messages.accept' is not an array!");return false}else if(!this._utils.isArrayContentsType(val.accept,"string")){this._error("Config entry 'messages.accept' property array does not contain all strings");return false}}if(val.reject){if(!Array.isArray(val.reject)){this._error("Config entry 'messages.reject' is not an array!");return false}else if(!this._utils.isArrayContentsType(val.reject,"string")){this._error("Config entry 'messages.reject' property array does not contain all strings");return false}}}return true};CfgEx.prototype.processAddFileList=function(){var config=this._config;if(config.appendFileList){this._appendFileList=true;this._warn("Configuration property 'appendFileList' : change to 'addFileList'")}else if(config.addFileList){this._addFileList=true}return true};CfgEx.prototype.processNameSpaces=function(){var config,nsp,ns,e;config=this._config;if(!config.nameSpaces){return true}if(!Array.isArray(config.nameSpaces)){config.nameSpaces=[config.nameSpaces]}nsp=config.nameSpaces;for(let i=0;i<nsp.length;i++){ns=nsp[i];if(!ns||typeof ns!=="string"){this._error(`Config 'nameSpaces' entry "${ns}" at index ${i} is not a valid namespace`);e=true}else if(ns.startsWith("oj-")||ns.startsWith("ns-")){this._error(`Config 'nameSpaces' entry '${ns}' must not use reserved JET prefix ${ns.substring(0,3)}`);e=true}}return e?false:true};CfgEx.prototype.processOptions=function(){var prop,opts,config=this._config,isCLI=this._modeCtx.isCLI||this._modeCtx.isOJETCLI;if(config.options){opts=config.options;for(prop in opts){if(!OPTIONS_PROPS.includes(prop)){this._error(`Config - unknown 'options' sub-property '${prop}'`);return false}else if((prop==="retCode"||prop==="rc")&&!isCLI){this._error(`Config - 'options' property '${prop}' is valid in CLI mode only`);return false}}}return true};CfgEx.prototype.processExtends=function(){var config=this._config;var ext;if(this._modeCtx.isAMD){if(ext=config.extends){if(typeof ext==="string"){this._error("Config use of non-profile 'extends' property is not supported in AMD mode.");return false}}if(config.extendOptions){this._error("Config use of 'extendOptions' property is not supported in AMD mode.");return false}}if(this._config.extendOptions){if(!this._utils.isObject(this._config.extendOptions)){this._error("Config 'extendOptions' is not an object.");return false}}this._extends=this._config?.extends?.profile;var extLib=new this._nd.extends(this,this._oConfig,config,this._path,this._nd,this._msgCtx,this._utils,this._fsUtils,this._modeCtx.isAMD);var cfg=extLib.extend();return cfg};CfgEx.prototype.processTitle=function(){var t,config=this._config;if(config.title){t=this._utils.getType(config.title);if(t!=="string"&&t!=="array"){this._error(`Config entry 'title has incorrect type ('${t}')`);return false}}return true};CfgEx.prototype.processRetCode=function(){var rc,prop,ret,config=this._config;if(config.options){prop=typeof config.options.retCode!==UNDEF?"retCode":typeof config.options.rc!==UNDEF?"rc":null;if(prop){rc=config.options[prop];ret=this.validateRetCode(rc,sev=>{this._error(`Config entry 'options.${prop}' : unknown severity '${sev}'`)});if(ret||typeof ret==="number"){config.options[prop]=ret}else{config.options[prop]=AUTO;return false}}}if(!prop){if(!config.options){config.options={}}config.options.retCode=DEF_RETCODE}return true};CfgEx.prototype.processRuleDiscriminant=function(){var rd,config=this._config;if(!config.hasOwnProperty("ruleDiscriminant")){return true}if(typeof(rd=config.ruleDiscriminant)!=="string"){this._error("`Config entry 'ruleDiscriminant' : expected a string");return false}if(rd!=="redwood-strict"){this._error(`Config entry 'ruleDiscriminant' : invalid value '${rd}'`);return false}return true};CfgEx.prototype.validateFileList=function(aFiles){var i,j,f,msg,ret=true;;for(i=0;i<aFiles.length;i++){f=aFiles[i];if(typeof f==="string"){continue}if(!this._utils.isObject(f)){msg=" property entry "+(i+1)+" is not a string or an object";break}if(f.files){if(!(Array.isArray(f.files)&&this._utils.isArrayContentsType(f.files,"string"))){msg=" property entry "+(i+1)+" does not contain a 'files' property array, or not all elements are strings";break}}else{msg=" property entry "+(i+1)+", does not contain a 'files' property";break}if(!f.base){msg=" property entry "+(i+1)+" does not contain a 'base' property";break}for(j=0;j<f.files.length;j++){f.files[j]=this._nd.path.join(f.base,f.files[j])}}if(!msg){for(i=0;i<aFiles.length;i++){f=aFiles[i];if(this._utils.isObject(f)){aFiles.splice(i,1,...f.files)}}}if(msg){this._error(msg);ret=false}return ret};CfgEx.prototype.validateRetCode=function(val,cb){var t,i,b;t=typeof val;if(t==="number"||t==="string"&&val===DEF_RETCODE||val===ERRORS){return val}if(t==="string"){if(!this._sevLib.isSev(val)){cb(val);return false}else{return this._sevLib.unmap(val)}}if(Array.isArray(val)){b=true;for(i=0;i<val.length;i++){if(!this._sevLib.isSev(val[i])){cb(val[i]);b=false}else{val[i]=this._sevLib.unmap(val[i])}}if(b){for(i=0;i<val.length;i++){if(Array.isArray(val[i])){let ar=[];for(i=0;i<val.length;i++){ar=ar.concat(val[i])}val=ar;break}}return val}}return false};CfgEx.prototype.setMessages=function(msgid,state){var accept,reject,msgs,target,changed=false,i;var config=this._config;msgs=config.messages;state=!!state;if(!msgs){if(!state){config.messages={reject:[msgid]};changed=true}}else{reject=msgs.reject;accept=msgs.accept;target=accept||reject;i=target?target.indexOf(msgid):-1;if(state){if(!accept&&!reject){msgs.accept=accept=[]}if(reject){if(i>=0){reject.splice(i,1);changed=true;if(reject.length===0){delete msgs.reject}}}else if(accept){if(i<0){accept.push(msgid);changed=true}}}else{if(!accept&&!reject){msgs.reject=reject=[]}if(reject){if(i<0){reject.push(msgid);changed=true}}else if(accept){if(i>=0){accept.splice(i,1);if(accept.length===0){delete msgs.accept}changed=true}}}}return changed};CfgEx.prototype.getAddFileList=function(){return!!(this._addFileList||this._appendFileList)};CfgEx.prototype.checkPropNames=function(cfg,path){var prop,ret=true,config=cfg?cfg:this._config;path=path||this._path;for(prop in config){if(!TOP_PROPS.includes(prop)){if(prop.charAt(0)==="_"){delete config[prop];continue}this._error(`Config - unknown property '${prop}' ${path?"- "+path:""}`);ret=false}else if(this._modeCtx.isAMD&&NOT_AMD.includes(prop)){this._error(`Config - property '${prop}' is not available in AMD mode!`);ret=false}}return ret};CfgEx.prototype.getExtendsProfileName=function(){return this._extends};CfgEx.prototype.setConfig=function(cfg,cfgPath,dir){this._config=cfg;this._path=cfgPath;this._dir=dir};CfgEx.prototype._findCompositesDir=function(base){return this._fsUtils.findFile(base,COMPOSITES)};module.exports=CfgEx;
|
|
6
|
+
const GROUPS=require("./groups");const DEFAULTS=require("./defaults");const SemVer=require("semver");const COMPOSITES="jet-composites";const TYPE_STRING="string";const TYPE_BOOLEAN="boolean";const AUTO="auto";const ERRORS="errors";const UNDEF="undefined";const NUMBER="number";const TOP_PROPS=["rulePacks","ruleMods","ruleDiscriminant","builtinJetRules","builtinCspRules","builtinSpocRules","builtinJetWcRules","builtinJetWcOracleRules","builtinOjcMigrationRules","builtinWebDriverTestRules","severity","groups","defGroups","ruleNames","base","files","exclude","typescript","jetPagesOnly","format","proseFormat","lineFormat","outPath","tabs","messages","addFileList","title","jetVer","components","componentUrls","componentOptions","jetCorePack","markdownOptions","stylesets","ecmaVer","ruleDescriptions","rulesFired","userDefs","options","comments","extends","extendOptions","nameSpaces","followLinks","tempDir","tokens","common","$JetCore","sevMap","theme","ojet","appendFileList"];const NOT_AMD=["addFileList","base","builtinJetWcRules","builtinJetWcOracleRules","builtinOjcMigrationRules","builtinWebDriverTestRules","components","componentOptions","componentUrls","extendOptions","files","exclude","followLinks","outPath","rulePacks","tempDir","tokens","typescript"];const OPTIONS_PROPS=["debug","verbose","color","msgid","ruleName","retCode","rc","ojetUpdate","experimental","$unittest"];const THEMES=["redwood","alta","stable","none"];const DEF_COMMENTS=false;const DEF_RULE_DESCRIPT="none";const DEF_GROUPS=["all"];const DEF_RETCODE="auto";const ISSUE_TAG="issueTag";const ECMA_VER=[5,6,7,8,9,10,11,12,13,14];const ECMA_YEAR=[-1,2015,2016,2017,2018,2019,2020,2021,2022,2023];function CfgEx(oConfig,nodeDeps,sevLib,utils,fsUtils,msgCtx,modeCtx){this._oConfig=oConfig;this._config=null;this._dir=null;this._sevLib=sevLib;this._extends=null;this._utils=utils;this._fsUtils=fsUtils;this._nd=nodeDeps;this._msgCtx=msgCtx;this._modeCtx=modeCtx;this._isVerbose=msgCtx.isVerbose;this._isCLI=modeCtx.isCLI||modeCtx.isOJETCLI;this._error=msgCtx.error;this._warn=msgCtx.warn;this._info=msgCtx.info};CfgEx.prototype.setDebugStatus=function(verbose,debug){this._isVerbose=this._msgCtx.isVerbose=verbose};CfgEx.prototype.processWebComponents=function(){var dir,o,t,i;var config=this._config;if(config.componentUrlBase){if(!typeof config.componentUrlBase===TYPE_STRING){this._error("Config entry 'componentUrlBase' must be a string!");return false}}if(config.componentUrls){if(typeof config.componentUrls===TYPE_STRING){config.componentUrls=[config.componentUrls]}else if(!Array.isArray(config.componentUrls)){this._error("Config entry 'componentUrls' must be a string or an aray of strings!");return false}for(i=0;i<this._config.componentUrls.length;i++){config.componentUrls[i]=config.componentUrls[i].trim();if(config.componentUrls[i].length===0){config.componentUrls.splice(i,1);i--}}}if(!config.components){if(this._isCLI&&!this._isOJET&&this._experimentalSet){dir=this._findCompositesDir(config.base);if(dir){config.components=[];config.components.push(this._nd.path.join(dir,COMPOSITES))}}}if(config.components){if(typeof config.components===TYPE_STRING){config.components=[config.components]}else if(!Array.isArray(config.components)){this._error("Config entry 'components' must be a string or an array of strings!");return false}for(i=0;i<config.components.length;i++){config.components[i]=config.components[i].trim();if(config.components[i].length===0){config.components.splice(i,1);i--}}}if(config.components&&config.components.length||config.componentUrls&&config.componentUrls.length){o=config.componentOptions;if(o){if(!this._utils.isObject(o)){this._error("Config 'components' sub-property 'componentOptions' must be an Object!");return false}t=typeof o.applySchema;if(t==="undefined"){o.applySchema=true}else if(t!=="boolean"){this._error("Config 'components' sub-property 'componentOptions' must be an Object!");return false}}}return true};CfgEx.prototype.processJetCorePack=function(){var config=this._config;var ret=true;if(!config.hasOwnProperty("jetCorePack")){return ret}let t=typeof config.jetCorePack;if(t===TYPE_BOOLEAN){if(config.jetCorePack){this._error("Config 'jetCorePack' property value cannot be boolean true!");ret=false}return ret}if(SemVer.lt(config.jetVer,"13.0.0")){this._error("Config 'jetCorePack' is valid for 'jetVer' values >= 13.0.0 only");ret=false}if(t!==TYPE_STRING){this._error("Config 'jetCorePack' property is not a string or a boolean!");ret=false}return ret};CfgEx.prototype.processTypeScript=function(){var ts,ret=true;if(this._config.hasOwnProperty("typescript")){ts=this._config.typescript;if(!this._utils.isObject(ts)){this._error("Config 'typescript' property is not an object!");ret=false}if(ts.hasOwnProperty("compile")){if(typeof ts.compile!=="boolean"){this._error("Config 'typescript' sub-property 'compile' is not a boolean!");ret=false}}if(ts.hasOwnProperty("tsconfig")){if(typeof ts.tsconfig!=="string"){this._error("Config 'typescript' sub-property 'tsconfig' must be a directory string!");ret=false}}}return ret};CfgEx.prototype.processRulePacks=function(){var packs,pack,i;var config=this._config;if(config.rulePacks){packs=this._config.rulePacks;if(!Array.isArray(packs)){this._error("Config entry 'rulePacks' is not an array!");return false}for(i=0;i<packs.length;i++){pack=packs[i];if(typeof pack!==TYPE_BOOLEAN){pack.enabled=true}if(!pack.path){this._error(`Config entry 'rulePacks' (entry ${i+1}) does not have a 'path' entry!`);return false}else{pack.path=pack.path.trim()}if(pack.status&&!Array.isArray(pack)){this._error(`Config entry 'rulePacks' (entry ${i+1}) 'status' property is not an array!`);return false}}}else{config.rulePacks=[]}return true};CfgEx.prototype.processRuleMods=function(cfg,fp){var mods,mod,val,rule;var config=cfg?cfg:this._config;const MSG="Config 'ruleMods' sub-property '${mod}' is not an array of rule names or group names";var self=this,b;if(!config.ruleMods){return true}function _emitRMError(s){s+=fp?` - in ${fp}`:"";self._error(s);b=true}mods=config.ruleMods;if(!this._utils.isObject(mods)){_emitRMError("Configuration property 'ruleMods' is not an object");return false}for(mod in mods){if(mod==="enabled"){_emitRMError("Config 'ruleMods' : invalid sub-property 'enabled' - did you mean 'enable'?")}else if(mod==="disabled"){_emitRMError("Config 'ruleMods' : invalid sub-property 'disabled' - did you mean 'disable'?")}if(b){return!b}val=mods[mod];if(mod==="enable"||mod==="disable"){if(!Array.isArray(val)){_emitRMError(this._utils.format(MSG,{mod:mod}))}if(!this._utils.isArrayContentsType(val,"string")){_emitRMError(this._utils.format(MSG,{mod:mod}))}}else{if(!this._utils.isObject(val)){_emitRMError(`Config 'ruleMods' sub-property '${mod}' is not an object!`)}else{for(rule in val){let o=val[rule];if(o.hasOwnProperty(ISSUE_TAG)){if(typeof o.issueTag!=="string"){_emitRMError(`Config 'ruleMods' for '${mod}' rule '${rule}' : '${ISSUE_TAG}' is not a string`)}}};}}}if(!b&&mods.enable&&mods.disable){mods.enable.forEach(function(r){if(mods.disable.includes(r)){_emitRMError(`Config 'ruleMods': 'enable' & 'disable' conflicting entry '${r}'`)}})}return!b};CfgEx.prototype.processFormat=function(){var config=this._config;if(config.hasOwnProperty("format")){if(config.format!=="json"&&config.format!=="prose"&&config.format!=="line"){this._error(`Config entry 'format' '${config.format}' not valid. Must be 'json', 'prose' or 'line'!`);return false}}else{this._config.format="prose"}return true};CfgEx.prototype.processProseFormat=function(){var config=this._config;if(config.hasOwnProperty("proseFormat")){if(typeof config.proseFormat==="string"){if(config.format!=="prose"){this._warn("Config entry 'proseFormat' ignored - not applicable if 'format' is not 'prose'!")}}else{this._error(`Config entry 'proseFormat' '${config.proseFormat}' is not valid!`);return false}}return true};CfgEx.prototype.processLineFormat=function(){var config=this._config;if(config.hasOwnProperty("lineFormat")){if(typeof config.lineFormat==="string"){if(config.format!=="line"){this._warn("Config entry 'lineFormat' ignored - not applicable if 'format is not 'line'!")}}else{this._error(`Config entry 'lineFormat' '${config.lineFormat}' is not valid!`);return false}}return true};CfgEx.prototype.processRuleDescriptions=function(){var val,valType;var config=this._config;if(config.ruleDescriptions){val=config.ruleDescriptions;valType=typeof val;if(valType!=="string"||val!="all"&&val!=="short"&&val!=="long"&&val!=="none"){this._error(`Config entry 'ruleDescriptions' '${val}' is not valid!`);return false}}else{config.ruleDescriptions=DEF_RULE_DESCRIPT}return true};CfgEx.prototype.processRulesFired=function(){var config=this._config;if(config.rulesFired){if(!this._modeCtx.isAPI&&!this._modeCtx.isAMD&&(!config.format||config.format!=="json")){this._error(`Config entry 'rulesFired' - API/AMD mode required, or 'format' property set to 'json' for CLI mode!`);return false}}return true};CfgEx.prototype.processSevMap=function(){var config=this._config;var set,sev,msgs,inv,mapped,val,b,error;if(!config.sevMap){return true}set=config.sevMap.sevSet;if(set){b=error=false;for(val in set){if(!this._sevLib.isValidConfigSeverity(val)){this._error(`Config entry 'sevMap' sub-property 'sevSet' value '${val}' is not 'blocker/critical/major/minor/info'!`);error=true;continue}if(val==="all"){this._error("Config entry 'sevMap' sub-property 'sevSet' - pseudo severity 'all' cannot be remapped!");error=true;continue}if(typeof set[val]!=="string"){this._error(`Config entry 'sevMap' sub-property 'sevSet' value '${val}' is not a string!`);error=true;continue}b=true}if(error){return false}if(b){inv={};for(sev in set){mapped=set[sev];if(inv[mapped]){if(!Array.isArray(inv[mapped])){inv[mapped]=[inv[mapped]]}inv[mapped].push(sev)}else{inv[mapped]=sev}}this._sevLib.setSevMap(config.sevMap,inv)}else{config.sevMap.sevSet=null}}msgs=config.sevMap.sevMsg;if(msgs){if(!this._utils.isObject(msgs)){this._error("Config entry 'sevMap' sub-property 'sevMsg' is not an object!");return false}b=error=false;for(val in msgs){sev=msgs[val];if(typeof sev!=="string"){this._error(`Config entry 'sevMap' sub-property 'sevMsg' : '${val}' is not a string!`);error=true;continue}if(!this._sevLib.isSev(sev)){this._error(`Config entry 'sevMap' sub-property 'sevMsg' : '${sev}' is ${UNDEF}!`);error=true;continue}b=true}if(error){return false}if(b){this._sevLib.setSevMsg(msgs)}else{config.sevMap.sevMsg=null}}else{b=true;for(val in config.sevMap){if(val!=="sevSet"&&val!=="sevMsg"){this._error(`Config entry 'sevMap' unknown sub-property '${val}'!`);b=false}}if(!b){return false}}return true};CfgEx.prototype.processSeverity=function(cliSev){var config=this._config;var val,se,i;if(cliSev){config.severity=cliSev}if(config.severity){val=config.severity;if(typeof val==="string"){se=this._sevLib.getSevExpr(val);if(!this._sevLib.isValidConfigSeverity(val)){if(se.op&&se.sev==="all"){this._error(`Config entry 'severity' ('${val}') : 'all' cannot be used with a severity expression !`)}else if(cliSev){this._error(`command line --severity '${val}' is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`)}else{this._error(`Config entry 'severity' ('${val}') is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`)}return false}this._sevLib.setSevExpr(se)}else if(Array.isArray(val)&&this._utils.isArrayContentsType(val,"string")){for(i=0;i<val.length;i++){if(!this._sevLib.isValidConfigSeverity(val[i])){this._error(`Config entry 'severity' ('${val[i]}') is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`);return false}}}else{this._error("Config entry 'severity' is invalid!");return false}}else{config.severity=this._sevLib.ALL;this._sevLib.setSevExpr(this._sevLib.getSevExpr(this._sevLib.ALL))}return true};CfgEx.prototype.processGroups=function(cliGroups){var group,i;var config=this._config;if(cliGroups){config.groups=cliGroups}if(!config.groups){config.groups=DEF_GROUPS;return true}if(!Array.isArray(config.groups)){config.groups=[config.groups]}if(config.groups.length===0){config.groups.push("all")}else{for(i=0;i<config.groups.length;i++){group=config.groups[i];if(!GROUPS.isGroup(group)){if(group.startsWith("jet-")||group.startsWith("htm")){this._error(`Config 'groups' entry '${group}' is not defined!`);return false}}}}return true};CfgEx.prototype.processDefGroups=function(){var config=this._config;if(config.defGroups){if(!this._utils.isObject(config.defGroups)){this._error("Config entry 'defGroups' is not an object!");return false}}else{config.defGroups=null}return true};CfgEx.prototype.processRuleNames=function(){var config=this._config;if(config.ruleNames){if(!Array.isArray(config.ruleNames)){this._error("Config entry 'ruleNames' is not an array!");return false}}return true};CfgEx.prototype.processTheme=function(){var t,config=this._config;t=config.theme;if(t){t=t.toLowerCase();if(typeof t==="string"){if(!THEMES.includes(t)){this._error(`Invalid config theme '${t}' : must be 'Redwood', 'Alta', 'Stable' or 'none'`);return false}}else{this._error("Config entry 'theme' is not a string!");return false}if(t==="stable"){t="redwood"};config.theme=t.charAt(0).toUpperCase()+t.substring(1)}else{config.theme=SemVer.gte(config.jetVer,"12.0.0")?"Redwood":DEFAULTS.THEME;if(this._isVerbose){this._info(`[Info]: Default theme '${config.theme}' applied for jetVer ${config.jetVer}`)}}return true};CfgEx.prototype.processComments=function(){var t,config=this._config;t=typeof config.comments;if(t===UNDEF){config.comments=DEF_COMMENTS}else if(t!=="boolean"){this._error("Invalid 'comments' property - expected a boolean");return false}return true};CfgEx.prototype.processMarkdownOpts=function(){var config=this._config;var val=config.markdownOptions;var t=typeof val;if(t===UNDEF){config.markdownOptions={linkify:true}}else if(Array.isArray(val)||t!=="object"){this._error("Invalid 'markdownOptions' property - expected an object");return false}else{t=typeof val.linkify;if(t==="undefined"){val.linkify=true}else if(typeof val.linkify!=="boolean"){this._error("Invalid 'markdownOptions.linkify' - expected a boolean");return false}let n=Object.keys(val);if(!val.hasOwnProperty("linkify")){if(n.length){this._error("Invalid 'markdownOptions.linkify' - expected a boolean");return false}else{val.linkify=true}}else if(n.length>1){this._error("Invalid 'markdownOptions' properties found");return false}}return true};CfgEx.prototype.processEcmaVer=function(){var val,config=this._config;if(config.ecmaVer){val=config.ecmaVer;if(typeof val==="string"){if(val.substring(0,2).toLowerCase()==="es"){val=val.substring(2)}val=parseInt(val);if(isNaN(val)){val=0}}if(typeof val===NUMBER){if(!(ECMA_VER.includes(val)||ECMA_YEAR.includes(val))){this._error(`Config 'ecmaVer: ${config.ecmaVer}' is not in the version range ${ECMA_VER[0]}-${ECMA_VER[ECMA_VER.length-1]} or the year range ${ECMA_YEAR[1]}-${ECMA_YEAR[ECMA_YEAR.length-1]}!`);return false}}if(val>=2015){val=ECMA_YEAR.indexOf(val);config.ecmaVer=ECMA_VER[val]}else{config.ecmaVer=val}}else{config.ecmaVer=DEFAULTS.ECMAVER}return true};CfgEx.prototype.processMessages=function(){var val,config=this._config;if(config.messages){val=config.messages;if(!this._utils.isObject(val)){this._error("Config entry 'messages' is not an object!");return false}if(val.accept&&val.reject){this._error("Config entry 'messages' - 'accept' and 'reject' are mutually exclusive!");return false}if(val.accept){if(!Array.isArray(val.accept)){this._error("Config entry 'messages.accept' is not an array!");return false}else if(!this._utils.isArrayContentsType(val.accept,"string")){this._error("Config entry 'messages.accept' property array does not contain all strings");return false}}if(val.reject){if(!Array.isArray(val.reject)){this._error("Config entry 'messages.reject' is not an array!");return false}else if(!this._utils.isArrayContentsType(val.reject,"string")){this._error("Config entry 'messages.reject' property array does not contain all strings");return false}}}return true};CfgEx.prototype.processAddFileList=function(){var config=this._config;if(config.appendFileList){this._appendFileList=true;this._warn("Configuration property 'appendFileList' : change to 'addFileList'")}else if(config.addFileList){this._addFileList=true}return true};CfgEx.prototype.processNameSpaces=function(){var config,nsp,ns,e;config=this._config;if(!config.nameSpaces){return true}if(!Array.isArray(config.nameSpaces)){config.nameSpaces=[config.nameSpaces]}nsp=config.nameSpaces;for(let i=0;i<nsp.length;i++){ns=nsp[i];if(!ns||typeof ns!=="string"){this._error(`Config 'nameSpaces' entry "${ns}" at index ${i} is not a valid namespace`);e=true}else if(ns.startsWith("oj-")||ns.startsWith("ns-")){this._error(`Config 'nameSpaces' entry '${ns}' must not use reserved JET prefix ${ns.substring(0,3)}`);e=true}}return e?false:true};CfgEx.prototype.processOptions=function(){var prop,opts,config=this._config,isCLI=this._modeCtx.isCLI||this._modeCtx.isOJETCLI;if(config.options){opts=config.options;for(prop in opts){if(!OPTIONS_PROPS.includes(prop)){this._error(`Config - unknown 'options' sub-property '${prop}'`);return false}else if((prop==="retCode"||prop==="rc")&&!isCLI){this._error(`Config - 'options' property '${prop}' is valid in CLI mode only`);return false}}}return true};CfgEx.prototype.processExtends=function(){var config=this._config;var ext;if(this._modeCtx.isAMD){if(ext=config.extends){if(typeof ext==="string"){this._error("Config use of non-profile 'extends' property is not supported in AMD mode.");return false}}if(config.extendOptions){this._error("Config use of 'extendOptions' property is not supported in AMD mode.");return false}}if(this._config.extendOptions){if(!this._utils.isObject(this._config.extendOptions)){this._error("Config 'extendOptions' is not an object.");return false}}this._extends=this._config?.extends?.profile;var extLib=new this._nd.extends(this,this._oConfig,config,this._path,this._nd,this._msgCtx,this._utils,this._fsUtils,this._modeCtx.isAMD);var cfg=extLib.extend();return cfg};CfgEx.prototype.processTitle=function(){var t,config=this._config;if(config.title){t=this._utils.getType(config.title);if(t!=="string"&&t!=="array"){this._error(`Config entry 'title has incorrect type ('${t}')`);return false}}return true};CfgEx.prototype.processRetCode=function(){var rc,prop,ret,config=this._config;if(config.options){prop=typeof config.options.retCode!==UNDEF?"retCode":typeof config.options.rc!==UNDEF?"rc":null;if(prop){rc=config.options[prop];ret=this.validateRetCode(rc,sev=>{this._error(`Config entry 'options.${prop}' : unknown severity '${sev}'`)});if(ret||typeof ret==="number"){config.options[prop]=ret}else{config.options[prop]=AUTO;return false}}}if(!prop){if(!config.options){config.options={}}config.options.retCode=DEF_RETCODE}return true};CfgEx.prototype.processRuleDiscriminant=function(){var rd,config=this._config;if(!config.hasOwnProperty("ruleDiscriminant")){return true}if(typeof(rd=config.ruleDiscriminant)!=="string"){this._error("`Config entry 'ruleDiscriminant' : expected a string");return false}if(rd!=="redwood-strict"){this._error(`Config entry 'ruleDiscriminant' : invalid value '${rd}'`);return false}return true};CfgEx.prototype.validateFileList=function(aFiles){var i,j,f,msg,ret=true;;for(i=0;i<aFiles.length;i++){f=aFiles[i];if(typeof f==="string"){continue}if(!this._utils.isObject(f)){msg=" property entry "+(i+1)+" is not a string or an object";break}if(f.files){if(!(Array.isArray(f.files)&&this._utils.isArrayContentsType(f.files,"string"))){msg=" property entry "+(i+1)+" does not contain a 'files' property array, or not all elements are strings";break}}else{msg=" property entry "+(i+1)+", does not contain a 'files' property";break}if(!f.base){msg=" property entry "+(i+1)+" does not contain a 'base' property";break}for(j=0;j<f.files.length;j++){f.files[j]=this._nd.path.join(f.base,f.files[j])}}if(!msg){for(i=0;i<aFiles.length;i++){f=aFiles[i];if(this._utils.isObject(f)){aFiles.splice(i,1,...f.files)}}}if(msg){this._error(msg);ret=false}return ret};CfgEx.prototype.validateRetCode=function(val,cb){var t,i,b;t=typeof val;if(t==="number"||t==="string"&&val===DEF_RETCODE||val===ERRORS){return val}if(t==="string"){if(!this._sevLib.isSev(val)){cb(val);return false}else{return this._sevLib.unmap(val)}}if(Array.isArray(val)){b=true;for(i=0;i<val.length;i++){if(!this._sevLib.isSev(val[i])){cb(val[i]);b=false}else{val[i]=this._sevLib.unmap(val[i])}}if(b){for(i=0;i<val.length;i++){if(Array.isArray(val[i])){let ar=[];for(i=0;i<val.length;i++){ar=ar.concat(val[i])}val=ar;break}}return val}}return false};CfgEx.prototype.setMessages=function(msgid,state){var accept,reject,msgs,target,changed=false,i;var config=this._config;msgs=config.messages;state=!!state;if(!msgs){if(!state){config.messages={reject:[msgid]};changed=true}}else{reject=msgs.reject;accept=msgs.accept;target=accept||reject;i=target?target.indexOf(msgid):-1;if(state){if(!accept&&!reject){msgs.accept=accept=[]}if(reject){if(i>=0){reject.splice(i,1);changed=true;if(reject.length===0){delete msgs.reject}}}else if(accept){if(i<0){accept.push(msgid);changed=true}}}else{if(!accept&&!reject){msgs.reject=reject=[]}if(reject){if(i<0){reject.push(msgid);changed=true}}else if(accept){if(i>=0){accept.splice(i,1);if(accept.length===0){delete msgs.accept}changed=true}}}}return changed};CfgEx.prototype.getAddFileList=function(){return!!(this._addFileList||this._appendFileList)};CfgEx.prototype.checkPropNames=function(cfg,path){var prop,ret=true,config=cfg?cfg:this._config;path=path||this._path;for(prop in config){if(!TOP_PROPS.includes(prop)){if(prop.charAt(0)==="_"){delete config[prop];continue}this._error(`Config - unknown property '${prop}' ${path?"- "+path:""}`);ret=false}else if(this._modeCtx.isAMD&&NOT_AMD.includes(prop)){this._error(`Config - property '${prop}' is not available in AMD mode!`);ret=false}}return ret};CfgEx.prototype.getExtendsProfileName=function(){return this._extends};CfgEx.prototype.setConfig=function(cfg,cfgPath,dir){this._config=cfg;this._path=cfgPath;this._dir=dir};CfgEx.prototype._findCompositesDir=function(base){return this._fsUtils.findFile(base,COMPOSITES)};module.exports=CfgEx;
|
package/lib/HtmlUtils.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 COMMON_ATTRS={"accesskey":true,"class":true,"contenteditable":true,"contextmenu":true,"dir":true,"draggable":true,"dropzone":true,"hidden":true,"id":true,"lang":true,"role":true,"spellcheck":true,"style":true,"tabindex":true,"title":true,"translate":true};var COMMON_ELEMS={"a":true,"abbr":true,"address":true,"area":true,"article":true,"aside":true,"audio":true,"b":true,"base":true,"bdi":true,"bdo":true,"blockquote":true,"body":true,"br":true,"button":true,"canvas":true,"caption":true,"cite":true,"code":true,"col":true,"colgroup":true,"command":true,"datalist":true,"dd":true,"del":true,"details":true,"dfn":true,"div":true,"dl":true,"dt":true,"em":true,"embed":true,"fieldset":true,"figcaption":true,"figure":true,"footer":true,"form":true,"h1":true,"h2":true,"h3":true,"h4":true,"h5":true,"h6":true,"head":true,"header":true,"hgroup":true,"hr":true,"html":true,"i":true,"iframe":true,"img":true,"input":true,"ins":true,"kbd":true,"keygen":true,"label":true,"legend":true,"li":true,"link":true,"map":true,"main":true,"mark":true,"menu":true,"meta":true,"meter":true,"nav":true,"noscript":true,"object":true,"ol":true,"optgroup":true,"option":true,"output":true,"p":true,"param":true,"pre":true,"progress":true,"q":true,"rp":true,"rt":true,"ruby":true,"s":true,"samp":true,"script":true,"section":true,"select":true,"small":true,"source":true,"span":true,"strong":true,"style":true,"sub":true,"summary":true,"sup":true,"table":true,"tbody":true,"td":true,"textarea":true,"tfoot":true,"th":true,"thead":true,"time":true,"title":true,"tr":true,"track":true,"u":true,"ul":true,"var":true,"video":true,"wbr":true,"svg":true};var COMMON_EVENT_ATTRS={"onabort":true,"onauxclick":true,"onblur":true,"oncanplay":true,"oncanplaythrough":true,"onchange":true,"onclick":true,"oncontextmenu":true,"ondblclick":true,"ondblclickcapture":true,"ondrag":true,"ondragend":true,"ondragenter":true,"ondragleave":true,"ondragover":true,"ondragstart":true,"ondrop":true,"ondurationchange":true,"onemptied":true,"onended":true,"onerror":true,"onfocus":true,"onfocusin":true,"onfocusout":true,"onformchange":true,"onforminput":true,"oninput":true,"oninvalid":true,"onkeydown":true,"onkeypress":true,"onkeyup":true,"onload":true,"onloadeddata":true,"onloadedmetadata":true,"onloadstart":true,"onmousedown":true,"onmouseenter":true,"onmouseleave":true,"onmousemove":true,"onmouseout":true,"onmouseover":true,"onmouseup":true,"onmousewheel":true,"onpause":true,"onplay":true,"onplaying":true,"onprogress":true,"onratechange":true,"onreadystatechange":true,"onreset":true,"onscroll":true,"onseeked":true,"onseeking":true,"onselect":true,"onshow":true,"onstalled":true,"onsubmit":true,"onsuspend":true,"ontimeupdate":true,"onvolumechange":true,"onwaiting":true,"onwheel":true};const SVG_ELEMS={"animate":true,"animatemotion":true,"animatetransform":true,"circle":true,"clippath":true,"color-profile":true,"defs":true,"desc":true,"discard":true,"ellipse":true,"feblend":true,"fecolormatrix":true,"fecomponenttransfer":true,"fecomposite":true,"feconvolvematrix":true,"fediffuselighting":true,"fedisplacementmap":true,"fedistantlight":true,"fedropshadow":true,"feflood":true,"fefunca":true,"fefuncb":true,"fefuncg":true,"fefuncr":true,"fegaussianblur":true,"feimage":true,"femerge":true,"femergenode":true,"femorphology":true,"feoffset":true,"fepointlight":true,"fespecularlighting":true,"fespotLight":true,"fetile":true,"feturbulence":true,"filter":true,"foreignobject":true,"g":true,"hatch":true,"hatchpath":true,"image":true,"line":true,"lineargradient":true,"marker":true,"mask":true,"mesh":true,"meshgradient":true,"meshpatch":true,"meshrow":true,"metadata":true,"mpath":true,"path":true,"pattern":true,"polygon":true,"polyline":true,"radialgradient":true,"rect":true,"script":true,"set":true,"solidcolor":true,"stop":true,"style":true,"svg":true,"switch":true,"symbol":true,"text":true,"textpath":true,"title":true,"tspan":true,"unknown":true,"use":true,"view":true};const HTML5_OBS_TAGS={"applet":true,"acronym":true,"basefont":true,"bgsound":true,"big":true,"blink":true,"center":true,"dir":true,"font":true,"frame":true,"frameset":true,"noframes":true,"isindex":true,"keygen":true,"listing":true,"marquee":true,"menuitem":true,"multicol":true,"nextid":true,"nobr":true,"noembed":true,"plaintext":true,"rb":true,"rlc":true,"s":true,"spacer":true,"strike":true,"tt":true,"xmp":true};const HTML5_OBS_ATTRS={"a":["charset","coords","methods","name","rev","shape","urn"],"area":["nohref"],"body":["alink","background","bgcolor","bottommargin","leftmargin","link","marginheight","marginwidth","rightmargin","text","vlink"],"br":["clear"],"caption":["align"],"col":["align","char","charoff","valign","width"],"div":["align"],"dl":["compact"],"embed":["align","name","hspace","vspace"],"form":["accept"],"head":["profile"],"hr":["align","noshade","size","width"],"h1":["align"],"h2":["align"],"h3":["align"],"h4":["align"],"h5":["align"],"h6":["align"],"html":["version"],"iframe":["align","allowtransparency","frameborder","framespacing","hspace","longdesc","marginheight","marginwidth","scrolling","vspace"],"img":["align","border","hspace","longdesc","lowsrc","name","vspace"],"input":["align","border","hspace","ismap","usemap","vspace"],"legend":["align"],"li":["type"],"link":["charset","methods","rev","target","urn"],"menu":["compact","label","type"],"meta":["scheme"],"object":["align","archive","border","classid","code","codebase","codetype","declare","hspace","standby","typemustmatch","vspace"],"ol":["compact"],"option":["name"],"p":["align"],"param":["type","valuetype"],"pre":["width"],"script":["charset","event","for","language"],"style":["type"],"table":["align","background","bgcolor","border","bordercolor","cellpadding","cellspacing","datapagesize","frame","height","rules","summary","width"],"tbody":["align","background","char","charoff","valign"],"tfoot":["align","background","char","charoff","valign"],"thead":["align","background","char","charoff","valign"],"td":["abbr","align","axis","background","bgcolor","char","charoff","height","nowrap","scope","valign","width"],"th":["abbr","align","axis","background","bgcolor","char","charoff","height","nowrap","valign","width"],"tr":["align","background","bgcolor","char","charoff","height","valign"],"ul":["compact","type"]};const HTML5_OBS_ATTR_ALL_ELEM=["contextmenu","dropzone","onshow"];const SELF_CLOSING_ELEMS={"area":true,"base":true,"br":true,"embed":true,"hr":true,"iframe":true,"img":true,"input":true,"link":true,"meta":true,"param":true,"source":true,"track":true};const SVG_PATH_COMMANDS=["M","m","L","I","H","h","V","v","C","c","S","s","Q","q","T","t","A","a","Z","z"];const OJ_NAMESPACE_PREFIXES=require("./ns");const ARIA_LIST=["aria-atomic","aria-busy","aria-controls","aria-describedat","aria-describedby","aria-disabled","aria-dropeffect","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-label","aria-labelledby","aria-live","aria-owns","aria-relevant","aria-autocomplete","aria-checked","aria-disabled","aria-expanded","aria-haspopup","aria-hidden","aria-invalid","aria-label","aria-level","aria-multiline","aria-multiselectable","aria-orientation","aria-pressed","aria-readonly","aria-required","aria-rowcount","aria-rowindex","aria-selected","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","aria-dropeffect","aria-grabbed","aria-activedescendant","aria-flowto","aria-posinset","aria-setsize"];module.exports.isCommonAttr=function(attrName){var x;attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===":"?attrName.substring(1):attrName;x=attrName.indexOf(".");if(x>=0){attrName=attrName.substring(0,x)};return COMMON_ATTRS[attrName]||attrName.startsWith("aria-")||attrName.startsWith("data-")&&attrName!=="data-oj-command"&&attrName!=="data-oj-context"};module.exports.isCommonEventAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===":"?attrName.substring(1):attrName;if(attrName.startsWith("on-oj-")){return false}if(attrName.startsWith("on-")){attrName=attrName.substring(0,2)+attrName.substring(3)}return COMMON_EVENT_ATTRS[attrName]};module.exports.isCommonElem=function(elem){return COMMON_ELEMS[elem.toLowerCase()]};module.exports.isSvgElem=function(elem){return SVG_ELEMS[elem.toLowerCase()]};module.exports.isSvgPath=function(s){var c=s.trim().charAt(0);return SVG_PATH_COMMANDS.indexOf(c)>=0};module.exports.isSelfClosingTag=function(elem){return SELF_CLOSING_ELEMS[elem]};module.exports.isNamespacePrefix=function(prefix){return OJ_NAMESPACE_PREFIXES.has(prefix)};module.exports.isNamespaceTag=function(tag){var s=tag.replace(/[<>]/g,"");var x,ret=false;if(tag.startsWith("demo-")||tag.startsWith("my-")||tag.startsWith("ns-")){return true}while(true){x=s.lastIndexOf("-");if(x>=0){s=s.substring(0,x);if(s.lastIndexOf("-")<0&&s==="oj"){break}if(OJ_NAMESPACE_PREFIXES.has(s)){ret=true;break}}else{break}}return ret};module.exports.isHtml5ObsoleteElem=function(tag){return HTML5_OBS_TAGS[tag.toLowerCase()]};module.exports.isHtml5ObsoleteAttr=function(tagName,attrName){var depAttrs,ret=false;attrName=attrName.charAt(0)!==":"?attrName:attrName.substring(1);depAttrs=HTML5_OBS_ATTRS[tagName];if(!depAttrs){depAttrs=HTML5_OBS_ATTR_ALL_ELEM}if(depAttrs){if(depAttrs.includes(attrName)){ret=true}}return ret};module.exports.isAriaAttr=function(attrName){attrName=attrName.charAt(0)===":"?attrName.substring(1):attrName;return ARIA_LIST.includes(attrName.toLowerCase())};const EXPR_CHARS=new RegExp("[?\"'=+:/()[]{}]","g");module.exports.isEncodedLiteral=function(expr){if(expr.charAt(0)==="'"&&expr.charAt(expr.length-1)==="'"){return EXPR_CHARS.test(expr.substring(1,expr.length-1))}return false};module.exports.replaceEntities=function(s){const ENTITY_LT=/</g;const ENTITY_GT=/&/g;const ENTITY_QUOT=/"/g;const ENTITY_APOS=/'/g;const ENTITY_AMP=/&/g;const ENTITY_NBSP=/ /g;if(s.indexOf("&")>=0){s=s.replace(ENTITY_LT,"<");s=s.replace(ENTITY_GT,"&");s=s.replace(ENTITY_QUOT,"\"");s=s.replace(ENTITY_APOS,"'");s=s.replace(ENTITY_AMP,"&");s=s.replace(ENTITY_NBSP," ")}return s};
|
|
6
|
+
const COMMON_ATTRS={"accesskey":true,"class":true,"contenteditable":true,"contextmenu":true,"dir":true,"draggable":true,"dropzone":true,"hidden":true,"id":true,"lang":true,"role":true,"spellcheck":true,"style":true,"tabindex":true,"title":true,"translate":true};var COMMON_ELEMS={"a":true,"abbr":true,"address":true,"area":true,"article":true,"aside":true,"audio":true,"b":true,"base":true,"bdi":true,"bdo":true,"blockquote":true,"body":true,"br":true,"button":true,"canvas":true,"caption":true,"cite":true,"code":true,"col":true,"colgroup":true,"command":true,"datalist":true,"dd":true,"del":true,"details":true,"dfn":true,"div":true,"dl":true,"dt":true,"em":true,"embed":true,"fieldset":true,"figcaption":true,"figure":true,"footer":true,"form":true,"h1":true,"h2":true,"h3":true,"h4":true,"h5":true,"h6":true,"head":true,"header":true,"hgroup":true,"hr":true,"html":true,"i":true,"iframe":true,"img":true,"input":true,"ins":true,"kbd":true,"keygen":true,"label":true,"legend":true,"li":true,"link":true,"map":true,"main":true,"mark":true,"menu":true,"meta":true,"meter":true,"nav":true,"noscript":true,"object":true,"ol":true,"optgroup":true,"option":true,"output":true,"p":true,"param":true,"pre":true,"progress":true,"q":true,"rp":true,"rt":true,"ruby":true,"s":true,"samp":true,"script":true,"section":true,"select":true,"small":true,"source":true,"span":true,"strong":true,"style":true,"sub":true,"summary":true,"sup":true,"table":true,"tbody":true,"td":true,"textarea":true,"tfoot":true,"th":true,"thead":true,"time":true,"title":true,"tr":true,"track":true,"u":true,"ul":true,"var":true,"video":true,"wbr":true,"svg":true};var COMMON_EVENT_ATTRS={"onabort":true,"onauxclick":true,"onblur":true,"oncanplay":true,"oncanplaythrough":true,"onchange":true,"onclick":true,"oncontextmenu":true,"ondblclick":true,"ondblclickcapture":true,"ondrag":true,"ondragend":true,"ondragenter":true,"ondragleave":true,"ondragover":true,"ondragstart":true,"ondrop":true,"ondurationchange":true,"onemptied":true,"onended":true,"onerror":true,"onfocus":true,"onfocusin":true,"onfocusout":true,"onformchange":true,"onforminput":true,"oninput":true,"oninvalid":true,"onkeydown":true,"onkeypress":true,"onkeyup":true,"onload":true,"onloadeddata":true,"onloadedmetadata":true,"onloadstart":true,"onmousedown":true,"onmouseenter":true,"onmouseleave":true,"onmousemove":true,"onmouseout":true,"onmouseover":true,"onmouseup":true,"onmousewheel":true,"onpause":true,"onplay":true,"onplaying":true,"onprogress":true,"onratechange":true,"onreadystatechange":true,"onreset":true,"onscroll":true,"onseeked":true,"onseeking":true,"onselect":true,"onshow":true,"onstalled":true,"onsubmit":true,"onsuspend":true,"ontimeupdate":true,"onvolumechange":true,"onwaiting":true,"onwheel":true};const SVG_ELEMS={"animate":true,"animatemotion":true,"animatetransform":true,"circle":true,"clippath":true,"color-profile":true,"defs":true,"desc":true,"discard":true,"ellipse":true,"feblend":true,"fecolormatrix":true,"fecomponenttransfer":true,"fecomposite":true,"feconvolvematrix":true,"fediffuselighting":true,"fedisplacementmap":true,"fedistantlight":true,"fedropshadow":true,"feflood":true,"fefunca":true,"fefuncb":true,"fefuncg":true,"fefuncr":true,"fegaussianblur":true,"feimage":true,"femerge":true,"femergenode":true,"femorphology":true,"feoffset":true,"fepointlight":true,"fespecularlighting":true,"fespotLight":true,"fetile":true,"feturbulence":true,"filter":true,"foreignobject":true,"g":true,"hatch":true,"hatchpath":true,"image":true,"line":true,"lineargradient":true,"marker":true,"mask":true,"mesh":true,"meshgradient":true,"meshpatch":true,"meshrow":true,"metadata":true,"mpath":true,"path":true,"pattern":true,"polygon":true,"polyline":true,"radialgradient":true,"rect":true,"script":true,"set":true,"solidcolor":true,"stop":true,"style":true,"svg":true,"switch":true,"symbol":true,"text":true,"textpath":true,"title":true,"tspan":true,"unknown":true,"use":true,"view":true};const HTML5_OBS_TAGS={"applet":true,"acronym":true,"basefont":true,"bgsound":true,"big":true,"blink":true,"center":true,"dir":true,"font":true,"frame":true,"frameset":true,"noframes":true,"isindex":true,"keygen":true,"listing":true,"marquee":true,"menuitem":true,"multicol":true,"nextid":true,"nobr":true,"noembed":true,"plaintext":true,"rb":true,"rlc":true,"s":true,"spacer":true,"strike":true,"tt":true,"xmp":true};const HTML5_OBS_ATTRS={"a":["charset","coords","methods","name","rev","shape","urn"],"area":["nohref"],"body":["alink","background","bgcolor","bottommargin","leftmargin","link","marginheight","marginwidth","rightmargin","text","vlink"],"br":["clear"],"caption":["align"],"col":["align","char","charoff","valign","width"],"div":["align"],"dl":["compact"],"embed":["align","name","hspace","vspace"],"form":["accept"],"head":["profile"],"hr":["align","noshade","size","width"],"h1":["align"],"h2":["align"],"h3":["align"],"h4":["align"],"h5":["align"],"h6":["align"],"html":["version"],"iframe":["align","allowtransparency","frameborder","framespacing","hspace","longdesc","marginheight","marginwidth","scrolling","vspace"],"img":["align","border","hspace","longdesc","lowsrc","name","vspace"],"input":["align","border","hspace","ismap","usemap","vspace"],"legend":["align"],"li":["type"],"link":["charset","methods","rev","target","urn"],"menu":["compact","label","type"],"meta":["scheme"],"object":["align","archive","border","classid","code","codebase","codetype","declare","hspace","standby","typemustmatch","vspace"],"ol":["compact"],"option":["name"],"p":["align"],"param":["type","valuetype"],"pre":["width"],"script":["charset","event","for","language"],"style":["type"],"table":["align","background","bgcolor","border","bordercolor","cellpadding","cellspacing","datapagesize","frame","height","rules","summary","width"],"tbody":["align","background","char","charoff","valign"],"tfoot":["align","background","char","charoff","valign"],"thead":["align","background","char","charoff","valign"],"td":["abbr","align","axis","background","bgcolor","char","charoff","height","nowrap","scope","valign","width"],"th":["abbr","align","axis","background","bgcolor","char","charoff","height","nowrap","valign","width"],"tr":["align","background","bgcolor","char","charoff","height","valign"],"ul":["compact","type"]};const HTML5_OBS_ATTR_ALL_ELEM=["contextmenu","dropzone","onshow"];const SELF_CLOSING_ELEMS={"area":true,"base":true,"br":true,"embed":true,"hr":true,"iframe":true,"img":true,"input":true,"link":true,"meta":true,"param":true,"source":true,"track":true};const SVG_PATH_COMMANDS=["M","m","L","I","H","h","V","v","C","c","S","s","Q","q","T","t","A","a","Z","z"];const OJ_NAMESPACE_PREFIXES=require("./ns");const ARIA_LIST=["aria-atomic","aria-busy","aria-controls","aria-current","aria-describedat","aria-describedby","aria-disabled","aria-dropeffect","aria-flowto","aria-grabbed","aria-haspopup","aria-hidden","aria-invalid","aria-label","aria-labelledby","aria-live","aria-owns","aria-relevant","aria-autocomplete","aria-checked","aria-disabled","aria-expanded","aria-haspopup","aria-hidden","aria-invalid","aria-label","aria-level","aria-multiline","aria-multiselectable","aria-orientation","aria-pressed","aria-readonly","aria-required","aria-rowcount","aria-rowindex","aria-selected","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","aria-dropeffect","aria-grabbed","aria-activedescendant","aria-flowto","aria-posinset","aria-setsize"];module.exports.isCommonAttr=function(attrName){var x;attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===":"?attrName.substring(1):attrName;x=attrName.indexOf(".");if(x>=0){attrName=attrName.substring(0,x)};return COMMON_ATTRS[attrName]||attrName.startsWith("aria-")||attrName.startsWith("data-")&&attrName!=="data-oj-command"&&attrName!=="data-oj-context"};module.exports.isCommonEventAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===":"?attrName.substring(1):attrName;if(attrName.startsWith("on-oj-")){return false}if(attrName.startsWith("on-")){attrName=attrName.substring(0,2)+attrName.substring(3)}return COMMON_EVENT_ATTRS[attrName]};module.exports.isCommonElem=function(elem){return COMMON_ELEMS[elem.toLowerCase()]};module.exports.isSvgElem=function(elem){return SVG_ELEMS[elem.toLowerCase()]};module.exports.isSvgPath=function(s){var c=s.trim().charAt(0);return SVG_PATH_COMMANDS.indexOf(c)>=0};module.exports.isSelfClosingTag=function(elem){return SELF_CLOSING_ELEMS[elem]};module.exports.isNamespacePrefix=function(prefix){return OJ_NAMESPACE_PREFIXES.has(prefix)};module.exports.isNamespaceTag=function(tag){var s=tag.replace(/[<>]/g,"");var x,ret=false;if(tag.startsWith("demo-")||tag.startsWith("my-")||tag.startsWith("ns-")){return true}while(true){x=s.lastIndexOf("-");if(x>=0){s=s.substring(0,x);if(s.lastIndexOf("-")<0&&s==="oj"){break}if(OJ_NAMESPACE_PREFIXES.has(s)){ret=true;break}}else{break}}return ret};module.exports.isHtml5ObsoleteElem=function(tag){return HTML5_OBS_TAGS[tag.toLowerCase()]};module.exports.isHtml5ObsoleteAttr=function(tagName,attrName){var depAttrs,ret=false;attrName=attrName.charAt(0)!==":"?attrName:attrName.substring(1);depAttrs=HTML5_OBS_ATTRS[tagName];if(!depAttrs){depAttrs=HTML5_OBS_ATTR_ALL_ELEM}if(depAttrs){if(depAttrs.includes(attrName)){ret=true}}return ret};module.exports.isAriaAttr=function(attrName){attrName=attrName.charAt(0)===":"?attrName.substring(1):attrName;return ARIA_LIST.includes(attrName.toLowerCase())};const EXPR_CHARS=new RegExp("[?\"'=+:/()[]{}]","g");module.exports.isEncodedLiteral=function(expr){if(expr.charAt(0)==="'"&&expr.charAt(expr.length-1)==="'"){return EXPR_CHARS.test(expr.substring(1,expr.length-1))}return false};module.exports.replaceEntities=function(s){const ENTITY_LT=/</g;const ENTITY_GT=/&/g;const ENTITY_QUOT=/"/g;const ENTITY_APOS=/'/g;const ENTITY_AMP=/&/g;const ENTITY_NBSP=/ /g;if(s.indexOf("&")>=0){s=s.replace(ENTITY_LT,"<");s=s.replace(ENTITY_GT,"&");s=s.replace(ENTITY_QUOT,"\"");s=s.replace(ENTITY_APOS,"'");s=s.replace(ENTITY_AMP,"&");s=s.replace(ENTITY_NBSP," ")}return s};
|
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._TsxSynopsis={};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){if(type==="Tsx<"){let entry,ret;for(entry in this._registry){if(entry.startsWith("Tsx<")){ret=true;break}}return ret||false}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.getTsxRuleSynopsis=function(){var o=this._TsxSynopsis;o.isTsxRC=this.isRegisteredCallback("TsxRenderComponent");o.isTsxWC=this.isRegisteredCallback("TsxWebComponent");o.isTsxJetWC=this.isRegisteredCallback("TsxJetComponent");o.isTsxComp=this.isRegisteredCallback("TsxComponent");o.isTsxElem=this.isRegisteredCallback("TsxElem");o.isTsxProp=this.isRegisteredCallback("TsxProperty");o.isTsxEvent=this.isRegisteredCallback("TsxEvent");o.isTsxStyle=this.isRegisteredCallback("TsxStyle");o.isTsxNamedComp=this.isRegisteredCallback("Tsx<");o.isAnyTsxCompAttr=this.isRegisteredAnyTsxCompAttr();o.isAnyTsxAttr=this.isRegisteredAnyTsxAttr();return o};Registry.prototype.isAnyTsxTypeRegistered=function(){var keys,key,ret,i;keys=Object.keys(this._registry);for(i=0;i<keys.length;i++){key=keys[i];if(ret=key.startsWith("Tsx")){break}}return!!ret};Registry.prototype.isRegisteredAnyTsxCompAttr=function(){var keys,key,ret,i;keys=Object.keys(this._registry);for(i=0;i<keys.length;i++){key=keys[i];if(ret=key.startsWith("Tsx<")&&key.includes("|")){break}}return!!ret};Registry.prototype.isRegisteredAnyTsxAttr=function(){var keys,key,ret,i;keys=Object.keys(this._registry);for(i=0;i<keys.length;i++){key=keys[i];if(ret=key.startsWith("Tsx<")&&key.includes("=")&&!key.includes("|")){break}}return!!ret};Registry.prototype.setRuleCallback=function(ruleName,ruleRegs,rsi){var typeObj,regType,rt,callbacks,func,args,elem,isTsx;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(isTsx=rt.startsWith("Tsx<")){regType=rt.substring(3)}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}>`;regType=(isTsx?"Tsx":"")+regType}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,aSource,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++){aSource=Object.keys(source).sort();aSource.forEach(type=>{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 ---";aSource=Object.keys(list2).sort();aSource.forEach(rule=>{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){var ret=s==="attrexpr-$props";return ret?!ret:RULE_RE.test(s)};module.exports=Registry;
|
|
6
|
+
const RULE_RE=new RegExp(/[~`!#$%\^&*+\[\]\\';,/{}|\\"\?]/);var Registry=function(appCtx){this._registry={};this._regexps={};this._reObjs={};this._TsxSynopsis={};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){if(type==="Tsx<"){let entry,ret;for(entry in this._registry){if(entry.startsWith("Tsx<")){ret=true;break}}return ret||false}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.getTsxRuleSynopsis=function(){var o=this._TsxSynopsis;o.isTsxRC=this.isRegisteredCallback("TsxRenderComponent");o.isTsxWC=this.isRegisteredCallback("TsxWebComponent");o.isTsxJetWC=this.isRegisteredCallback("TsxJetComponent");o.isTsxComp=this.isRegisteredCallback("TsxComponent");o.isTsxElem=this.isRegisteredCallback("TsxElem");o.isTsxProp=this.isRegisteredCallback("TsxProperty");o.isTsxEvent=this.isRegisteredCallback("TsxEvent");o.isTsxStyle=this.isRegisteredCallback("TsxStyle");o.isTsxNamedComp=this.isRegisteredCallback("Tsx<");o.isAnyTsxCompAttr=this.isRegisteredAnyTsxCompAttr();o.isAnyTsxAttr=this.isRegisteredAnyTsxAttr();return o};Registry.prototype.isAnyTsxTypeRegistered=function(){var keys,key,ret,i;keys=Object.keys(this._registry);for(i=0;i<keys.length;i++){key=keys[i];if(ret=key.startsWith("Tsx")){break}}return!!ret};Registry.prototype.isRegisteredAnyTsxCompAttr=function(){var keys,key,ret,i;keys=Object.keys(this._registry);for(i=0;i<keys.length;i++){key=keys[i];if(ret=key.startsWith("Tsx<")&&key.includes("|")){break}}return!!ret};Registry.prototype.isRegisteredAnyTsxAttr=function(){var keys,key,ret,i;keys=Object.keys(this._registry);for(i=0;i<keys.length;i++){key=keys[i];if(ret=key.startsWith("Tsx<")&&key.includes("=")&&!key.includes("|")){break}}return!!ret};Registry.prototype.setRuleCallback=function(ruleName,ruleRegs,rsi){var typeObj,regType,rt,callbacks,func,args,attrib,elem,isTsx;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(isTsx=rt.startsWith("Tsx<")){regType=rt.substring(3)}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}>`;regType=(isTsx?"Tsx":"")+regType}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,aSource,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++){aSource=Object.keys(source).sort();aSource.forEach(type=>{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 ---";aSource=Object.keys(list2).sort();aSource.forEach(rule=>{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){var ret=s==="attrexpr-$props";return ret?!ret: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 OJC_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"ojc";const VDOM_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"vdom";const JETVDOM_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"jetvdom";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-","wdt-","vdom-","jetvdom-","exch-","demo-"];const RESERVED_PACK_PREFIX=["JAF","JET","SPOC","CSP","JETWC","JETWCO","VDOM","JETVDOM","WDT","DEMO"];const NO_MSGID_PACKS=[];const RULE_STATUS=["prod","production","ready","beta","alpha","deprecated"];const RULE_OPTS_JAF=["enabled","severity","status","filetype","group","jetver","theme","variants","inservice","amd","customopts","issuetag"];const OPT_SEVERITY="severity";const FUNCTION="function";const COLON=":";const RULE_RE=new RegExp(/[~`!#$%\^&*+\[\]\\';,/{}|\\"\?]/,"g");const JAF_RULEOPT_RE=RegExp(/^(\$|jet|jaf|oj|vdom|spoc|wdt|csp|_)/);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,msgCtx,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._tsxUtils=appCtx.tsxUtils;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._RSI={};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.utils.msgLib={msg:msgCtx.msg,error:msgCtx.error,info:msgCtx.info,debug:msgCtx.debug,assert:msgCtx.assert};this._registerCtx.utils.sevLib=this._severity.getSevLib();this._registerCtx.utils.OjetLib=appCtx.ojetLib;this._registerCtx.utils.pluginLib=appCtx.plugin.getPluginLib();this._msgCtx=msgCtx;this._msg=msgCtx.msg;this._info=msgCtx.info;this._debug=msgCtx.debug;this._error=msgCtx.error;this._warn=msgCtx.warn;this._assert=msgCtx.assert;this._debugMode=msgCtx.isDebug;this._verboseMode=msgCtx.isVerbose;if(!this._ruleSets){this._ruleSets=[]}let rsi=this._RSI.JAF=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._RSI.JET=rsi;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,JET_BUILTIN_RULES_PATH):null,"builtin":true});this._RSI.OJC=rsi;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,OJC_BUILTIN_RULES_PATH):null,"builtin":true});this._RSI.VDOM=rsi;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,VDOM_BUILTIN_RULES_PATH):null,"builtin":true});this._RSI.JETVDOM=rsi;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,JETVDOM_BUILTIN_RULES_PATH):null,"builtin":true})}if(config._config.builtinCspRules){this._RSI.CSP=rsi;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._RSI.JETWC=rsi;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._RSI.JETWCO=rsi;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._RSI.SPOC=rsi;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._RSI.OJCMIG=rsi;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._RSI.WEBDT=rsi;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]){let amdpref=apack.rulesJson.prefix;if(amdpref){this._RSI[amdpref]=rsi}this._ruleSets.splice(rsi++,0,{enabled:true,path:null,builtin:false,amdpack:apack})}}}};RuleSet.prototype.loadRulePacks=function(config,isDryRun,isRuleDump,fnSetJafMsgIds){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._RSI,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)){let rspath=rulePath?` at '${rulePath}'`:"";this._error(`Rule pack${rspath} cannot use use reserved prefix '${prefix}'!`);break}}for(j=0;j<this._rulesetSummary.length;j++){if(this._rulesetSummary[j].prefix===prefix){let rspath,rpath;if(rspath=this._rulesetSummary[j].path){rspath=` at '${this._rulesetSummary[j].path}'`}else{rspath=" by another rulepack"}rpath=rulePath?` at '${rulePath}'`:"";this._error(`Rule pack prefix '${prefix}'${rpath} ignored - previously defined${rspath}.`);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(rule.issueTag){if(typeof rule.issueTag!=="string"){this._error(`Syntax - rules.json for pack '${prefix}' rule '${ruleName}' : 'issueTag' is not a string.`);break}}}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){let n=this._rulePacks.length;this._info(`[info]: ------ ${n} Built-in Rulepack${n===1?"":"s"} 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_EnableDisable();this._postProcess_RuleNames();if(!this._processRuleSets(fnSetJafMsgIds)){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_EnableDisable=function(){var rs,rm,are,ard,count=0,n;rm=this._config.ruleMods;if(rm&&(rm.enable||rm.disable)){rs=this._ruleSets;if(are=rm.enable){n=_replaceGroups(are,rs);if(n){are=_removeDups(are);count+=n}}if(ard=rm.disable){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(coreLoad,jafLoad){var msgObj,rp,rs,o,rsi,fpath,err;if(coreLoad){this._msgIds=null}if(!coreLoad&&!jafLoad){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._RSI,this._appCtx)}}else{if(rs.builtin){o=this._nd.msgidLoader(this._nd,rsi,this._ruleSets[rsi],this._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}if(jafLoad){break}}}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(fnSetJafMsgIds){var ruleName,ruleNamesWild,rulePack,rules,opts,opt,ruleJS,rule,rulePath,packStat,ruleDiscriminant,variant,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}}if(ruleDiscriminant=this._config.ruleDiscriminant){if(temp=opts.variants){if(!this._utils.isObject(temp)){this._error(`rule '${ruleName}' - rule option 'variants' is not an object`);opts.enabled=false;continue}for(let dis in temp){if(dis!=="redwood-strict"||dis!==ruleDiscriminant){continue}variant=temp[dis];if(!this._utils.isObject(variant)){this._error(`rule '${ruleName}' - rule variant '${dis}' is not an object`);opts.enabled=false;continue}if(variant.severity){if(typeof variant.severity==="string"){opts.severity=variant.severity}else{this._error(`rule '${ruleName}' - rule variant '${dis}' - 'severity' : expected a string`);opts.enabled=false;continue}}if(variant.hasOwnProperty("enabled")){if(typeof variant.enabled==="boolean"){opts.enabled=variant.enabled;if(!opts.enabled){this._showIgnoredRule(`rule '${ruleName}' disabled by ruleDiscriminant/variant '${dis}'`);continue}}else{this._error(`rule '${ruleName}' - rule variant '${dis}' - 'enabled' : expected a boolean`);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){var __self=this;function _unsupFileType(opts,isArray){let ft=isArray?opts.filetype.join("', '"):opts.filetype;__self._showIgnoredRule(`rule '${ruleName}' ignored by 'filetype' value${isArray?"s":""} '${ft}'`);opts.enabled=false};if(Array.isArray(opts.filetype)){let ftcount=0;for(j=0;j<opts.filetype.length;j++){opts.filetype[j]=opts.filetype[j].toLowerCase();if(!FILETYPE.isFileTypeSupported(opts.filetype[j])){ftcount++;continue}}if(ftcount===opts.filetype.length){if(!opts.$required){_unsupFileType(opts,true);continue}}}else{if(!FILETYPE.isFileTypeSupported(opts.filetype)){if(!opts.$required){_unsupFileType(opts,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(opts.hasOwnProperty("customOpts")){if(!this._utils.isObject(opts.customOpts)){this._error(`rule '${ruleName}' - rule option 'customOpts' is not an object`);opts.enabled=false;continue}}if(opts.enabled){for(opt in opts){if(!this._isJafRuleOption(opt)){this._msgCtx.jafMsg("jaf-sys-rule-opt",`Error - rule '${ruleName}' unknown top-level config option property '${opt}'. (If a custom property, move to the rule's 'customOpts' property).`,"E");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){let FTypeIsArray=Array.isArray(opts.filetype);if(FTypeIsArray||typeof opts.filetype==="string"){if(opts.filetype==="js"||FTypeIsArray&&opts.filetype.includes("js")){this._registerCtx.jsNodeTypes=AstNodeTypes}else if(opts.filetype==="ts"||FTypeIsArray&&opts.filetype.includes("ts")){this._registerCtx.tsNodeTypes=AstNodeTypes}else if(opts.filetype==="tsx"||FTypeIsArray&&opts.filetype.includes("tsx")){this._registerCtx.tsNodeTypes=AstNodeTypes;this._registerCtx.utils.tsxUtils=this._tsxUtils}}}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)}}if(rsi===0){fnSetJafMsgIds(this.loadMsgIds(false,true))}}this._showIgnoredRule(null);return true};RuleSet.prototype._isJafRuleOption=function(prop){var prop_lc=prop.toLowerCase();return RULE_OPTS_JAF.includes(prop_lc)||JAF_RULEOPT_RE.test(prop_lc)};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(isBuiltinRules){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;function _mergeCustomOpts(ruleCustomOpts,modCustomOpts){var p;for(p in modCustomOpts){ruleCustomOpts[p]=modCustomOpts[p]}};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}if(prop==="customOpts"){if(!ruleOpts.customOpts){ruleOpts[prop]=configOpts[prop]}else{_mergeCustomOpts(ruleOpts.customOpts,configOpts.customOpts)}}else{ruleOpts[prop]=configOpts[prop];if(prop===OPT_SEVERITY){ruleOpts.$sevLocked=true}}}};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;
|
|
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 OJC_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"ojc";const VDOM_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"vdom";const JETVDOM_BUILTIN_RULES_PATH=BUILTIN_RULEPACK_PATH+"jetvdom";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-","wdt-","vdom-","jetvdom-","exch-","demo-"];const RESERVED_PACK_PREFIX=["JAF","JET","SPOC","CSP","JETWC","JETWCO","VDOM","JETVDOM","WDT","DEMO"];const NO_MSGID_PACKS=[];const RULE_STATUS=["prod","production","ready","beta","alpha","deprecated"];const RULE_OPTS_JAF=["enabled","severity","status","filetype","group","jetver","theme","variants","inservice","amd","customopts","issuetag"];const OPT_SEVERITY="severity";const FUNCTION="function";const COLON=":";const RULE_RE=new RegExp(/[~`!#$%\^&*+\[\]\\';,/{}|\\"\?]/,"g");const JAF_RULEOPT_RE=RegExp(/^(\$|jet|jaf|oj|vdom|spoc|wdt|csp|_)/);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,msgCtx,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._isAPI=!this._isCLI&&!this._isAMD;this._isCliOrApi=!this._isAMD;this._metaLib=appCtx.metaLib;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._tsxUtils=appCtx.tsxUtils;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._RSI={};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.utils.msgLib={msg:msgCtx.msg,error:msgCtx.error,info:msgCtx.info,debug:msgCtx.debug,assert:msgCtx.assert};this._registerCtx.utils.sevLib=this._severity.getSevLib();this._registerCtx.utils.OjetLib=appCtx.ojetLib;this._registerCtx.utils.pluginLib=appCtx.plugin.getPluginLib();this._msgCtx=msgCtx;this._msg=msgCtx.msg;this._info=msgCtx.info;this._debug=msgCtx.debug;this._error=msgCtx.error;this._warn=msgCtx.warn;this._assert=msgCtx.assert;this._debugMode=msgCtx.isDebug;this._verboseMode=msgCtx.isVerbose;if(!this._ruleSets){this._ruleSets=[]}let rsi=this._RSI.JAF=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._RSI.JET=rsi;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,JET_BUILTIN_RULES_PATH):null,"builtin":true});this._RSI.OJC=rsi;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,OJC_BUILTIN_RULES_PATH):null,"builtin":true});this._RSI.VDOM=rsi;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,VDOM_BUILTIN_RULES_PATH):null,"builtin":true});this._RSI.JETVDOM=rsi;this._ruleSets.splice(rsi++,0,{"enabled":true,"path":this._isCliOrApi?nodeDeps.path.join(__dirname,JETVDOM_BUILTIN_RULES_PATH):null,"builtin":true})}if(config._config.builtinCspRules){this._RSI.CSP=rsi;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._RSI.JETWC=rsi;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._RSI.JETWCO=rsi;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._RSI.SPOC=rsi;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._RSI.OJCMIG=rsi;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._RSI.WEBDT=rsi;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]){let amdpref=apack.rulesJson.prefix;if(amdpref){this._RSI[amdpref]=rsi}this._ruleSets.splice(rsi++,0,{enabled:true,path:null,builtin:false,amdpack:apack})}}}};RuleSet.prototype.loadRulePacks=function(config,isDryRun,isRuleDump,fnSetJafMsgIds){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._RSI,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)){let rspath=rulePath?` at '${rulePath}'`:"";this._error(`Rule pack${rspath} cannot use use reserved prefix '${prefix}'!`);break}}for(j=0;j<this._rulesetSummary.length;j++){if(this._rulesetSummary[j].prefix===prefix){let rspath,rpath;if(rspath=this._rulesetSummary[j].path){rspath=` at '${this._rulesetSummary[j].path}'`}else{rspath=" by another rulepack"}rpath=rulePath?` at '${rulePath}'`:"";this._error(`Rule pack prefix '${prefix}'${rpath} ignored - previously defined${rspath}.`);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(rule.issueTag){if(typeof rule.issueTag!=="string"){this._error(`Syntax - rules.json for pack '${prefix}' rule '${ruleName}' : 'issueTag' is not a string.`);break}}}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){let n=this._rulePacks.length;this._info(`[info]: ------ ${n} Built-in Rulepack${n===1?"":"s"} 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_EnableDisable();this._postProcess_RuleNames();if(!this._processRuleSets(fnSetJafMsgIds)){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_EnableDisable=function(){var rs,rm,are,ard,count=0,n;rm=this._config.ruleMods;if(rm&&(rm.enable||rm.disable)){rs=this._ruleSets;if(are=rm.enable){n=_replaceGroups(are,rs);if(n){are=_removeDups(are);count+=n}}if(ard=rm.disable){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(coreLoad,jafLoad){var msgObj,rp,rs,o,rsi,fpath,err;if(coreLoad){this._msgIds=null}if(!coreLoad&&!jafLoad){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._RSI,this._appCtx)}}else{if(rs.builtin){o=this._nd.msgidLoader(this._nd,rsi,this._ruleSets[rsi],this._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}if(jafLoad){break}}}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(fnSetJafMsgIds){var ruleName,ruleNamesWild,rulePack,rules,opts,opt,ruleJS,rule,rulePath,packStat,ruleDiscriminant,variant,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}}if(ruleDiscriminant=this._config.ruleDiscriminant){if(temp=opts.variants){if(!this._utils.isObject(temp)){this._error(`rule '${ruleName}' - rule option 'variants' is not an object`);opts.enabled=false;continue}for(let dis in temp){if(dis!=="redwood-strict"||dis!==ruleDiscriminant){continue}variant=temp[dis];if(!this._utils.isObject(variant)){this._error(`rule '${ruleName}' - rule variant '${dis}' is not an object`);opts.enabled=false;continue}if(variant.severity){if(typeof variant.severity==="string"){opts.severity=variant.severity}else{this._error(`rule '${ruleName}' - rule variant '${dis}' - 'severity' : expected a string`);opts.enabled=false;continue}}if(variant.hasOwnProperty("enabled")){if(typeof variant.enabled==="boolean"){opts.enabled=variant.enabled;if(!opts.enabled){this._showIgnoredRule(`rule '${ruleName}' disabled by ruleDiscriminant/variant '${dis}'`);continue}}else{this._error(`rule '${ruleName}' - rule variant '${dis}' - 'enabled' : expected a boolean`);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){var __self=this;function _unsupFileType(opts,isArray){let ft=isArray?opts.filetype.join("', '"):opts.filetype;__self._showIgnoredRule(`rule '${ruleName}' ignored by 'filetype' value${isArray?"s":""} '${ft}'`);opts.enabled=false};if(Array.isArray(opts.filetype)){let ftcount=0;for(j=0;j<opts.filetype.length;j++){opts.filetype[j]=opts.filetype[j].toLowerCase();if(!FILETYPE.isFileTypeSupported(opts.filetype[j])){ftcount++;continue}}if(ftcount===opts.filetype.length){if(!opts.$required){_unsupFileType(opts,true);continue}}}else{if(!FILETYPE.isFileTypeSupported(opts.filetype)){if(!opts.$required){_unsupFileType(opts,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(opts.hasOwnProperty("customOpts")){if(!this._utils.isObject(opts.customOpts)){this._error(`rule '${ruleName}' - rule option 'customOpts' is not an object`);opts.enabled=false;continue}}if(opts.enabled){let packDisabled;for(opt in opts){if(!this._isJafRuleOption(opt)){if(!this._handleTopLevelOption(ruleName,opt,opts)){packDisabled=true}}}if(packDisabled){let packInfo=this._rulesetSummary[rsi];this._msgCtx.jafMsg("jaf-sys-rule-pack-disable",`Warning - disabling all rules in pack '${packInfo.prefix}' ('${packInfo.title}') because of previous 'required' rule issues.`,"W");this._disableAllPackRules(rules);break}}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){let FTypeIsArray=Array.isArray(opts.filetype);if(FTypeIsArray||typeof opts.filetype==="string"){if(opts.filetype==="js"||FTypeIsArray&&opts.filetype.includes("js")){this._registerCtx.jsNodeTypes=AstNodeTypes}else if(opts.filetype==="ts"||FTypeIsArray&&opts.filetype.includes("ts")){this._registerCtx.tsNodeTypes=AstNodeTypes}else if(opts.filetype==="tsx"||FTypeIsArray&&opts.filetype.includes("tsx")){this._registerCtx.tsNodeTypes=AstNodeTypes;this._registerCtx.utils.tsxUtils=this._tsxUtils}}}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)}}if(rsi===0){fnSetJafMsgIds(this.loadMsgIds(false,true))}}this._showIgnoredRule(null);return true};RuleSet.prototype._handleTopLevelOption=function(ruleName,opt,opts){let emitSev,emitType;let required=opts.$required?"'required '":"";function _setErr(){emitSev="Error";emitType="E"}function _setWarn(){emitSev="Warning";emitType="W"}this._isAMD||this._isAPI?_setWarn():_setErr();this._msgCtx.jafMsg("jaf-sys-rule-opt",`${emitSev} - ${required}rule '${ruleName}' declares unknown top-level config option property '${opt}'. (If a custom property, move to the rule's 'customOpts' property).`,emitType);if(this._isAMD||this._isAPI){if(required){return false}else{this._msgCtx.jafMsg("jaf-sys-rule-disable",`${emitSev} - ${required}rule '${ruleName}' has been disabled due to top-level rule property '${opt}'.`,emitType);opts.enabled=false;return true}}return true};RuleSet.prototype._isJafRuleOption=function(prop){var prop_lc=prop.toLowerCase();return RULE_OPTS_JAF.includes(prop_lc)||JAF_RULEOPT_RE.test(prop_lc)};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(isBuiltinRules){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;function _mergeCustomOpts(ruleCustomOpts,modCustomOpts){var p;for(p in modCustomOpts){ruleCustomOpts[p]=modCustomOpts[p]}};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}if(prop==="customOpts"){if(!ruleOpts.customOpts){ruleOpts[prop]=configOpts[prop]}else{_mergeCustomOpts(ruleOpts.customOpts,configOpts.customOpts)}}else{ruleOpts[prop]=configOpts[prop];if(prop===OPT_SEVERITY){ruleOpts.$sevLocked=true}}}};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};RuleSet.prototype._disableAllPackRules=function(rules){var ruleName,opts,n=0;for(ruleName in rules){opts=rules[ruleName];opts.enabled=false;n++;if(this._isDebug){this._debug(`rule '${ruleName}' disabled due pack shutdown.`)}}return n};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;
|