@oracle/oraclejet-audit 14.1.3 → 15.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/corePackMigrator/cli.js +6 -0
- package/corePackMigrator/corePackMigrator.js +10 -0
- package/corePackMigrator/metadata/avatarMetadata.json +40 -0
- package/corePackMigrator/metadata/buttonMetadata.json +55 -0
- package/corePackMigrator/metadata/collapsibleMetadata.json +15 -0
- package/corePackMigrator/metadata/filePickerMetadata.json +8 -0
- package/corePackMigrator/metadata/inputNumberMetadata.json +56 -0
- package/corePackMigrator/metadata/inputPasswordMetadata.json +50 -0
- package/corePackMigrator/metadata/inputTextMetadata.json +62 -0
- package/corePackMigrator/metadata/legendItemMetadata.json +8 -0
- package/corePackMigrator/metadata/legendMetadata.json +18 -0
- package/corePackMigrator/metadata/legendSectionMetadata.json +8 -0
- package/corePackMigrator/metadata/listItemLayoutMetadata.json +15 -0
- package/corePackMigrator/metadata/listviewMetadata.json +8 -0
- package/corePackMigrator/metadata/messagesMetadata.json +35 -0
- package/corePackMigrator/metadata/progressBarMetadata.json +15 -0
- package/corePackMigrator/metadata/progressCircleMetadata.json +8 -0
- package/corePackMigrator/metadata/ratingGaugeMetadata.json +78 -0
- package/corePackMigrator/metadata/selectManyMetadata.json +39 -0
- package/corePackMigrator/metadata/selectSingleMetadata.json +39 -0
- package/corePackMigrator/metadata/statusMeterGaugeMetadata.json +99 -0
- package/corePackMigrator/metadata/textAreaMetadata.json +44 -0
- package/corePackMigrator/resource/astUtils.js +6 -0
- package/corePackMigrator/resource/componentMigrator.js +6 -0
- package/corePackMigrator/resource/fileScanner.js +6 -0
- package/corePackMigrator/resource/htmlUtils.js +6 -0
- package/corePackMigrator/resource/manifest.json +102 -0
- package/corePackMigrator/resource/migrationConfig.json +21 -0
- package/corePackMigrator/templates/componentMetaData.json +119 -0
- package/corePackMigrator/templates/migrationConfig.json +17 -0
- package/corePackMigrator/utilities/logging.js +6 -0
- package/jaf-amd.js +1 -1
- package/lib/AST_Ts.js +1 -1
- package/lib/Cli.js +1 -1
- package/lib/Components.js +1 -1
- package/lib/Config.js +1 -1
- package/lib/ConfigLib.js +1 -1
- package/lib/DomUtils.js +1 -1
- package/lib/FileIndex.js +1 -1
- package/lib/FileSet.js +1 -1
- package/lib/FsUtils.js +1 -1
- package/lib/HtmlUtils.js +1 -1
- package/lib/JsonLoader.js +1 -1
- package/lib/MetaLib.js +1 -1
- package/lib/NetUtils.js +1 -1
- package/lib/Parser.js +1 -1
- package/lib/RegTypes.js +1 -1
- package/lib/Registry.js +1 -1
- package/lib/Reporter.js +1 -1
- package/lib/RulePack.js +1 -1
- package/lib/RuleSet.js +1 -1
- package/lib/Rules.js +1 -1
- package/lib/Scope.js +1 -1
- package/lib/Ts.js +1 -1
- package/lib/TsxUtils.js +1 -1
- package/lib/TsxUtils2.js +6 -0
- package/lib/Utils.js +1 -1
- package/lib/ZipUtils.js +1 -1
- package/lib/checkage.js +1 -1
- package/lib/cmdline.js +1 -1
- package/lib/defaults.js +1 -1
- package/lib/exportRules.js +1 -1
- package/lib/filetypes.js +1 -1
- package/lib/groups.js +1 -1
- package/lib/help.js +1 -1
- package/lib/jetver.js +1 -1
- package/lib/jsx.js +1 -1
- package/lib/maint.js +6 -0
- package/lib/manpage.js +1 -1
- package/lib/manual.js +1 -1
- package/lib/migrator.js +6 -0
- package/lib/msgidLoader.js +1 -1
- package/lib/ns.js +1 -1
- package/lib/outfile.js +1 -1
- package/lib/schema.js +1 -1
- package/lib/scopewalker.js +1 -1
- package/libext/expparser.js +1 -1
- package/meta/14.0.0/jetauditmeta.js +1 -1
- package/meta/14.1.0/jetauditmeta.js +1 -1
- package/meta/15.0.0/jetauditmeta.js +9 -0
- package/meta/metaverlist.json +1 -1
- package/package.json +16 -8
- package/profiles/redwood-strict.json +2 -1
- package/rulepacks/csp/csp-html-script-unsafe-inline.js +1 -1
- package/rulepacks/csp/csp-html-unsafe-expr.js +1 -1
- package/rulepacks/csp/csp-js-script-unsafe-eval.js +1 -1
- package/rulepacks/csp/csp-js-style-unsafe-inline.js +1 -1
- package/rulepacks/csp/csp-json-unsafe-expr.js +6 -0
- package/rulepacks/csp/msgid.json +1 -1
- package/rulepacks/csp/rules.json +1 -1
- package/rulepacks/jetwc/jetwc-absolute-jetversion.js +1 -1
- package/rulepacks/jetwc/jetwc-aria-redefinition.js +1 -1
- package/rulepacks/jetwc/jetwc-bootstrap.js +1 -1
- package/rulepacks/jetwc/jetwc-compjson-bp-ar.js +1 -1
- package/rulepacks/jetwc/jetwc-compjson-bp-obj.js +1 -1
- package/rulepacks/jetwc/jetwc-component-dependencies.js +1 -1
- package/rulepacks/jetwc/jetwc-component-displayname.js +1 -1
- package/rulepacks/jetwc/jetwc-component-foldername.js +1 -1
- package/rulepacks/jetwc/jetwc-component-location.js +1 -1
- package/rulepacks/jetwc/jetwc-component-type.js +1 -1
- package/rulepacks/jetwc/jetwc-css-oj-complete.js +1 -1
- package/rulepacks/jetwc/jetwc-css-pack-load-path.js +6 -0
- package/rulepacks/jetwc/jetwc-css-scoping.js +1 -1
- package/rulepacks/jetwc/jetwc-data-property-prefix.js +1 -1
- package/rulepacks/jetwc/jetwc-deprecated-lifecycle.js +1 -1
- package/rulepacks/jetwc/jetwc-disabled-property.js +1 -1
- package/rulepacks/jetwc/jetwc-displayname.js +1 -1
- package/rulepacks/jetwc/jetwc-dynamic-slot-context.js +1 -1
- package/rulepacks/jetwc/jetwc-event-displayname.js +1 -1
- package/rulepacks/jetwc/jetwc-events.js +1 -1
- package/rulepacks/jetwc/jetwc-exchange-images.js +1 -1
- package/rulepacks/jetwc/jetwc-jet-version.js +1 -1
- package/rulepacks/jetwc/jetwc-loader-file.js +1 -1
- package/rulepacks/jetwc/jetwc-markdown-link.js +1 -1
- package/rulepacks/jetwc/jetwc-method-displayname.js +1 -1
- package/rulepacks/jetwc/jetwc-methods.js +1 -1
- package/rulepacks/jetwc/jetwc-namespace.js +1 -1
- package/rulepacks/jetwc/jetwc-nested-defaults.js +1 -1
- package/rulepacks/jetwc/jetwc-nls-languages.js +1 -1
- package/rulepacks/jetwc/jetwc-nls-root.js +1 -1
- package/rulepacks/jetwc/jetwc-oj-register.js +1 -1
- package/rulepacks/jetwc/jetwc-ojcss.js +1 -1
- package/rulepacks/jetwc/jetwc-pack-children.js +1 -1
- package/rulepacks/jetwc/jetwc-packable-components.js +1 -1
- package/rulepacks/jetwc/jetwc-prerelease-dependencies.js +1 -1
- package/rulepacks/jetwc/jetwc-prerelease-pattern.js +1 -1
- package/rulepacks/jetwc/jetwc-prerelease-version.js +1 -1
- package/rulepacks/jetwc/jetwc-property-changed.js +1 -1
- package/rulepacks/jetwc/jetwc-property-displayname.js +1 -1
- package/rulepacks/jetwc/jetwc-property-nesting.js +1 -1
- package/rulepacks/jetwc/jetwc-property-translatable.js +1 -1
- package/rulepacks/jetwc/jetwc-public-modules.js +1 -1
- package/rulepacks/jetwc/jetwc-reference-npm-path.js +6 -0
- package/rulepacks/jetwc/jetwc-register-css.js +1 -1
- package/rulepacks/jetwc/jetwc-register-with-promises.js +1 -1
- package/rulepacks/jetwc/jetwc-require-paths.js +1 -1
- package/rulepacks/jetwc/jetwc-required-subproperty.js +1 -1
- package/rulepacks/jetwc/jetwc-reserved-property.js +1 -1
- package/rulepacks/jetwc/jetwc-schema.js +1 -1
- package/rulepacks/jetwc/jetwc-semantic-version.js +1 -1
- package/rulepacks/jetwc/jetwc-slot-displayname.js +1 -1
- package/rulepacks/jetwc/jetwc-slots.js +1 -1
- package/rulepacks/jetwc/jetwc-standard-files.js +1 -1
- package/rulepacks/jetwc/jetwc-status-since.js +6 -0
- package/rulepacks/jetwc/jetwc-unused-events.js +1 -1
- package/rulepacks/jetwc/jetwc-unused-slots.js +1 -1
- package/rulepacks/jetwc/jetwc-vb-category.js +1 -1
- package/rulepacks/jetwc/jetwc-vb-icon.js +1 -1
- package/rulepacks/jetwc/jetwc-vcomponent-jetversion.js +1 -1
- package/rulepacks/jetwc/jetwc-vcomponent-loader.js +1 -1
- package/rulepacks/jetwc/jetwc-vcomponent-version.js +1 -1
- package/rulepacks/jetwc/jetwc-version-openrange.js +1 -1
- package/rulepacks/jetwc/jetwc-writeback-required.js +1 -1
- package/rulepacks/jetwc/msgid.json +1 -1
- package/rulepacks/jetwc/rules.json +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-auditComponentCacheManager.js +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-commonListenerImpls.js +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-componentAuditUtils.js +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-componentFinder.js +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-preCompiler.js +1 -1
- package/rulepacks/jetwc-lib/jetwcutils-tsxUtils.js +1 -1
- package/rulepacks/jetwco/jetwco-bootstrap.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-componentType.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-dependencies.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-dynamicSlots.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-eventBubbles.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-eventCancelable.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-eventPayload.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-events.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-helpers.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-jetVer.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-methodParamTypes.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-methodParams.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-methodReturnType.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-methods.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-packBundle.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-packBundleContent.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-packContent.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-properties.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-propertyDefault.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-propertyEnumeration.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-propertyReadOnly.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-propertyRequired.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-propertyType.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-propertyWriteback.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-publicModules.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-slotDataVariable.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-slotDataVariableType.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-slots.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-styleClasses.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-styleVariables.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-typeMappingOverrides.js +6 -0
- package/rulepacks/jetwco/jetwco-compjson-ns-reg.js +1 -1
- package/rulepacks/jetwco/jetwco-component-api-baseline-changes.js +1 -1
- package/rulepacks/jetwco/jetwco-component-api-changes.js +1 -1
- package/rulepacks/jetwco/jetwco-component-api-controlled-changes.js +1 -1
- package/rulepacks/jetwco/jetwco-component-cdn.js +1 -1
- package/rulepacks/jetwco/jetwco-description-standards.js +1 -1
- package/rulepacks/jetwco/jetwco-displayname-standards.js +1 -1
- package/rulepacks/jetwco/jetwco-exchange-version-check.js +1 -1
- package/rulepacks/jetwco/jetwco-license-info.js +1 -1
- package/rulepacks/jetwco/jetwco-prerelease-cdn.js +1 -1
- package/rulepacks/jetwco/jetwco-thirdparty-ba.js +1 -1
- package/rulepacks/jetwco/msgid.json +1 -1
- package/rulepacks/jetwco/rules.json +1 -1
- package/rules/jaf/jaf-ts-noparser.js +6 -0
- package/rules/jaf/msgid.json +1 -1
- package/rules/jaf/rules.json +1 -1
- package/rules/jet/helpers/has-slot-name.js +1 -1
- package/rules/jet/helpers/style-selector.js +1 -1
- package/rules/jet/helpers/tsx/has-slot-name.js +6 -0
- package/rules/jet/msgid.json +1 -1
- package/rules/jet/oj-acc-aria-labelledby.js +1 -1
- package/rules/jet/oj-cca-compjson-bp-ar.js +1 -1
- package/rules/jet/oj-cca-compjson-bp-obj.js +1 -1
- package/rules/jet/oj-css-bp-dir-flow.js +1 -1
- package/rules/jet/oj-html-attr-$unique.js +1 -1
- package/rules/jet/oj-html-attr-expr-delims.js +6 -0
- package/rules/jet/oj-html-combo-converter.js +1 -1
- package/rules/jet/oj-html-file-pick-accept.js +1 -1
- package/rules/jet/oj-html-form-bindif.js +1 -1
- package/rules/jet/oj-html-input-isodate.js +1 -1
- package/rules/jet/oj-html-invalid-doctype.js +1 -1
- package/rules/jet/oj-html-msgs-cat-text.js +1 -1
- package/rules/jet/oj-html-ojattr-deprecated.js +1 -1
- package/rules/jet/oj-html-ojattr-enum-deprecated.js +1 -1
- package/rules/jet/oj-html-ojtag-deprecated.js +1 -1
- package/rules/jet/oj-html-ojtag-ns.js +1 -1
- package/rules/jet/oj-html-rating-gauge-track-resize.js +6 -0
- package/rules/jet/oj-html-self-close.js +1 -1
- package/rules/jet/oj-html-slot-deprecated.js +1 -1
- package/rules/jet/oj-html-slot-item-minmax.js +1 -1
- package/rules/jet/oj-html-slot-name.js +1 -1
- package/rules/jet/oj-html-slot-pref-content.js +1 -1
- package/rules/jet/oj-html-style.js +1 -1
- package/rules/jet/oj-html-stylesel.js +1 -1
- package/rules/jet/oj-html-tabbar-edge.js +6 -0
- package/rules/jet/oj-html-unsup-theme.js +1 -1
- package/rules/jet/oj-html-wctag-maintenance.js +1 -1
- package/rules/jet/oj-html-wctag-nested.js +1 -1
- package/rules/jet/oj-html-wctag-supersedes.js +6 -0
- package/rules/jet/oj-js-numconv-pattern.js +6 -0
- package/rules/jet/oj-ts-numconv-pattern.js +6 -0
- package/rules/jet/oj-tsx-5-tag-obs.js +1 -1
- package/rules/jet/oj-tsx-acc-avatar-aria-role.js +6 -0
- package/rules/jet/oj-tsx-acc-button-onclick.js +1 -1
- package/rules/jet/oj-tsx-aria-ojselector-labelledby.js +1 -1
- package/rules/jet/oj-tsx-aria-prop.js +1 -1
- package/rules/jet/oj-tsx-attr-req.js +1 -1
- package/rules/jet/oj-tsx-cca-tagname.js +1 -1
- package/rules/jet/oj-tsx-combo-converter.js +1 -1
- package/rules/jet/oj-tsx-databind-all.js +1 -1
- package/rules/jet/oj-tsx-dlg-title.js +1 -1
- package/rules/jet/oj-tsx-form-bindif.js +6 -0
- package/rules/jet/oj-tsx-form-noflex.js +6 -0
- package/rules/jet/oj-tsx-input-isodate.js +1 -1
- package/rules/jet/oj-tsx-ojattr-deprecated.js +6 -0
- package/rules/jet/oj-tsx-ojattr-enum-deprecated.js +6 -0
- package/rules/jet/oj-tsx-ojattr-value.js +1 -1
- package/rules/jet/oj-tsx-ojattr.js +1 -1
- package/rules/jet/oj-tsx-ojtag-deprecated.js +1 -1
- package/rules/jet/oj-tsx-ojtag-ns.js +6 -0
- package/rules/jet/oj-tsx-pageopts-type.js +1 -1
- package/rules/jet/oj-tsx-picker-attrs.js +1 -1
- package/rules/jet/oj-tsx-prop-inline-definition.js +1 -1
- package/rules/jet/oj-tsx-rating-gauge-size.js +1 -1
- package/rules/jet/oj-tsx-rating-gauge-track-resize.js +6 -0
- package/rules/jet/oj-tsx-slot-deprecated.js +6 -0
- package/rules/jet/oj-tsx-slot-pref-content.js +6 -0
- package/rules/jet/oj-tsx-tabbar-edge.js +6 -0
- package/rules/jet/oj-tsx-unsup-theme.js +1 -1
- package/rules/jet/oj-tsx-wctag-maintenance.js +1 -1
- package/rules/jet/oj-tsx-wctag-nested.js +1 -1
- package/rules/jet/rules.json +1 -1
- package/schema/component-schema.json +1 -1
- package/src/JafCore.js +1 -1
- package/types/index.d.ts +6 -4
- package/rules/jet/oj-html-cspexpr.js +0 -6
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-","exch-","demo-"];const RESERVED_PACK_PREFIX=["JAF","JET","SPOC","CSP","JETWC","JETWCO","DEMO"];const NO_MSGID_PACKS=[];const RULE_STATUS=["prod","production","ready","beta","alpha","deprecated"];const RULE_OPTS_JAF=["enabled","severity","status","filetype","group","jetver","theme","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,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:appCtx.msg,error:appCtx.error,info:appCtx.info,debug:appCtx.debug,assert:appCtx.assert};this._registerCtx.utils.sevLib=this._severity.getSevLib();this._registerCtx.utils.OjetLib=appCtx.ojetLib;this._registerCtx.utils.pluginLib=appCtx.plugin.getPluginLib();this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._assert=appCtx.assert;this._debugMode=appCtx.debugMode;this._verboseMode=appCtx.verboseMode;if(!this._ruleSets){this._ruleSets=[]}let rsi=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){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()){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(){var msgObj,rp,rs,o,rsi,fpath,err;if(this._msgIds){return this._msgIds}if(this._rulePacks&&this._rulePacks.length){for(rsi=0;rsi<this._rulePacks.length;rsi++){rp=this._rulePacks[rsi];rs=this._ruleSets[rsi];if(rs.builtin&&NO_MSGID_PACKS.includes(rs.prefix)){continue}if(rs.enabled){if(!msgObj){msgObj={}}o=null;try{if(this._isCliOrApi){fpath=this._nd.path.join(rp.path,"msgid.json");if(rs.builtin||this._fsUtils.fileExists(fpath)){o=this._nd.msgidLoader(fpath,this._nd,this._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}}}return err?-1:this._msgIds=msgObj};RuleSet.prototype.getMsgIds=function(){return this._msgIds};RuleSet.prototype.getLoadedRule=function(rsi,ruleName){return this._shadowRulePacks[rsi][ruleName]};RuleSet.prototype.getSemVer=function(){return this._semVer};RuleSet.prototype._processRuleSets=function(){var ruleName,ruleNamesWild,rulePack,rules,opts,opt,ruleJS,rule,rulePath,packStat,rset,callbacks,callback,atLine,rn,rsi,temp,s,i,j;for(rsi=0;rsi<this._rulePacks.length;rsi++){rulePack=this._rulePacks[rsi];rules=rulePack.rulesJson.rules;rulePack.rulePack=new RulePack(this._rulesetSummary,this._rulePacks,this._shadowRulePacks,rsi,this._appCtx);this._registerCtx.rulePack=rulePack.rulePack;packStat=this._rulesetSummary[rsi].status;for(ruleName in rules){opts=rules[ruleName];if(this._debugMode){this._debug(`Loading rule '${ruleName}'`)}if(opts.hasOwnProperty("inservice")){if(!opts.inservice){this._showIgnoredRule(`rule '${ruleName}' is not in service - ignored`);opts.enabled=false;continue}}try{if(this._isAMD){if(!_isAMDRule(opts)){this._showIgnoredRule(`rule '${ruleName}' is not supported in AMD mode - ignored`);opts.enabled=false;continue}}opts.enabled=typeof opts.enabled==="boolean"?opts.enabled:true;if(!opts.enabled){this._showIgnoredRule(`rule '${ruleName}' is disabled - ignored`);continue}if(opts._rsi===undefined){this._showIgnoredRule(`rule '${ruleName}' does not belong to an active ruleset - ignored`);opts.enabled=false;continue}if(opts.severity){if(typeof opts.severity!=="string"||!this._severity.isValidRuleSeverity(opts.severity)){this._showIgnoredRule(`rule '${ruleName}' has invalid 'severity' of ${opts.severity} - assuming default of '${this._severity.DEFAULT}'`,true);opts.severity=this._severity.DEFAULT;opts.enabled=false}}else{opts.severity=this._severity.DEFAULT}if(opts.group){if(rsi&&!this._isGroupActive(opts.group)){this._showIgnoredRule(`rule '${ruleName}' ignored by group`);opts.enabled=false;continue}}if(!opts.status){opts.status="production"}if(!RULE_STATUS.includes(opts.status)){this._showIgnoredRule(`rule '${ruleName}' invalid 'status' (i.e. not 'production', 'prod', 'ready', 'deprecated', 'beta', 'alpha'`,true);opts.enabled=false;continue}if(!_isStatEnabledByPack(packStat,opts.status)){this._showIgnoredRule(`rule '${ruleName}' status does not match rulepack status - ignored`);opts.enabled=false;continue}if(opts.filetype){if(Array.isArray(opts.filetype)){for(j=0;j<opts.filetype.length;j++){opts.filetype[j]=opts.filetype[j].toLowerCase();if(!FILETYPE.isFileTypeSupported(opts.filetype[j])){this._showIgnoredRule(`rule '${ruleName}' ignored by 'filetype' value '${opts.filetype[j]}'`);opts.enabled=false;continue}}}else{if(!FILETYPE.isFileTypeSupported(opts.filetype)){this._showIgnoredRule(`rule '${ruleName}' ignored by 'filetype' value '${opts.filetype}'`);opts.enabled=false;continue}}}if(!ruleName.startsWith("jaf-")&&this._confNamedRules&&this._confNamedRules.length){if(!ruleNamesWild){ruleNamesWild=[];for(j=0;j<this._confNamedRules.length;j++){rn=this._confNamedRules[j];ruleNamesWild.push(_isRE(rn)?new RegExp(rn):null)}}for(j=0;j<this._confNamedRules.length;j++){if(this._confNamedRules.includes(ruleName)){break}rn=ruleNamesWild[j];if(rn){if(rn.test(ruleName)){break}}}if(j>=this._confNamedRules.length){if(opts.$required){this._showIgnoredRule(`rule '${ruleName}' not excluded by config 'ruleNames'- rule is mandatory`)}else{this._showIgnoredRule(`rule '${ruleName}' ignored - excluded by config 'ruleNames'`);opts.enabled=false}continue}}if(opts.jetver){if(!this._semVer.match(opts.jetver)){this._showIgnoredRule(`rule '${ruleName}' ignored : 'jetVer' option is '${opts.jetver}' but metadata is '${this._semVer.getReference()}'`);opts.enabled=false;continue}}if(opts.theme){temp=opts.theme;if(typeof temp==="string"){temp=opts.theme.toLowerCase();if(temp==="redwood"||temp==="alta"){opts.theme=temp.charAt(0).toUpperCase()+temp.substring(1);if(this._config.theme!==opts.theme){this._showIgnoredRule(`rule '${ruleName}' ignored : 'theme' option '${opts.theme}' excluded by config '${this._config.theme}'`);opts.enabled=false;continue}}else{this._showIgnoredRule(`rule '${ruleName}' theme option '${opts.theme}' - must be 'Redwood' or 'Alta'`,true);opts.enabled=false}}else{if(!Array.isArray(temp)){this._showIgnoredRule(`rule '${ruleName}' theme option - must be a string or a string array`,true);opts.enabled=false;continue}temp.forEach((theme,idx)=>{theme=theme.toLowerCase();if(theme==="redwood"||theme==="alta"){theme=theme.charAt(0).toUpperCase()+theme.substring(1);temp[idx]=theme}else{this._showIgnoredRule(`rule '${ruleName}' theme option '${theme}' - must be 'Redwood' or 'Alta'`,true);opts.enabled=false}});if(opts.enabled&&!opts.theme.includes(this._config.theme)){this._showIgnoredRule(`rule '${ruleName}' ignored : 'theme' option '${opts.theme}' excluded by config '${this._config.theme}'`);opts.enabled=false}}}if(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){let custOpts;if(!this._isJafRuleOption(opt)){if(opts.hasOwnProperty("customOpts")){custOpts=opts.customOpts}else{opts.customOpts=custOpts={}}if(!custOpts.hasOwnProperty(opt)){custOpts[opt]=opts[opt]}}}}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)}}}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(!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-","exch-","demo-"];const RESERVED_PACK_PREFIX=["JAF","JET","SPOC","CSP","JETWC","JETWCO","DEMO"];const NO_MSGID_PACKS=[];const RULE_STATUS=["prod","production","ready","beta","alpha","deprecated"];const RULE_OPTS_JAF=["enabled","severity","status","filetype","group","jetver","theme","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,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:appCtx.msg,error:appCtx.error,info:appCtx.info,debug:appCtx.debug,assert:appCtx.assert};this._registerCtx.utils.sevLib=this._severity.getSevLib();this._registerCtx.utils.OjetLib=appCtx.ojetLib;this._registerCtx.utils.pluginLib=appCtx.plugin.getPluginLib();this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._assert=appCtx.assert;this._debugMode=appCtx.debugMode;this._verboseMode=appCtx.verboseMode;if(!this._ruleSets){this._ruleSets=[]}let rsi=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){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()){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(){var msgObj,rp,rs,o,rsi,fpath,err;if(this._msgIds){return this._msgIds}if(this._rulePacks&&this._rulePacks.length){for(rsi=0;rsi<this._rulePacks.length;rsi++){rp=this._rulePacks[rsi];rs=this._ruleSets[rsi];if(rs.builtin&&NO_MSGID_PACKS.includes(rs.prefix)){continue}if(rs.enabled){if(!msgObj){msgObj={}}o=null;try{if(this._isCliOrApi){fpath=this._nd.path.join(rp.path,"msgid.json");if(rs.builtin||this._fsUtils.fileExists(fpath)){o=this._nd.msgidLoader(fpath,this._nd,this._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}}}return err?-1:this._msgIds=msgObj};RuleSet.prototype.getMsgIds=function(){return this._msgIds};RuleSet.prototype.getLoadedRule=function(rsi,ruleName){return this._shadowRulePacks[rsi][ruleName]};RuleSet.prototype.getSemVer=function(){return this._semVer};RuleSet.prototype._processRuleSets=function(){var ruleName,ruleNamesWild,rulePack,rules,opts,opt,ruleJS,rule,rulePath,packStat,rset,callbacks,callback,atLine,rn,rsi,temp,s,i,j;for(rsi=0;rsi<this._rulePacks.length;rsi++){rulePack=this._rulePacks[rsi];rules=rulePack.rulesJson.rules;rulePack.rulePack=new RulePack(this._rulesetSummary,this._rulePacks,this._shadowRulePacks,rsi,this._appCtx);this._registerCtx.rulePack=rulePack.rulePack;packStat=this._rulesetSummary[rsi].status;for(ruleName in rules){opts=rules[ruleName];if(this._debugMode){this._debug(`Loading rule '${ruleName}'`)}if(opts.hasOwnProperty("inservice")){if(!opts.inservice){this._showIgnoredRule(`rule '${ruleName}' is not in service - ignored`);opts.enabled=false;continue}}try{if(this._isAMD){if(!_isAMDRule(opts)){this._showIgnoredRule(`rule '${ruleName}' is not supported in AMD mode - ignored`);opts.enabled=false;continue}}opts.enabled=typeof opts.enabled==="boolean"?opts.enabled:true;if(!opts.enabled){this._showIgnoredRule(`rule '${ruleName}' is disabled - ignored`);continue}if(opts._rsi===undefined){this._showIgnoredRule(`rule '${ruleName}' does not belong to an active ruleset - ignored`);opts.enabled=false;continue}if(opts.severity){if(typeof opts.severity!=="string"||!this._severity.isValidRuleSeverity(opts.severity)){this._showIgnoredRule(`rule '${ruleName}' has invalid 'severity' of ${opts.severity} - assuming default of '${this._severity.DEFAULT}'`,true);opts.severity=this._severity.DEFAULT;opts.enabled=false}}else{opts.severity=this._severity.DEFAULT}if(opts.group){if(rsi&&!this._isGroupActive(opts.group)){this._showIgnoredRule(`rule '${ruleName}' ignored by group`);opts.enabled=false;continue}}if(!opts.status){opts.status="production"}if(!RULE_STATUS.includes(opts.status)){this._showIgnoredRule(`rule '${ruleName}' invalid 'status' (i.e. not 'production', 'prod', 'ready', 'deprecated', 'beta', 'alpha'`,true);opts.enabled=false;continue}if(!_isStatEnabledByPack(packStat,opts.status)){this._showIgnoredRule(`rule '${ruleName}' status does not match rulepack status - ignored`);opts.enabled=false;continue}if(opts.filetype){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){let custOpts;if(!this._isJafRuleOption(opt)){if(opts.hasOwnProperty("customOpts")){custOpts=opts.customOpts}else{opts.customOpts=custOpts={}}if(!custOpts.hasOwnProperty(opt)){custOpts[opt]=opts[opt]}}}}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)}}}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(!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;
|
package/lib/Rules.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const RuleContext=require("./RuleContext");const REG=require("../lib/RegTypes");const PROP_FILETYPE="filetype";const FILETYPE_CSS="css";var Rules=function(ruleSets,nodeDeps,config,fnMsgId,appCtx){this._appCtx=appCtx;this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._warn=appCtx.warn;this._assert=appCtx.assert;this._metaLib=appCtx.metaLib;this._reporter=appCtx.reporter;this._Issue=appCtx.Issue;this._semVer=ruleSets.getSemVer();this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._sevLib=appCtx.severity.getSevLib();this._ojetLib=appCtx.ojetLib;this._plugin=appCtx.plugin;this._registry=ruleSets.getRegistry();this._ruleCount=ruleSets.getActiveRuleCount();this._rulesetSummary=ruleSets.getRulesetSummary();this._rulePacks=ruleSets.getRulePacks();this._common=this._createCommon();this._shadowRulePacks=ruleSets.getShadowRulePacks();this._ruleSets=ruleSets;this._Stats=appCtx.Stats;this._isUnitTest=appCtx.isUnitTest;if(this._isUnitTest||config.rulesFired){this._Stats.packRulesFired=[];for(let i=0;i<ruleSets._ruleSets.length;i++)this._Stats.packRulesFired.push({pack:ruleSets._ruleSets[i].prefix,rules:{}})}this._builtinJetRules=null;this._useBuiltinJetRules=true;this._config=config;this._nd=nodeDeps;this._isNode=!!nodeDeps.fs;this._curFile=null;this._getMsgId=fnMsgId;this._sysOpts={verboseMode:appCtx.verboseMode,debugMode:appCtx.debugMode};this._message={msg:this._msg,info:this._info,debug:this._debug,error:this._error,warn:this._warn,assert:this._assert}};Rules.prototype.fireRules=function(ruleCtx,arg1,filepath,filetype,arg2,isEmbeddedCss){var ruleName,callbacks,typeObj;if(this._curFile!==filepath){this._curFile=filepath;this._fileType=filetype}typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type);if(typeObj){if(ruleCtx.type==="TsxWebComponent"||ruleCtx.type==="TsxTag"||ruleCtx.type.startsWith("Tsx<")||ruleCtx.type==="TsxJetComponent"){ruleCtx.type=arg1.type="TsxComponent"}for(ruleName in typeObj){if(this._isRuleDisabledByComment&&this._isRuleDisabledByComment(ruleName)){continue}callbacks=typeObj[ruleName];this._fireRulePreTest(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks)}}};Rules.prototype.setJafLib=function(jl){this._jafLib=jl};Rules.prototype._fireRulePreTest=function(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks){var opts,callback,fileType,i;if(!callbacks){return}for(i=0;i<callbacks.length;i++){callback=callbacks[i];opts=this._getRuleOptionsByName(ruleName,callback.rsi);if(!opts.enabled){return}fileType=opts[PROP_FILETYPE];if(fileType){if(isEmbeddedCss&&!this._isFileTypeOk(fileType,FILETYPE_CSS)){return}if(!this._isFileTypeOk(fileType,this._fileType)){return}}ruleCtx._rsi=callback.rsi;ruleCtx.getMsgId=this._getMsgId;this._fireRule(ruleCtx,ruleName,arg1,arg2,filepath,fileType,callback.cb)}};Rules.prototype._fireRule=function(ruleCtx,ruleName,name,value,filepath,filetype,callback){var rule,msg,ctxType,oFired;ctxType=ruleCtx.type;this._debug("Firing rule "+ruleName+" type="+ctxType+" name="+name+" value="+value);rule=this._getRuleByName(ruleName,ruleCtx._rsi);if(!rule){return}ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;ruleCtx.filepath=filepath;ruleCtx.filetype=filetype;ruleCtx.utils=ruleCtx.utils?ruleCtx.utils:{};ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[ruleCtx._rsi].rulePack;ruleCtx.sysOpts=this._sysOpts;ruleCtx.common=this._common[ruleCtx._rsi];ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.sevLib=this._sevLib;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.jafLib=this._jafLib.getJafLib();ruleCtx.utils.OjetLib=this._ojetLib;ruleCtx.utils.pluginLib=this._plugin.getPluginLib();this._curCtx=ruleCtx;try{if(callback){ruleCtx.rulePack._setCBCtx(ruleCtx);if((ctxType==="attr"||ctxType==="attrexpr"||ctxType==="attrexpr-$props"||ctxType==="event"||ctxType.indexOf("|")>0||ctxType==="class"||ctxType==="style"||ctxType.startsWith("<")&&ctxType.includes("="))&&typeof value!=="string"){if(ctxType==="style"){callback(ruleCtx,name,_extractStyles(value.val),value.rawval)}else{callback(ruleCtx,name,value.val,value.rawval)}}else if(ctxType.startsWith("compjson")||ctxType==="comment"){callback(ruleCtx,value)}else if(ruleCtx.type==="json"){callback(ruleCtx,value.ast)}else{callback(ruleCtx,name,value)}this._Stats.rulesFired++;if(this._isUnitTest||this._config.rulesFired){if(oFired=this._Stats.packRulesFired[ruleCtx._rsi]){oFired=oFired.rules;if(oFired[ruleName]){oFired[ruleName]++}else{oFired[ruleName]=1}}}}else{rule.run(ruleCtx,name,value)}}catch(e){msg=!e||!e.message?"Unknown error (rule "+this._getFileSuffix(ruleCtx.filepath)+" syntax issue?)":e.message;this._error("** running rule "+ruleName+" ["+msg+"]"+"\n - "+ruleCtx.filepath);this._error(e.stack)}};Rules.prototype.makeRuleContext=function(){return new RuleContext};Rules.prototype.isTypeRegistered=function(regType){return this._registry.isRegisteredCallback(regType)};Rules.prototype.isTypeRegisteredAsElemName=function(elem){return this._registry.isRegisteredCallbackRE(elem)};Rules.prototype.setJSCommentCallback=function(fnCB){this._isRuleDisabledByComment=fnCB};Rules.prototype.filterHtmlCallbacks=function(htmlCB){return htmlCB};Rules.prototype.getRulesProse=function(isInternal){var rulePacks,rulePack,rules,rule,ruleName,names,rsi,opts,haveRules,prefix,msgIds,ids;this._nd.exportRules.setupRulesToProse(this._nd,this._config.severity,this._appCtx);msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson;prefix=rules.prefix;this._nd.exportRules.packToProse(rules,rulePack.path,rsi);haveRules=false;rules=rules.rules;names=_getSortedRuleNames(rules);for(ruleName of names){opts=rules[ruleName];if(!opts.enabled||opts.hasOwnProperty("inservice")&&!opts.inservice){continue}opts=this._utils.extend(opts,isInternal);rule=this._shadowRulePacks[rsi][ruleName];ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);this._nd.exportRules.ruleToProse(ruleName,rule,opts,ids);haveRules=true}if(!haveRules){this._nd.exportRules.packToProse()}}return this._nd.exportRules.getProse()};Rules.prototype.getRulesJson=function(active,obj){var rulePacks,rulePack,rulesJson,ruleName,rule,ruleOpts,opts,pack,rsi,prefix,msgIds,ids;msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;this._nd.exportRules.setupRulesToJson(obj,this._config.severity,this._appCtx);for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];this._nd.exportRules.packToJson(rulePack);rulesJson=rulePack.rulesJson;prefix=rulesJson.prefix;for(ruleName in rulesJson.rules){ruleOpts=rulesJson.rules[ruleName];if(ruleOpts.hasOwnProperty("inservice")&&!ruleOpts.inservice){continue}if(active&&!ruleOpts.enabled){continue}opts=this._utils.extend(ruleOpts);ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);if(pack=this._shadowRulePacks[rsi]){rule=pack[ruleName]}else{rule=null}if(!active||rule){this._nd.exportRules.ruleToJson(ruleName,rule,opts,ids,active)}}}return this._nd.exportRules.getJson()};Rules.prototype.getRulesSonar=function(){var rulePacks,rulePack,ruleName,rules,rule,opts,prefix,msgIds,ids,rsi;this._nd.exportRules.setupRulesToXml(this._appCtx);msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson.rules;prefix=rulePack.rulesJson.prefix;for(ruleName in rules){opts=rules[ruleName];if(!opts.enabled||opts.hasOwnProperty("inservice")&&!opts.inservice){continue}opts=this._utils.extend(opts);rule=this._shadowRulePacks[rsi][ruleName];ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);this._nd.exportRules.ruleToXml(ruleName,rule,opts,ids)}}return this._nd.exportRules.getXml()};Rules.prototype.getRuleOptions=function(ruleName,rsi){return this._getRuleOptionsByName(ruleName,rsi)};Rules.prototype.getActiveRuleCount=function(){return this._ruleCount};Rules.prototype.getRuleSetSummaryByIndex=function(rsi){return this._rulesetSummary[rsi]};Rules.prototype.getRulePack=function(rsi){return this._rulePacks[rsi].rulePack};Rules.prototype.getRSIByPrefix=function(prefix){var i,rsi=-1;;for(i=0;i<this._rulesetSummary.length;i++){if(this._rulesetSummary[i].prefix===prefix){rsi=i;break}}return rsi};Rules.prototype.isRuleEnabled=function(ruleName,rsi){if(rsi===undefined){rsi=this.getRSIByRuleName(ruleName);if(rsi<0){return false}}var opts=this._getRuleOptionsByName(ruleName,rsi);return!!(opts&&opts.enabled)};Rules.prototype.getRSIByRuleName=function(ruleName){var rsi,rp,len;len=this._shadowRulePacks.length;for(rsi=0;rsi<len;rsi++){rp=this._shadowRulePacks[rsi];if(rp[ruleName]){break}}return rsi<len?rsi:-1};Rules.prototype.getRuleDescription=function(prefix,ruleName,isShort){var rule,rsi,ret="";rsi=this.getRSIByPrefix(prefix);if(rsi>=0){rule=this._shadowRulePacks[rsi][ruleName];if(rule){ret=isShort?rule.getShortDescription():rule.getDescription()}}return ret};Rules.prototype.getRuleDescriptionEx=function(msgId,ruleName,isShort){var descrip,rule,prefix,msgNum,rsi,msgTab,msgIds,mid,sev,x;var idList=[];if(ruleName){var rp=this._shadowRulePacks;for(rsi=0;rsi<rp.length;rsi++){rule=rp[rsi][ruleName];if(rule){descrip=isShort?rule.getShortDescription():rule.getDescription();if(descrip){msgTab=this._ruleSets.loadMsgIds();if(prefix=this._rulesetSummary[rsi]){prefix=prefix.prefix;if(msgIds=msgTab[prefix]){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}}}break}}}}if(msgId){rsi=this._ruleSets.getRsiFromMsgId(msgId);if(rsi>=0){x=msgId.indexOf("-");prefix=msgId.substring(0,x);msgNum=msgId.substring(x+1);msgTab=this._ruleSets.loadMsgIds();msgIds=msgTab[prefix];if(msgNum.length<4){msgNum="0".repeat(4-msgNum.length)+msgNum}for(mid in msgIds){if(msgIds[mid]===msgNum){x=mid.lastIndexOf("_");ruleName=x>0?mid.substring(0,x):mid;if(descrip=this.getRuleDescription(prefix,ruleName,isShort)){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}break}}}}}if(ruleName){sev=this._getRuleOptionsByName(ruleName,rsi);sev=sev?sev.severity:""}return{descrip:descrip,rule:ruleName,prefix:prefix,sev:sev,idList:idList}};Rules.prototype._getMsgIdsForRule=function(rname,ids,prefix){var r,list=[];prefix=prefix?prefix+"-":"";for(r in ids){if(r.startsWith(rname)){list.push(prefix+ids[r])}}return list};Rules.prototype._showIgnoredRule=function(msg,isError){if(msg){if(!this._ignoredRulesShown){this._info("\n--------- Start-up Rule analysis ---------");this._ignoredRulesShown=true}isError?this._error(msg):this._info(msg)}else if(this._ignoredRulesShown){this._info("------------ End Rule analysis -------------")}};Rules.prototype.fireHookRules=function(ruleCtx,rsi){var ruleName,typeObj,callbacks,callback,opts,rc,i;var _rsi;ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;_rsi=rsi;if(!(typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type))){return}ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.OjetLib=this._ojetLib;ruleCtx.sysOpts=this._sysOpts;ruleCtx.getMsgId=this._getMsgId;for(ruleName in typeObj){callbacks=typeObj[ruleName];if(!callbacks){continue}for(i=0;i<callbacks.length;i++){callback=callbacks[i];if(rsi===undefined){_rsi=callback.rsi}else{if(rsi!==callback.rsi){continue}_rsi=rsi}opts=this._getRuleOptionsByName(ruleName,_rsi);if(ruleCtx.type==="file"||ruleCtx.type==="startscript"){if(opts&&opts.filetype){if(!this._isFileTypeOk(opts.filetype,ruleCtx.filetype)){continue}}}ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[_rsi].rulePack;ruleCtx._rsi=_rsi;ruleCtx.common=this._common[_rsi];this._debug("Firing hook rule "+ruleName+" type="+ruleCtx.type);ruleCtx.rulePack._setCBCtx(ruleCtx);rc=callback.cb(ruleCtx);this._Stats.hooksFired++;if((ruleCtx.phase===REG.PHASE_STARTUP||ruleCtx.phase===REG.PHASE_START_AUDIT||ruleCtx.phase===REG.PHASE_FILE)&&typeof rc==="boolean"&&!rc){this._info("Hook rule ('"+ruleCtx.type+"') veto! by '"+ruleName+"'");return rc}}}return true};Rules.prototype._getRuleByName=function(ruleName,rsi){var rs=this._shadowRulePacks[rsi];return rs[ruleName]};Rules.prototype._getRuleOptionsByName=function(ruleName,rsi){var rulePack=this._rulePacks[rsi];return rulePack.rulesJson.rules[ruleName]};Rules.prototype._isGroupActive=function(group){var groups,defs,def,i;groups=this._config.groups;defs=this._config.defGroups;if(this._checkGroups(groups,group)){return true}if(!defs){return false}for(i=0;i<groups.length;i++){def=groups[i];if(this._checkDefGroup(defs,def,group)){return true}}return false};Rules.prototype._loadBuiltinJetRulesDescriptions=function(){var ruleName,rules;try{if(!this._builtinJetRules){this._builtinJetRules=require("../rules/jet/rules.json")}}catch(e){this._error("Unable to load builtin rule definition file "+e)}if(this._builtinJetRules&&this._builtinJetRules.rules){rules=this._builtinJetRules.rules;for(ruleName in rules){rules[ruleName].$builtin=true}}return this._builtinJetRules};Rules.prototype._isFileTypeOk=function(ruleFileType,fileType){var ret=false;if(Array.isArray(ruleFileType)){ret=ruleFileType.indexOf(fileType)>=0}else{ret=ruleFileType===fileType}return ret};Rules.prototype._createCommon=function(){var i,a=[];for(i=0;i<this._rulesetSummary.length;i++){a.push({})}return a};Rules.prototype._getFileSuffix=function(fp){var s="";if(fp){s=this._nd.path.extname(fp)}return s.length?s:"?"};Rules.prototype.dumpRegistry=function(){return this._registry.dump()};function _extractStyles(s){var a,isExpr,i,sc=";";s=s.trim();isExpr=_isExpr(s);s=s.replace(/[\'\"\[\]\{\}]/g,"").trim();if(!s.includes(";")){if(isExpr){if(s.includes(",")){sc=","}}}a=s.split(sc);for(i=0;i<a.length;i++){a[i]=a[i].trim();if(!a[i].length){a.splice(i,1);i--}}return a};function _isExpr(s){s=s.trim();return s.startsWith("[[")||s.startsWith("{{")};function _getSortedRuleNames(rules){var rule,names=[];for(rule in rules){names.push(rule)}names.sort();return names};module.exports=Rules;
|
|
6
|
+
const RuleContext=require("./RuleContext");const REG=require("../lib/RegTypes");const PROP_FILETYPE="filetype";const FILETYPE_CSS="css";var Rules=function(ruleSets,nodeDeps,config,fnMsgId,appCtx){this._appCtx=appCtx;this._msg=appCtx.msg;this._info=appCtx.info;this._debug=appCtx.debug;this._error=appCtx.error;this._warn=appCtx.warn;this._assert=appCtx.assert;this._metaLib=appCtx.metaLib;this._reporter=appCtx.reporter;this._Issue=appCtx.Issue;this._semVer=ruleSets.getSemVer();this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._sevLib=appCtx.severity.getSevLib();this._ojetLib=appCtx.ojetLib;this._plugin=appCtx.plugin;this._registry=ruleSets.getRegistry();this._ruleCount=ruleSets.getActiveRuleCount();this._rulesetSummary=ruleSets.getRulesetSummary();this._rulePacks=ruleSets.getRulePacks();this._common=this._createCommon();this._shadowRulePacks=ruleSets.getShadowRulePacks();this._ruleSets=ruleSets;this._Stats=appCtx.Stats;this._isUnitTest=appCtx.isUnitTest;this._debugMode=appCtx.debugMode;if(this._isUnitTest||config.rulesFired){this._Stats.packRulesFired=[];for(let i=0;i<ruleSets._ruleSets.length;i++)this._Stats.packRulesFired.push({pack:ruleSets._ruleSets[i].prefix,rules:{}})}this._builtinJetRules=null;this._useBuiltinJetRules=true;this._config=config;this._nd=nodeDeps;this._isNode=!!nodeDeps.fs;this._curFile=null;this._getMsgId=fnMsgId;this._sysOpts={verboseMode:appCtx.verboseMode,debugMode:appCtx.debugMode};this._message={msg:this._msg,info:this._info,debug:this._debug,error:this._error,warn:this._warn,assert:this._assert}};Rules.prototype.fireRules=function(ruleCtx,arg1,filepath,filetype,arg2,isEmbeddedCss){var ruleName,callbacks,typeObj;if(this._curFile!==filepath){this._curFile=filepath;this._fileType=filetype}if(typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type)){if(ruleCtx.type==="TsxWebComponent"||ruleCtx.type==="TsxElem"||ruleCtx.type.startsWith("Tsx<")||ruleCtx.type==="TsxJetComponent"){if(ruleCtx.type.includes("|")||ruleCtx.type.includes("=")){ruleCtx.type=arg1.type="TsxProperty"}else{ruleCtx.type=arg1.type="TsxComponent"}}for(ruleName in typeObj){if(this._isRuleDisabledByComment&&this._isRuleDisabledByComment(ruleName)){continue}callbacks=typeObj[ruleName];this._fireRulePreTest(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks)}}};Rules.prototype.getTsxRuleSynopsis=function(){return this._registry.getTsxRuleSynopsis()};Rules.prototype.setJafLib=function(jl){this._jafLib=jl};Rules.prototype._fireRulePreTest=function(ruleCtx,ruleName,arg1,filepath,arg2,isEmbeddedCss,callbacks){var opts,callback,fileType,i;if(!callbacks){return}for(i=0;i<callbacks.length;i++){callback=callbacks[i];opts=this._getRuleOptionsByName(ruleName,callback.rsi);if(!opts.enabled){return}fileType=opts[PROP_FILETYPE];if(fileType){if(isEmbeddedCss&&!this._isFileTypeOk(fileType,FILETYPE_CSS)){return}if(!this._isFileTypeOk(fileType,this._fileType)){return}}ruleCtx._rsi=callback.rsi;ruleCtx.getMsgId=this._getMsgId;this._fireRule(ruleCtx,ruleName,arg1,arg2,filepath,fileType,callback.cb)}};Rules.prototype._fireRule=function(ruleCtx,ruleName,name,value,filepath,filetype,callback){var rule,msg,ctxType,oFired;ctxType=ruleCtx.type;if(this._debugMode){this._debug(`Firing rule '${ruleName}' ...`)}rule=this._getRuleByName(ruleName,ruleCtx._rsi);if(!rule){if(this._debugMode){this._debug(`'${ruleName}' rsi=${ruleCtx._rsi} instance could not be loaded`)}return}ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;ruleCtx.filepath=filepath;ruleCtx.filetype=filetype;ruleCtx.utils=ruleCtx.utils?ruleCtx.utils:{};ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[ruleCtx._rsi].rulePack;ruleCtx.sysOpts=this._sysOpts;ruleCtx.common=this._common[ruleCtx._rsi];ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.sevLib=this._sevLib;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.jafLib=this._jafLib.getJafLib();ruleCtx.utils.OjetLib=this._ojetLib;ruleCtx.utils.pluginLib=this._plugin.getPluginLib();this._curCtx=ruleCtx;try{if(callback){ruleCtx.rulePack._setCBCtx(ruleCtx);if((ctxType==="attr"||ctxType==="attrexpr"||ctxType==="attrexpr-$props"||ctxType==="event"||ctxType.indexOf("|")>0||ctxType==="class"||ctxType==="style"||ctxType.startsWith("<")&&ctxType.includes("="))&&typeof value!=="string"){if(ctxType==="style"){if(this._debugMode){this._debugRuleCall(ctxType,name,_extractStyles(value.val),value.rawval)}callback(ruleCtx,name,_extractStyles(value.val),value.rawval)}else{if(this._debugMode){this._debugRuleCall(ctxType,name,value.val,value.rawVal)}callback(ruleCtx,name,value.val,value.rawval)}}else if(ctxType.startsWith("compjson")||ctxType==="comment"){if(this._debugMode){this._debugRuleCall(ctxType,value)}callback(ruleCtx,value)}else if(ruleCtx.type==="json"){if(this._debugMode){this._debugRuleCall(ctxType,value.ast)}callback(ruleCtx,value.ast)}else if(ctxType==="MemberExpression"||ctxType==="CallExpression"){if(this._debugMode){this._debugRuleCall(ctxType,name)}callback(ruleCtx,name)}else{if(this._debugMode){this._debugRuleCall(ctxType,name,value)}callback(ruleCtx,name,value)}this._Stats.rulesFired++;if(this._isUnitTest||this._config.rulesFired){if(oFired=this._Stats.packRulesFired[ruleCtx._rsi]){oFired=oFired.rules;if(oFired[ruleName]){oFired[ruleName]++}else{oFired[ruleName]=1}}}}else{rule.run(ruleCtx,name,value)}}catch(e){msg=!e||!e.message?"Unknown error (rule "+this._getFileSuffix(ruleCtx.filepath)+" syntax issue?)":e.message;this._error("** running rule "+ruleName+" ["+msg+"]"+"\n - "+ruleCtx.filepath);this._error(e.stack)}};Rules.prototype._debugRuleCall=function(ctxType){let s="";for(let i=1;i<arguments.length;i++){s+=`${i>1?",":""} arg${i}=${arguments[i]}`}this._debug(` -> ${ctxType} ${s}`)};Rules.prototype.makeRuleContext=function(){return new RuleContext};Rules.prototype.isTypeRegistered=function(regType){return this._registry.isRegisteredCallback(regType)};Rules.prototype.isAnyTsxCompAttrRegistered=function(){return this._registry.isRegisteredAnyTsxCompAttr()};Rules.prototype.isAnyTsxAttrRegistered=function(){return this._registry.isRegisteredAnyTsxAttr()};Rules.prototype.isAnyTsxTypeRegistered=function(){return this._registry.isAnyTsxTypeRegistered()};Rules.prototype.isTypeRegisteredAsElemName=function(elem){return this._registry.isRegisteredCallbackRE(elem)};Rules.prototype.setJSCommentCallback=function(fnCB){this._isRuleDisabledByComment=fnCB};Rules.prototype.filterHtmlCallbacks=function(htmlCB){return htmlCB};Rules.prototype.getRulesProse=function(isInternal){var rulePacks,rulePack,rules,rule,ruleName,names,rsi,opts,haveRules,prefix,msgIds,ids;this._nd.exportRules.setupRulesToProse(this._nd,this._config.severity,this._appCtx);msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson;prefix=rules.prefix;this._nd.exportRules.packToProse(rules,rulePack.path,rsi);haveRules=false;rules=rules.rules;names=_getSortedRuleNames(rules);for(ruleName of names){opts=rules[ruleName];if(!opts.enabled||opts.hasOwnProperty("inservice")&&!opts.inservice){continue}opts=this._utils.extend(opts,isInternal);rule=this._shadowRulePacks[rsi][ruleName];ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);this._nd.exportRules.ruleToProse(ruleName,rule,opts,ids);haveRules=true}if(!haveRules){this._nd.exportRules.packToProse()}}return this._nd.exportRules.getProse()};Rules.prototype.getRulesJson=function(active,obj){var rulePacks,rulePack,rulesJson,ruleName,rule,ruleOpts,opts,pack,rsi,prefix,msgIds,ids;msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;this._nd.exportRules.setupRulesToJson(obj,this._config.severity,this._appCtx);for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];this._nd.exportRules.packToJson(rulePack);rulesJson=rulePack.rulesJson;prefix=rulesJson.prefix;for(ruleName in rulesJson.rules){ruleOpts=rulesJson.rules[ruleName];if(ruleOpts.hasOwnProperty("inservice")&&!ruleOpts.inservice){continue}if(active&&!ruleOpts.enabled){continue}opts=this._utils.extend(ruleOpts);ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);if(pack=this._shadowRulePacks[rsi]){rule=pack[ruleName]}else{rule=null}if(!active||rule){this._nd.exportRules.ruleToJson(ruleName,rule,opts,ids,active)}}}return this._nd.exportRules.getJson()};Rules.prototype.getRulesSonar=function(){var rulePacks,rulePack,ruleName,rules,rule,opts,prefix,msgIds,ids,rsi;this._nd.exportRules.setupRulesToXml(this._appCtx);msgIds=this._ruleSets.getMsgIds();rulePacks=this._rulePacks;for(rsi=0;rsi<rulePacks.length;rsi++){rulePack=rulePacks[rsi];rules=rulePack.rulesJson.rules;prefix=rulePack.rulesJson.prefix;for(ruleName in rules){opts=rules[ruleName];if(!opts.enabled||opts.hasOwnProperty("inservice")&&!opts.inservice){continue}opts=this._utils.extend(opts);rule=this._shadowRulePacks[rsi][ruleName];ids=this._getMsgIdsForRule(ruleName,msgIds[prefix],prefix);this._nd.exportRules.ruleToXml(ruleName,rule,opts,ids)}}return this._nd.exportRules.getXml()};Rules.prototype.getRuleOptions=function(ruleName,rsi){return this._getRuleOptionsByName(ruleName,rsi)};Rules.prototype.getActiveRuleCount=function(){return this._ruleCount};Rules.prototype.getRuleSetSummaryByIndex=function(rsi){return this._rulesetSummary[rsi]};Rules.prototype.getRulePack=function(rsi){return this._rulePacks[rsi].rulePack};Rules.prototype.getRSIByPrefix=function(prefix){var i,rsi=-1;;for(i=0;i<this._rulesetSummary.length;i++){if(this._rulesetSummary[i].prefix===prefix){rsi=i;break}}return rsi};Rules.prototype.isRuleEnabled=function(ruleName,rsi){if(rsi===undefined){rsi=this.getRSIByRuleName(ruleName);if(rsi<0){return false}}var opts=this._getRuleOptionsByName(ruleName,rsi);return!!(opts&&opts.enabled)};Rules.prototype.getRSIByRuleName=function(ruleName){var rsi,rp,len;len=this._shadowRulePacks.length;for(rsi=0;rsi<len;rsi++){rp=this._shadowRulePacks[rsi];if(rp[ruleName]){break}}return rsi<len?rsi:-1};Rules.prototype.getRuleDescription=function(prefix,ruleName,isShort){var rule,rsi,ret="";rsi=this.getRSIByPrefix(prefix);if(rsi>=0){rule=this._shadowRulePacks[rsi][ruleName];if(rule){ret=isShort?rule.getShortDescription():rule.getDescription()}}return ret};Rules.prototype.getRuleDescriptionEx=function(msgId,ruleName,isShort){var descrip,rule,prefix,msgNum,rsi,msgTab,msgIds,mid,sev,x;var idList=[];if(ruleName){var rp=this._shadowRulePacks;for(rsi=0;rsi<rp.length;rsi++){rule=rp[rsi][ruleName];if(rule){descrip=isShort?rule.getShortDescription():rule.getDescription();if(descrip){msgTab=this._ruleSets.loadMsgIds();if(prefix=this._rulesetSummary[rsi]){prefix=prefix.prefix;if(msgIds=msgTab[prefix]){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}}}break}}}}if(msgId){rsi=this._ruleSets.getRsiFromMsgId(msgId);if(rsi>=0){x=msgId.indexOf("-");prefix=msgId.substring(0,x);msgNum=msgId.substring(x+1);msgTab=this._ruleSets.loadMsgIds();msgIds=msgTab[prefix];if(msgNum.length<4){msgNum="0".repeat(4-msgNum.length)+msgNum}for(mid in msgIds){if(msgIds[mid]===msgNum){x=mid.lastIndexOf("_");ruleName=x>0?mid.substring(0,x):mid;if(descrip=this.getRuleDescription(prefix,ruleName,isShort)){for(mid in msgIds){if(mid.startsWith(ruleName)){idList.push(msgIds[mid])}}break}}}}}if(ruleName){sev=this._getRuleOptionsByName(ruleName,rsi);sev=sev?sev.severity:""}return{descrip:descrip,rule:ruleName,prefix:prefix,sev:sev,idList:idList}};Rules.prototype._getMsgIdsForRule=function(rname,ids,prefix){var r,list=[];prefix=prefix?prefix+"-":"";for(r in ids){if(r.startsWith(rname)){list.push(prefix+ids[r])}}return list};Rules.prototype._showIgnoredRule=function(msg,isError){if(msg){if(!this._ignoredRulesShown){this._info("\n--------- Start-up Rule analysis ---------");this._ignoredRulesShown=true}isError?this._error(msg):this._info(msg)}else if(this._ignoredRulesShown){this._info("------------ End Rule analysis -------------")}};Rules.prototype.fireHookRules=function(ruleCtx,rsi){var ruleName,typeObj,callbacks,callback,opts,rc,i;var _rsi;ruleCtx.Issue=this._Issue;ruleCtx.reporter=this._reporter;_rsi=rsi;if(!(typeObj=this._registry.getRegisteredCallbacks(ruleCtx.type))){return}ruleCtx.userDefs=this._config.userDefs;ruleCtx.utils.metaLib=this._metaLib;ruleCtx.utils.utils=this._utils;ruleCtx.utils.fsUtils=this._fsUtils;ruleCtx.utils.msgLib=this._message;ruleCtx.utils.semVerUtils=this._semVer;ruleCtx.utils.OjetLib=this._ojetLib;ruleCtx.sysOpts=this._sysOpts;ruleCtx.getMsgId=this._getMsgId;for(ruleName in typeObj){callbacks=typeObj[ruleName];if(!callbacks){continue}for(i=0;i<callbacks.length;i++){callback=callbacks[i];if(rsi===undefined){_rsi=callback.rsi}else{if(rsi!==callback.rsi){continue}_rsi=rsi}opts=this._getRuleOptionsByName(ruleName,_rsi);if(ruleCtx.type==="file"||ruleCtx.type==="startscript"){if(opts&&opts.filetype){if(!this._isFileTypeOk(opts.filetype,ruleCtx.filetype)){continue}}}ruleCtx.ruleName=ruleName;ruleCtx.rulePack=this._rulePacks[_rsi].rulePack;ruleCtx._rsi=_rsi;ruleCtx.common=this._common[_rsi];if(this._debugMode){this._debug(`Firing hook rule '${ruleName}' type=${ruleCtx.type}`)}ruleCtx.rulePack._setCBCtx(ruleCtx);rc=callback.cb(ruleCtx);this._Stats.hooksFired++;if((ruleCtx.phase===REG.PHASE_STARTUP||ruleCtx.phase===REG.PHASE_START_AUDIT||ruleCtx.phase===REG.PHASE_FILE)&&typeof rc==="boolean"&&!rc){this._info("Hook rule ('"+ruleCtx.type+"') veto! by '"+ruleName+"'");return rc}}}return true};Rules.prototype._getRuleByName=function(ruleName,rsi){var rs=this._shadowRulePacks[rsi];return rs[ruleName]};Rules.prototype._getRuleOptionsByName=function(ruleName,rsi){var rulePack=this._rulePacks[rsi];return rulePack.rulesJson.rules[ruleName]};Rules.prototype._isGroupActive=function(group){var groups,defs,def,i;groups=this._config.groups;defs=this._config.defGroups;if(this._checkGroups(groups,group)){return true}if(!defs){return false}for(i=0;i<groups.length;i++){def=groups[i];if(this._checkDefGroup(defs,def,group)){return true}}return false};Rules.prototype._loadBuiltinJetRulesDescriptions=function(){var ruleName,rules;try{if(!this._builtinJetRules){this._builtinJetRules=require("../rules/jet/rules.json")}}catch(e){this._error("Unable to load builtin rule definition file "+e)}if(this._builtinJetRules&&this._builtinJetRules.rules){rules=this._builtinJetRules.rules;for(ruleName in rules){rules[ruleName].$builtin=true}}return this._builtinJetRules};Rules.prototype._isFileTypeOk=function(ruleFileType,fileType){var ret=false;if(Array.isArray(ruleFileType)){ret=ruleFileType.indexOf(fileType)>=0}else{ret=ruleFileType===fileType}return ret};Rules.prototype._createCommon=function(){var i,a=[];for(i=0;i<this._rulesetSummary.length;i++){a.push({})}return a};Rules.prototype._getFileSuffix=function(fp){var s="";if(fp){s=this._nd.path.extname(fp)}return s.length?s:"?"};Rules.prototype.dumpRegistry=function(){return this._registry.dump()};function _extractStyles(s){var a,isExpr,i,sc=";";s=s.trim();isExpr=_isExpr(s);s=s.replace(/[\'\"\[\]\{\}]/g,"").trim();if(!s.includes(";")){if(isExpr){if(s.includes(",")){sc=","}}}a=s.split(sc);for(i=0;i<a.length;i++){a[i]=a[i].trim();if(!a[i].length){a.splice(i,1);i--}}return a};function _isExpr(s){s=s.trim();return s.startsWith("[[")||s.startsWith("{{")};function _getSortedRuleNames(rules){var rule,names=[];for(rule in rules){names.push(rule)}names.sort();return names};module.exports=Rules;
|
package/lib/Scope.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
var walker=require('./scopewalker');const TS_ANY='TSAnyKeyword';const TS_TYPEREF='TSTypeReference';const TS_ARRAY='TSArrayType';const STRING='string';const NUMBER='number';const BOOLEAN='boolean';const NULL='null';const OBJECT='Object';const FUNCTION='function';const ANY='any';const REG_EXP='RegExp';const UNKNOWN='unknown';const PROGRAM='Program';const GLOBAL_SCOPE='_@global';const ANON='$anon';const DOCUMENT_METHODS={createElement:'Element',createTextNode:'Element',getElementById:'Element',getElementsByClassName:'HTMLCollection',getElementsByName:'HTMLCollection',getElementsByTagName:'HTMLCollection',getElementsByTagNameNS:'HTMLCollecion',hasFocus:'boolean',querySelector:'Element',querySelectorAll:'NodeList'};const DOCUMENT_MEMBERS={activeElement:'Element',anchors:'HTMLCollection',body:'Element',childElementCount:'number',dir:'string',documentElement:'Element',documentURI:'string',docType:'DTD',forms:'HTMLCollection',getElementById:'Element',head:'Element',hidden:'boolean',links:'HTMLCollection',scrollingElement:'Element',visibilityState:'string'};const INDENT=3;var _level=-INDENT;function _trace(t,n){function _rj(s,w){s=''+s;if(s.length<w){s=' '.repeat(w-s.length)+s}return s}_level+=t==='E'?INDENT:0;if(t==='E')console.log(`${_rj(n.loc.start.line,4)}] ${' '.repeat(_level)} ${n.type}`);else console.log(`${' '.repeat(4)} ${' '.repeat(_level)} ${n.type}`);_level-=t==='L'?INDENT:0};class Scope{constructor(msgCtx,config,file){this._msgCtx=msgCtx;this._config=config;this._file=file;this.reset()}reset(){this._fStack=[];this._bStack=[];this._imports=[];this._funcStack=[];this._idxStack=0;this._parents=[];this._blockStack=[];this._idxBlkStack=0;this._blkParents=[];this._nextAnonId=0;this._varKind;this._level=-INDENT}build(ast){this.reset();try{walker.traverse(ast,{enter:this._enter.bind(this),leave:this._leave.bind(this)})}catch(e){let stk=e.stack;let x=stk.indexOf('\n');stk=x>=0?stk.substring(x+1):stk;stk=`${'-'.repeat(10)}\n${stk}\n${'-'.repeat(10)}`;this._msgCtx.jafMsg('jaf-ts-walk',`TS walk exception: ${e.message} File: ${this._file}\n\n${stk}`)}return{funcs:this._fStack,blocks:this._bStack}}_buildFuncIndexesToBlocks(){var i,j;for(i=0;i<this._fStack.length;i++){for(j=0;j<this._bStack.length;j++){if(this._bStack[j].func==i){this._fStack[i].blocks.push(j)}}}}getAccessor(){return new _scope(this._fStack,this._bStack)}_enter(node){var type;if(this._msgCtx.isDebug){_trace('E',node)}type=node.type;if(this._isNewScope(node)){this._addNewFunc(node)}else if(type==='VariableDeclarator'||type==='ClassProperty'){this._varDecl(node)}else if(type==='VariableDeclaration'){this._varKind=node.kind}else if(type==='BlockStatement'){this._addNewBlock(node)}else if(type==='ClassDeclaration'){this._inClass=true;this._className=node.id.name}else if(type==='ImportDeclaration'){this._addImport(node)}}_leave(node){if(this._msgCtx.isDebug){_trace('L',node)}if(this._isNewScope(node)){if(this._parents.length){this._parents.pop()}this._funcStack.pop()}else if(node.type==='BlockStatement'){if(this._blkParents.length){this._blkParents.pop()}this._blockStack.pop()}else if(node.type==='ClassDeclaration'){this._inClass=false;this._className=null}}_addNewFunc(node){var type,func,curParent,x;type=node.type;if(type===PROGRAM){func=GLOBAL_SCOPE}else if(node.kind==='method'||node.kind==='get'||node.kind==='set'||node.kind==='constructor'){func=node.key.name}else if(node.id){func=node.id.name}else if(type==='ClassBody'){func=this._className}else{this._getNextAnon()}if(this._parents.length){curParent=this._fStack[this._parents[this._parents.length-1]]}x=this._fStack.push({func:func,accessor:node.kind==='get'?'get':node.kind==='set'?'set':null,node:node,vars:{},args:{},blocks:[],children:[],parent:this._parents.length?this._parents[this._parents.length-1]:-1});x--;this._parents.push(x);if(curParent){curParent.children.push(x)}this._funcStack.push(x);this._addFuncArgs(node)}_addNewBlock(node){var func,curParent,x;var func=this._fStack[this._getCurFunc()];let n=this._fStack[this._getCurFunc()].node;if((n.kind==='method'||n.kind==='constructor')&&this._isMethodRange(n,node)||n.kind!=='method'&&n.kind!=='constructor'&&n.body&&node.range===n.body.range){return}if(this._blkParents.length){curParent=this._bStack[this._blkParents[this._blkParents.length-1]]}x=this._bStack.push({func:this._getCurFunc(),node:node,lets:{},children:[],parent:this._blkParents.length?this._blkParents[this._blkParents.length-1]:-1});x--;this._blkParents.push(x);if(curParent){curParent.children.push(x)}this._blockStack.push(x);func.blocks.push(x)}_addImport(node){var src,local,o;src=node.source.value;if(!src.startsWith('ojs/')){return}o={src:src};if(node.specifiers.length){node.specifiers.forEach(s=>{if(!local)local=[];local.push(s.local.name)});if(local){o.local=local}}this._imports.push(o)}_getCurFunc(){return this._funcStack[this._funcStack.length-1]}_getCurBlock(){return this._blockStack[this._blockStack.length-1]}_addFuncArgs(node){var vt,curScope;if(node.params){curScope=this._fStack[this._getCurFunc()];node.params.forEach(function(n){if(n.type==='Identifier'){vt=this._getVarType(n);curScope.args[n.name]={type:vt}}else{if(n.type==='AssignmentPattern'){if(n.left&&n.left.name){curScope.args[n.left.name]={type:'???'}}else{console.log('scopes nt = n.type')}}}},this)}}_isNewScope(node){var type=node.type;return type==='FunctionDeclaration'||type==='MethodDefinition'||type==='FunctionExpression'&&!this._inClass||type==='ClassBody'||type==='Program'}_varDecl(node){var curScope,vt,name;function _declVar(vt,self){curScope=self._fStack[self._getCurFunc()];if(node.id){name=node.id.name}else{name=node.key.name}curScope.vars[name]={type:vt,node:node}};vt=this._getVarType(node);if(this._varKind==='let'||this._varKind==='const'){if(this._blockStack.length===0){this._varKind='var'}}if(this._varKind==='var'||node.type==='ClassProperty'){_declVar(vt,this)}else if(this._varKind==='let'||this._varKind==='const'){let b=this._getCurBlock();if(b>=0){let block=this._bStack[b];let br=block.node.range;let start=node.range;if(start[0]>=br[0]&&start[1]<=br[1]){block.lets[node.id.name]={type:vt,node:node}}}else{_declVar(vt,this)}}}_getVarType(node){var vt,ta,et,ty;if(node.type==='ClassProperty'){if(node.value){if(node.value.type==='ArrowFunctionExpression'){return'function'}else if(node.value.type==='CallExpression'){if(node.value.callee.object.name==='ko'){if(node.value.callee.property.name==='observable'){return'KO_Observable'}else if(node.value.callee.property.name==='computed'){return'KO_computed'}else{return'KO_Unknown'}}}}}ta=node.id&&node.id.typeAnnotation?node.id.typeAnnotation:node.typeAnnotation;if(!ta){ty=node.init?this._getInitType(node.init):ANY}else{vt=ta.typeAnnotation.type;if(vt===TS_TYPEREF){if(ta.typeAnnotation.typeName.name){ty=ta.typeAnnotation.typeName.name}else{if(ta.typeAnnotation.typeName.left){if(ta.typeAnnotation.typeName.left.name){ty=ta.typeAnnotation.typeName.left.name;if(ta.typeAnnotation.typeName.right&&ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}else if(ta.typeAnnotation.typeName.left.left.name){ty+='.'+ta.typeAnnotation.typeName.left.left.name;if(ta.typeAnnotation.typeName.left.right.name){ty+='.'+ta.typeAnnotation.typeName.left.right.name}if(ta.typeAnnotation.typeName.right.name){ty+='.'+ta.typeAnnotation.typeName.right.name}}}}}else if(vt===TS_ARRAY){et=ta.typeAnnotation.elementType.type;if(et===TS_TYPEREF){ty=ta.typeAnnotation.elementType.typeName.name+'[]'}else{ty=et+'[]'}}else{ty=vt}}if(ty){ty=_transformType(ty)}if(!ty){console.log('[ASSERT]: scopes: ty not defined')}return ty}_getInitType(init){var vt,raw;if(init.type==='Literal'&&init.raw){raw=init.raw;if(raw.charAt(0)==='"'||raw.charAt(0)==='\''){vt=STRING}else if(raw==='true'||raw==='false'){vt=BOOLEAN}else if(!isNaN(raw)){vt=NUMBER}else if(raw==='null'){vt=NULL}else if(raw.startsWith('/')&&raw.endsWith('/')){vt=REG_EXP}else{console.log('[ASSERT]: SCOPES - UNKNOWN VAR INIT LITERAL TYPE = '+raw);vt=UNKNOWN}}else if(init.type==='ObjectExpression'){vt=OBJECT}else if(init.type==='NewExpression'){if(init.callee&&init.callee.name){vt=init.callee.name}}else if(init.type==='CallExpression'){if(init.callee&&init.callee.object){let o=init.callee.object;if(o.type==='Identifier'&&o.name==='document'){o=init.callee.property;if(o=DOCUMENT_METHODS[o.name]){return o}else{return'unknown document function'}}if(o.type==='MemberExpression'){vt=this._unravelCallME(o)}if(init.callee&&init.callee.object&&init.callee.object.type==='FunctionExpression'){vt='function'}}}else if(init.type==='MemberExpression'){if(init.object.type==='TSAsExpression'){vt=UNKNOWN}}else if(init.type==='TSAsExpression'){if(init.typeAnnotation&&init.typeAnnotation.type==='TSTypeReference'){vt=init.typeAnnotation.typeName.name}else{vt=UNKNOWN}}else if(init.type==='TSTypeAssertion'){if(init.typeAnnotation){vt=init.typeAnnotation.type}}else if(init.type==='AwaitExpression'){vt=ANY}else{vt=init.type}if(!vt){vt=UNKNOWN}return vt}_isMethodRange(n,node){return n.value&&n.value.body&&n.value.body.range===node.range}_unravelCallME(o){var prop;if(o.object.type==='ThisExpression'){prop=o.property.name;return this._getClassPropType(o,prop)}}_getClassPropType(o,prop){var c,ret;c=this._getContainingClass(o);if(c&&c.vars){ret=c.vars[prop];if(ret){ret=ret.type}}return ret}_getContainingClass(node){var c=this._getCurFunc(node);if(c<0){return}do{c=this._fStack[c];if(c.node.type==='ClassBody'){break}c=c.parent}while(c>=0);return c}_dumpEnter(node){let funcName=node.id?node.id.name:'anon';console.log(`ENTER=${funcName} ${node.type}`)}_dumpLeave(node){let funcName=node.id?node.id.name:'anon';console.log(`LEAVE=${funcName} ${node.type}`)}dumpStacks(){this.dumpFuncStack();this.dumpBlockStack()}dumpFuncStack(){var st,v,o,s,i,title;console.log('\n-------- Function/Class Scope Map --------');st=this._fStack;for(i=0;i<st.length;i++){o=st[i];s=(o.children.length?'children='+_dumpArrayIndices(o.children):'')+' blocks='+_dumpArrayIndices(o.blocks);console.log(`\n[${i}] "${o.func}" ${_dumpStackType(o)} parent=${o.parent} ${s}`);title=false;if(_hasProps(o.args)){for(v in o.args){console.log((!title?' Args: ':' ')+v+': '+o.args[v].type);title=true}}else{console.log(' Args: none')}title=false;if(_hasProps(o.vars)){for(v in o.vars){console.log((!title?' Vars: ':' ')+v+': '+o.vars[v].type+' ('+(o.vars[v].node.type==='ClassProperty'?'class prop':'var')+')');title=true}}else{console.log(' Vars: none')}}}dumpBlockStack(){var st,v,o,ch,i,title;console.log('\n-------- Internal Block Scope Map --------');st=this._bStack;if(!st.length){console.log('\nNo blocks.');return''}for(i=0;i<st.length;i++){o=st[i];ch=o.children.length?'children='+_dumpArrayIndices(o.children):'';console.log(`\n[${i}] ${this._dumpBlkOwner(o)}="${this._fStack[o.func].func}" parent=${o.parent} ${ch}`);title=false;if(_hasProps(o.lets)){for(v in o.lets){console.log((!title?' Lets: ':' ')+v+': '+o.lets[v].type);title=true}}else{console.log(' Lets: none')}}}_dumpBlkOwner(o){var f=this._fStack[o.func];return f.node.type==='FunctionDeclaration'?'func':'meth'}_getNextAnon(){return ANON+ ++this._nextAnonId}};function _hasProps(obj){var ret=false;for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}return ret};function _dumpArrayIndices(a){var ret='[';a.forEach(function(v,i){ret+=(i?', ':'')+v});return ret+']'}function _dumpStackType(o){var s='';switch(o.node.type){case'ClassBody':s='class';break;case'MethodDefinition':s='method';if(o.accessor){if(o.accessor==='get'){s+=' getter'}else if(o.accessor==='set'){s+=' setter'}else{s+=' ?accessor'}}break;case'FunctionDeclaration':s='func';break;}return s.length?'('+s+')':s};function _transformType(ty){const list={TSStringKeyword:'string',TSNumberKeyword:'number',TSBooleanKeyword:'boolean',TSNullKeyword:'null',TSObjectKeyword:'object',TSUnknownKeyword:'unknown',TSAnyKeyword:'any'};return list[ty]||ty};class _scope{constructor(fs,bs){this._fstk=fs;this._bstk=bs}getVarType(node){var name,func,block,v;if(!(name=node.name)){return null};block=this.getContainingBlock(node);if(block){v=block.lets[name];if(v){return v.type}while(block.parent>=0){block=this._bstk[block.parent];if(block){v=block.lets[name];if(v){return v.type}}}}func=this.getContainingFunc(node);do{if(func.vars&&func.vars[name]){v=func.vars[name].type}else if(func.args&&func.args[name]){v=func.args[name].type}if(v){break}if(func.parent>=0){func=this._fstk[func.parent]}else{func=null}}while(func);return v}getContainingFunc(node){var start,fnRange,fnIndex,func,fr,i;start=node.range[0];for(i=0;i<this._fstk.length;i++){func=this._fstk[i];fr=func.node.range;if(start>=fr[0]&&start<=fr[1]){if(fnRange){if(fr[0]>=fnRange[0]&&fr[1]<=fnRange[1]){fnRange=fr;fnIndex=i}}else{fnRange=fr;fnIndex=i}}}return typeof fnIndex==='number'?this._fstk[fnIndex]:null}getContainingBlock(node){var nrange,brange,range,bindex,blocks,block,i;if(!this._bstk.length)return;var blocks=this.getContainingFunc(node).blocks;nrange=node.range;for(i=0;i<blocks.length;i++){block=this._bstk[i];brange=block.node.range;if(nrange[0]>=brange[0]&&nrange[1]<=brange[1]){if(range){if(brange[0]>=range[0]&&brange[1]<=range[1]){range=nrange;bindex=i}}else{range=brange;bindex=i}}}return typeof bindex==='number'?this._bstk[bindex]:null}getContainingClass(node){}getGlobals(){return this._fstk[0]}getFuncStack(){return this._fstk}getBlockStack(){return this._bstk}};module.exports=Scope;
|
|
6
|
+
var walker=require("./scopewalker");const TS_ANY="TSAnyKeyword";const TS_TYPEREF="TSTypeReference";const TS_ARRAY="TSArrayType";const STRING="string";const NUMBER="number";const BOOLEAN="boolean";const NULL="null";const OBJECT="Object";const FUNCTION="function";const ANY="any";const REG_EXP="RegExp";const UNKNOWN="unknown";const PROGRAM="Program";const GLOBAL_SCOPE="_@global";const ANON="$anon";const DOCUMENT_METHODS={createElement:"Element",createTextNode:"Element",getElementById:"Element",getElementsByClassName:"HTMLCollection",getElementsByName:"HTMLCollection",getElementsByTagName:"HTMLCollection",getElementsByTagNameNS:"HTMLCollecion",hasFocus:"boolean",querySelector:"Element",querySelectorAll:"NodeList"};const DOCUMENT_MEMBERS={activeElement:"Element",anchors:"HTMLCollection",body:"Element",childElementCount:"number",dir:"string",documentElement:"Element",documentURI:"string",docType:"DTD",forms:"HTMLCollection",getElementById:"Element",head:"Element",hidden:"boolean",links:"HTMLCollection",scrollingElement:"Element",visibilityState:"string"};const INDENT=3;var _level=-INDENT;function _trace(t,n){function _rj(s,w){s=""+s;if(s.length<w){s=" ".repeat(w-s.length)+s}return s}_level+=t==="E"?INDENT:0;if(t==="E")console.log(`${_rj(n.loc.start.line,4)}] ${" ".repeat(_level)} ${n.type}`);else console.log(`${" ".repeat(4)} ${" ".repeat(_level)} ${n.type}`);_level-=t==="L"?INDENT:0};class Scope{constructor(msgCtx,config,file){this._msgCtx=msgCtx;this._config=config;this._file=file;this.reset()}reset(){this._fStack=[];this._bStack=[];this._imports=[];this._funcStack=[];this._idxStack=0;this._parents=[];this._blockStack=[];this._idxBlkStack=0;this._blkParents=[];this._nextAnonId=0;this._varKind;this._level=-INDENT}build(ast){this.reset();try{walker.traverse(ast,{enter:this._enter.bind(this),leave:this._leave.bind(this)})}catch(e){let stk=e.stack;let x=stk.indexOf("\n");stk=x>=0?stk.substring(x+1):stk;stk=`${"-".repeat(10)}\n${stk}\n${"-".repeat(10)}`;this._msgCtx.jafMsg("jaf-ts-walk",`TS walk exception: ${e.message} File: ${this._file}\n\n${stk}`)}return{funcs:this._fStack,blocks:this._bStack}}_buildFuncIndexesToBlocks(){var i,j;for(i=0;i<this._fStack.length;i++){for(j=0;j<this._bStack.length;j++){if(this._bStack[j].func==i){this._fStack[i].blocks.push(j)}}}}getAccessor(){return new _scope(this._fStack,this._bStack)}_enter(node){var type;if(this._msgCtx.isDebug){_trace("E",node)}type=node.type;if(this._isNewScope(node)){this._addNewFunc(node)}else if(type==="VariableDeclarator"||type==="ClassProperty"){this._varDecl(node)}else if(type==="VariableDeclaration"){this._varKind=node.kind}else if(type==="BlockStatement"){this._addNewBlock(node)}else if(type==="ClassDeclaration"){this._inClass=true;this._className=node.id.name}else if(type==="ImportDeclaration"){this._addImport(node)}}_leave(node){if(this._msgCtx.isDebug){_trace("L",node)}if(this._isNewScope(node)){if(this._parents.length){this._parents.pop()}this._funcStack.pop()}else if(node.type==="BlockStatement"){if(this._blkParents.length){this._blkParents.pop()}this._blockStack.pop()}else if(node.type==="ClassDeclaration"){this._inClass=false;this._className=null}}_addNewFunc(node){var type,func,curParent,x;type=node.type;if(type===PROGRAM){func=GLOBAL_SCOPE}else if(node.kind==="method"||node.kind==="get"||node.kind==="set"||node.kind==="constructor"){func=node.key.name}else if(node.id){func=node.id.name}else if(type==="ClassBody"){func=this._className}else{this._getNextAnon()}if(this._parents.length){curParent=this._fStack[this._parents[this._parents.length-1]]}x=this._fStack.push({func:func,accessor:node.kind==="get"?"get":node.kind==="set"?"set":null,node:node,vars:{},args:{},blocks:[],children:[],parent:this._parents.length?this._parents[this._parents.length-1]:-1});x--;this._parents.push(x);if(curParent){curParent.children.push(x)}this._funcStack.push(x);this._addFuncArgs(node)}_addNewBlock(node){var func,curParent,x;var func=this._fStack[this._getCurFunc()];let n=this._fStack[this._getCurFunc()].node;if((n.kind==="method"||n.kind==="constructor")&&this._isMethodRange(n,node)||n.kind!=="method"&&n.kind!=="constructor"&&n.body&&node.range===n.body.range){return}if(this._blkParents.length){curParent=this._bStack[this._blkParents[this._blkParents.length-1]]}x=this._bStack.push({func:this._getCurFunc(),node:node,lets:{},children:[],parent:this._blkParents.length?this._blkParents[this._blkParents.length-1]:-1});x--;this._blkParents.push(x);if(curParent){curParent.children.push(x)}this._blockStack.push(x);func.blocks.push(x)}_addImport(node){var src,local,o;src=node.source.value;if(!src.startsWith("ojs/")){return}o={src:src};if(node.specifiers.length){node.specifiers.forEach(s=>{if(!local)local=[];local.push(s.local.name)});if(local){o.local=local}}this._imports.push(o)}_getCurFunc(){return this._funcStack[this._funcStack.length-1]}_getCurBlock(){return this._blockStack[this._blockStack.length-1]}_addFuncArgs(node){var props,left,n,vt,varKeys,curScope;if(node.params){curScope=this._fStack[this._getCurFunc()];node.params.forEach(function(n){if(n.type==="Identifier"){vt=this._getVarType(n);curScope.args[n.name]={type:vt}}else if(n.type==="AssignmentPattern"){if(n?.left?.type==="ObjectPattern"){left=n.left;vt=this._getTypeAnnotationType(n.left);if(varKeys=this._deconstructObject(n.left.properties)){varKeys.forEach(key=>{curScope.args[key]=vt?vt:"?"})}}else if(n?.left.type==="Identifier"){vt=this._getTypeAnnotationType(n.left);curScope.args[n.left.name]=vt?vt:"?"}else{this._msgCtx.assert(`scopes nt n.type= ${n.type} n.left.type=${n.left.type} n.right.type=${n.right.type}\n${this._file}`)}}else if(n.type==="ObjectPattern"){vt=this._getTypeAnnotationType(n);if(varKeys=this._deconstructObject(n.properties)){varKeys.forEach(key=>{curScope.args[key]=vt?vt:"?"})}}else if(n.type==="RestElement"){}else{this._msgCtx.assert(`scopes nt n.type= ${n.type} ${this._file}`)}},this)}}_deconstructObject(props){var ret;if(props){ret=[];props.forEach(prop=>{if(prop?.key?.type==="Identifier"){ret.push(prop.key.name)}});return ret}}_getTypeAnnotationType(node){var vt;if(node.typeAnnotation){if(node.typeAnnotation.type==="TSTypeReference"){vt=propAnnotation.typeName.name}else if(node.typeAnnotation?.typeAnnotation.type==="TSTypeReference"){vt=node.typeAnnotation.typeAnnotation.typeName.name}}return vt}_isNewScope(node){var type=node.type;return type==="FunctionDeclaration"||type==="MethodDefinition"||type==="FunctionExpression"&&!this._inClass||type==="ClassBody"||type==="Program"}_varDecl(node){var curScope,vt,name;function _declVar(vt,self){curScope=self._fStack[self._getCurFunc()];if(node.id){name=node.id.name}else{name=node.key.name}curScope.vars[name]={type:vt,node:node}};vt=this._getVarType(node);if(this._varKind==="let"||this._varKind==="const"){if(this._blockStack.length===0){this._varKind="var"}}if(this._varKind==="var"||node.type==="ClassProperty"){_declVar(vt,this)}else if(this._varKind==="let"||this._varKind==="const"){let b=this._getCurBlock();if(b>=0){let block=this._bStack[b];let br=block.node.range;let start=node.range;if(start[0]>=br[0]&&start[1]<=br[1]){block.lets[node.id.name]={type:vt,node:node}}}else{_declVar(vt,this)}}}_getVarType(node){var vt,ta,et,ty;if(node.type==="ClassProperty"){if(node.value){if(node.value.type==="ArrowFunctionExpression"){return"function"}else if(node.value.type==="CallExpression"){if(node.value.callee.object.name==="ko"){if(node.value.callee.property.name==="observable"){return"KO_Observable"}else if(node.value.callee.property.name==="computed"){return"KO_computed"}else{return"KO_Unknown"}}}}}ta=node.id&&node.id.typeAnnotation?node.id.typeAnnotation:node.typeAnnotation;if(!ta){ty=node.init?this._getInitType(node.init):ANY}else{vt=ta.typeAnnotation.type;if(vt===TS_TYPEREF){if(ta.typeAnnotation.typeName.name){ty=ta.typeAnnotation.typeName.name}else{if(ta.typeAnnotation.typeName.left){if(ta.typeAnnotation.typeName.left.name){ty=ta.typeAnnotation.typeName.left.name;if(ta.typeAnnotation.typeName.right&&ta.typeAnnotation.typeName.right.name){ty+="."+ta.typeAnnotation.typeName.right.name}}else if(ta.typeAnnotation.typeName.left.left.name){ty+="."+ta.typeAnnotation.typeName.left.left.name;if(ta.typeAnnotation.typeName.left.right.name){ty+="."+ta.typeAnnotation.typeName.left.right.name}if(ta.typeAnnotation.typeName.right.name){ty+="."+ta.typeAnnotation.typeName.right.name}}}}}else if(vt===TS_ARRAY){et=ta.typeAnnotation.elementType.type;if(et===TS_TYPEREF){ty=ta.typeAnnotation.elementType.typeName.name+"[]"}else{ty=et+"[]"}}else{ty=vt}}if(ty){ty=_transformType(ty)}if(!ty){console.log("[ASSERT]: scopes: ty not defined")}return ty}_getInitType(init){var vt,raw;if(init.type==="Literal"&&init.raw){raw=init.raw;if(raw.charAt(0)==="\""||raw.charAt(0)==="'"){vt=STRING}else if(raw==="true"||raw==="false"){vt=BOOLEAN}else if(!isNaN(raw)){vt=NUMBER}else if(raw==="null"){vt=NULL}else if(_isRegExpr(raw)){vt=REG_EXP}else{console.log("[ASSERT]: SCOPES - UNKNOWN VAR INIT LITERAL TYPE = "+raw);vt=UNKNOWN}}else if(init.type==="ObjectExpression"){vt=OBJECT}else if(init.type==="NewExpression"){if(init.callee&&init.callee.name){vt=init.callee.name}}else if(init.type==="CallExpression"){if(init.callee&&init.callee.object){let o=init.callee.object;if(o.type==="Identifier"&&o.name==="document"){o=init.callee.property;if(o=DOCUMENT_METHODS[o.name]){return o}else{return"unknown document function"}}if(o.type==="MemberExpression"){vt=this._unravelCallME(o)}if(init.callee&&init.callee.object&&init.callee.object.type==="FunctionExpression"){vt="function"}}}else if(init.type==="MemberExpression"){if(init.object.type==="TSAsExpression"){vt=UNKNOWN}}else if(init.type==="TSAsExpression"){if(init.typeAnnotation&&init.typeAnnotation.type==="TSTypeReference"){vt=init.typeAnnotation.typeName.name}else{vt=UNKNOWN}}else if(init.type==="TSTypeAssertion"){if(init.typeAnnotation){vt=init.typeAnnotation.type}}else if(init.type==="AwaitExpression"){vt=ANY}else{vt=init.type}if(!vt){vt=UNKNOWN}return vt}_isMethodRange(n,node){return n.value&&n.value.body&&n.value.body.range===node.range}_unravelCallME(o){var prop;if(o.object.type==="ThisExpression"){prop=o.property.name;return this._getClassPropType(o,prop)}}_getClassPropType(o,prop){var c,ret;c=this._getContainingClass(o);if(c&&c.vars){ret=c.vars[prop];if(ret){ret=ret.type}}return ret}_getContainingClass(node){var c=this._getCurFunc(node);if(c<0){return}do{c=this._fStack[c];if(c.node.type==="ClassBody"){break}c=c.parent}while(c>=0);return c}_dumpEnter(node){let funcName=node.id?node.id.name:"anon";console.log(`ENTER=${funcName} ${node.type}`)}_dumpLeave(node){let funcName=node.id?node.id.name:"anon";console.log(`LEAVE=${funcName} ${node.type}`)}dumpStacks(){this.dumpFuncStack();this.dumpBlockStack()}dumpFuncStack(){var st,v,o,s,i,title;console.log("\n-------- Function/Class Scope Map --------");st=this._fStack;for(i=0;i<st.length;i++){o=st[i];s=(o.children.length?"children="+_dumpArrayIndices(o.children):"")+" blocks="+_dumpArrayIndices(o.blocks);console.log(`\n[${i}] "${o.func}" ${_dumpStackType(o)} parent=${o.parent} ${s}`);title=false;if(_hasProps(o.args)){for(v in o.args){console.log((!title?" Args: ":" ")+v+": "+o.args[v].type);title=true}}else{console.log(" Args: none")}title=false;if(_hasProps(o.vars)){for(v in o.vars){console.log((!title?" Vars: ":" ")+v+": "+o.vars[v].type+" ("+(o.vars[v].node.type==="ClassProperty"?"class prop":"var")+")");title=true}}else{console.log(" Vars: none")}}}dumpBlockStack(){var st,v,o,ch,i,title;console.log("\n-------- Internal Block Scope Map --------");st=this._bStack;if(!st.length){console.log("\nNo blocks.");return""}for(i=0;i<st.length;i++){o=st[i];ch=o.children.length?"children="+_dumpArrayIndices(o.children):"";console.log(`\n[${i}] ${this._dumpBlkOwner(o)}="${this._fStack[o.func].func}" parent=${o.parent} ${ch}`);title=false;if(_hasProps(o.lets)){for(v in o.lets){console.log((!title?" Lets: ":" ")+v+": "+o.lets[v].type);title=true}}else{console.log(" Lets: none")}}}_dumpBlkOwner(o){var f=this._fStack[o.func];return f.node.type==="FunctionDeclaration"?"func":"meth"}_getNextAnon(){return ANON+ ++this._nextAnonId}};function _hasProps(obj){var ret=false;for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}return ret};function _dumpArrayIndices(a){var ret="[";a.forEach(function(v,i){ret+=(i?", ":"")+v});return ret+"]"}function _dumpStackType(o){var s="";switch(o.node.type){case"ClassBody":s="class";break;case"MethodDefinition":s="method";if(o.accessor){if(o.accessor==="get"){s+=" getter"}else if(o.accessor==="set"){s+=" setter"}else{s+=" ?accessor"}}break;case"FunctionDeclaration":s="func";break}return s.length?"("+s+")":s};function _transformType(ty){const list={TSStringKeyword:"string",TSNumberKeyword:"number",TSBooleanKeyword:"boolean",TSNullKeyword:"null",TSObjectKeyword:"object",TSUnknownKeyword:"unknown",TSAnyKeyword:"any"};return list[ty]||ty};function _isRegExpr(raw){return raw.startsWith("/")&&(raw.endsWith("/")||raw.endsWith("/g")||raw.endsWith("/i")||raw.endsWith("/gi")||raw.endsWith("/ig"))};class _scope{constructor(fs,bs){this._fstk=fs;this._bstk=bs}getVarType(node){var name,func,block,v;if(!(name=node.name)){return null};block=this.getContainingBlock(node);if(block){v=block.lets[name];if(v){return v.type}while(block.parent>=0){block=this._bstk[block.parent];if(block){v=block.lets[name];if(v){return v.type}}}}func=this.getContainingFunc(node);do{if(func.vars&&func.vars[name]){v=func.vars[name].type}else if(func.args&&func.args[name]){v=func.args[name].type}if(v){break}if(func.parent>=0){func=this._fstk[func.parent]}else{func=null}}while(func);return v}getContainingFunc(node){var start,fnRange,fnIndex,func,fr,i;start=node.range[0];for(i=0;i<this._fstk.length;i++){func=this._fstk[i];fr=func.node.range;if(start>=fr[0]&&start<=fr[1]){if(fnRange){if(fr[0]>=fnRange[0]&&fr[1]<=fnRange[1]){fnRange=fr;fnIndex=i}}else{fnRange=fr;fnIndex=i}}}return typeof fnIndex==="number"?this._fstk[fnIndex]:null}getContainingBlock(node){var nrange,brange,range,bindex,blocks,block,i;if(!this._bstk.length)return;var blocks=this.getContainingFunc(node).blocks;nrange=node.range;for(i=0;i<blocks.length;i++){block=this._bstk[i];brange=block.node.range;if(nrange[0]>=brange[0]&&nrange[1]<=brange[1]){if(range){if(brange[0]>=range[0]&&brange[1]<=range[1]){range=nrange;bindex=i}}else{range=brange;bindex=i}}}return typeof bindex==="number"?this._bstk[bindex]:null}getContainingClass(node){}getGlobals(){return this._fstk[0]}getFuncStack(){return this._fstk}getBlockStack(){return this._bstk}};module.exports=Scope;
|
package/lib/Ts.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 AST=require("../lib/AST_Ts");const Comments=require("../lib/Comments");const JSX=require("../lib/jsx");const VAR_DECL="VariableDeclarator";const CALL_EXPR="CallExpression";const RETURN_STMT="ReturnStatement";const ASSIGN_EXPR="AssignmentExpression";function Ts(parser,nd,rules,fileIndex,appCtx,msgCtx){this._parser=parser;this._rules=rules;this._Issue=appCtx.Issue;this._reporter=appCtx.reporter;this._fileIndex=fileIndex;this._utils=appCtx.utils;this._msgCtx=msgCtx;this._nd=nd;this._Ast=null;this._jsx=new JSX(appCtx.metaLib);this._tsxUtils=appCtx.tsxUtils;this._debugMode=msgCtx.debugMode;this._debug=msgCtx.debug;this._error=msgCtx.error;this._info=msgCtx.info;this._verboseMode=msgCtx.isVerbose;this._config=appCtx.config;this._ecmaVer=appCtx.config.getEcmaVer();this._isComments=appCtx.config.getComments();this._reportJafIssue=appCtx.reportJafIssue;this._flushIssues=appCtx.flushIssues};Ts.prototype.parse=function(data,file,fileType){var self=this;this._parseIt(data,file,fileType,function(treenode){let rc=self._parser.fireHookFileRules(treenode,null,false)});this._parser.fireHookFileRules(null,null)};Ts.prototype.getAst=function(){return this._Ast.getAst()};Ts.prototype.getAstUtils=function(){return this._Ast?this._Ast.getUtils():null};Ts.prototype._parseIt=function(data,file,fileType,cb){var ret=false,rowNow,colNow,issue,opts,arRawComs,startPos;try{this._debug(`Parsing ${fileType
|
|
6
|
+
const AST=require("../lib/AST_Ts");const Comments=require("../lib/Comments");const JSX=require("../lib/jsx");const VAR_DECL="VariableDeclarator";const CALL_EXPR="CallExpression";const RETURN_STMT="ReturnStatement";const ASSIGN_EXPR="AssignmentExpression";function Ts(parser,nd,rules,fileIndex,appCtx,msgCtx){this._parser=parser;this._rules=rules;this._Issue=appCtx.Issue;this._reporter=appCtx.reporter;this._fileIndex=fileIndex;this._utils=appCtx.utils;this._msgCtx=msgCtx;this._nd=nd;this._Ast=null;this._jsx=new JSX(appCtx.metaLib,msgCtx);this._tsxUtils=appCtx.tsxUtils;this._debugMode=msgCtx.debugMode;this._debug=msgCtx.debug;this._error=msgCtx.error;this._info=msgCtx.info;this._verboseMode=msgCtx.isVerbose;this._config=appCtx.config;this._ecmaVer=appCtx.config.getEcmaVer();this._isComments=appCtx.config.getComments();this._reportJafIssue=appCtx.reportJafIssue;this._flushIssues=appCtx.flushIssues;this._runMode=appCtx.runMode};Ts.prototype.parse=function(data,file,fileType){var self=this;this._parseIt(data,file,fileType,function(treenode){let rc=self._parser.fireHookFileRules(treenode,null,false)});this._parser.fireHookFileRules(null,null)};Ts.prototype.hasParser=function(){return!!this._nd.tsparse};Ts.prototype.reportNoParser=function(){let issue=new this._Issue(`.ts/.tsx support not loaded - run mode '${this._runMode}'`);this._reportJafIssue(issue,this._parser.RULE_TS_NO_PARSER,0,0,0,0)};Ts.prototype.getAst=function(){return this._Ast.getAst()};Ts.prototype.getAstUtils=function(){return this._Ast?this._Ast.getUtils():null};Ts.prototype._parseIt=function(data,file,fileType,cb){var ret=false,rowNow,colNow,issue,opts,arRawComs,startPos;try{this._debug(`Parsing ${fileType.toUpperCase()}...`);this._Ast=new AST(data,file,fileType,this._nd,this._ecmaVer,this._isComments,this._msgCtx,this._config);ret=!!this._Ast.getAst()}catch(e){startPos=this._parser.startJsPosition;opts=this._rules.getRuleOptions(this._parser.RULE_TS_DIAGNOSE,this._parser.JAF_RSI);if(opts&&opts.enabled){rowNow=e.lineNumber+(startPos.row===0?0:startPos.row-2);colNow=e.column+(startPos.col===0?0:startPos.col-1);e.message=e.message.replace("}","{");issue=new this._Issue("TypeScript syntax - "+e.message);this._reportJafIssue(issue,this._parser.RULE_TS_DIAGNOSE,rowNow,colNow,e.index+startPos.startIndex,e.index+startPos.startIndex+1)}else{rowNow=e.lineNumber+(startPos.row===0?0:startPos.row-2);colNow=e.column+(startPos.col===0?0:startPos.col-1);console.log(`\nTS-DIAGNOSE : [${rowNow}, ${colNow}] ${e.message}\n File -> ${this._curFile}`)}this._parser.parseErrors++;if(this._debugMode||this._verboseMode){this._info(`[TS PARSE ERROR(4) #${this._parser.parseErrors} : '${e.message}' File -> ${this._parser.curFile?this._parser.curFile:"n/a"}`)}}if(!ret){return ret}if(cb)cb(this._Ast.getProgram());ret=false;try{this._debug("Walking TS...");if(this._isComments){arRawComs=this._Ast.getRawComments();if(arRawComs&&arRawComs.length){if(!this._comments){this._comments=new Comments(this._nd,this._rules,this._msgCtx,this._utils,true)}this._comments.reset(this._Ast)}}this._fileType=fileType;this._Ast.walk(this._AstNodeHandler.bind(this));ret=true}catch(e){this._error(`TypeScript walk failure - ${e} in ${this._parser.curFile}`)}return ret};Ts.prototype._AstNodeHandler=function(node){var coms;if(this._rules.isTypeRegistered(node.type)){if(this._comments){coms=this._comments.isDisabled(node);if(coms&&(!coms.rules||coms.rules.length===0)){return}this._rules.setJSCommentCallback(coms?function(ruleName){var b=coms.rules.includes(ruleName);return!coms.invert?b:!b}:null)}this._rules.fireRules({type:node.type,node:node,position:{offset:this._parser.startJsPosition.startIndex,start:node.range[0],end:node.range[1]},data:this._Ast.getData(),utils:{AstUtils:this._Ast.getUtils(),tsxUtils:this._tsxUtils}},node,this._parser.curFile,this._parser.curFileType,null)}if(this._fileType==="tsx"){if(this._rules.isAnyTsxTypeRegistered()){this._fireTsxRules(node)}}};Ts.prototype._fireTsxRules=function(node){var _self=this;if(node.type===VAR_DECL||node.type===CALL_EXPR||node.type===RETURN_STMT||node.type===ASSIGN_EXPR){let result;if(result=this._jsx.genTsxRenderComponent(node,this._Ast.getData())){let syn=this._rules.getTsxRuleSynopsis();if(syn.isTsxRC){if(!Array.isArray(result)){_fireTsxRules(result)}else{result.forEach(tsxRC=>{_fireTsxRules(tsxRC)})}}if(syn.isTsxWC||syn.isTsxNamedComp||syn.isTsxComp||syn.isTsxElem||syn.isTsxJetWC||syn.isTsxProp){result.components.forEach(tsxComp=>{function _fireTsx(tsxComp){let props;if(syn.isTsxWC&&tsxComp.isWCTag){tsxComp.type="TsxWebComponent";_fireTsxRules(tsxComp)}if(syn.isTsxJetWC){tsxComp.type="TsxJetComponent";_fireTsxRules(tsxComp)}if(syn.isTsxComp){_fireTsxRules(tsxComp)}if(syn.isTsxElem&&!tsxComp.isPreactComp&&!tsxComp.isWCTag&&!tsxComp.NaT){tsxComp.type="TsxElem";_fireTsxRules(tsxComp)}if(syn.isTsxNamedComp){let t="Tsx<"+tsxComp.name+">";if(_self._rules.isTypeRegistered(t)){tsxComp.type=t;_fireTsxRules(tsxComp)}}if(syn.isAnyTsxCompAttr){if(props=tsxComp.properties){props.forEach(prop=>{let t=`Tsx<${tsxComp.name}|${prop.name}>`;if(_self._rules.isTypeRegistered(t)){prop.type=t;_fireTsxRules(prop)}})}}if(syn.isAnyTsxAttr){if(props=tsxComp.properties){props.forEach(prop=>{let t=`Tsx<${prop.name}=>`;if(_self._rules.isTypeRegistered(t)){prop.type=t;_fireTsxRules(prop)}})}}if(syn.isTsxProp){if(props=tsxComp.properties){props.forEach(prop=>{_fireTsxRules(prop)})}}if(tsxComp.children){tsxComp.children.forEach(child=>{_fireTsx(child)})}}_fireTsx(tsxComp)})}}}function _fireTsxRules(tsxObj){_self._rules.fireRules({type:tsxObj.type,node:tsxObj,position:{offset:_self._parser.startJsPosition.startIndex,start:tsxObj.range[0],end:tsxObj.range[1]},data:_self._Ast.getData(),utils:{AstUtils:_self._Ast.getUtils(),tsxUtils:_self._tsxUtils}},tsxObj,_self._parser.curFile,_self._parser.curFileType,tsxObj.type!=="TsxRenderComponent"?tsxObj.name:null)}};Ts.prototype.getAst=function(){return this._Ast};Ts.prototype.clear=function(){};module.exports=Ts;
|
package/lib/TsxUtils.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 HTML_UTILS=require("./HtmlUtils");const CB_END="end";const CB_NEXT_COMP="next-comp";var TsxUtils=function(){};TsxUtils.prototype.extractTsxProperties=function(ruleCtx,tsxRC,cb){this._onTsxRC(ruleCtx,tsxRC,cb)};TsxUtils.prototype.getProperty=function(
|
|
6
|
+
const TSX2_UTILS=require("./TsxUtils2");const HTML_UTILS=require("./HtmlUtils");const CB_END="end";const CB_NEXT_COMP="next-comp";const TSX_COMPONENT="TsxComponent";const TSX_PROPERTY="TsxProperty";const TEMPLATE="template";const OJ_DEFER="oj-defer";const OJ_BIND="oj-bind";const BODY="body";var TsxUtils=function(assert){this._fnAssert=assert};TsxUtils.prototype.extractTsxProperties=function(ruleCtx,tsxRC,cb){this._onTsxRC(ruleCtx,tsxRC,cb)};TsxUtils.prototype.getProperty=function(tsxObj,propName){return this._extractProp(tsxObj,propName)};TsxUtils.prototype._extractProp=function(tsxObj,propName){var ret,ot;if(tsxObj&&(ot=tsxObj.type)){if(ot===TSX_PROPERTY){return tsxObj}if(ot===TSX_COMPONENT&&propName){let props,prop,i;if(props=tsxObj.properties){for(i=0;i<props.length;i++){prop=props[i];if(prop.name===propName){ret=prop;break}}}}}return ret};TsxUtils.prototype.getPropertyRawValue=function(tsxComp,name,stripDelims){var prop,ret;if(prop=this.getProperty(tsxComp,name)){ret=prop.valueRaw;if(stripDelims&&ret.charAt(0)==="\""){ret=ret.charAt(1)==="\""?ret="":ret.substring(1,ret.length-1)}}return typeof ret==="string"?ret:null};TsxUtils.prototype.getPropertyValue=function(tsxComp,propName){var tsxProp,ret,obj,i;var a=propName.split(".");var major=a[0];if(tsxProp=this.getProperty(tsxComp,major)){if(a.length===1){return tsxProp.value}if(!this.isPropertyPreactExpr(tsxProp)){return undefined}obj=tsxProp.value.value;for(i=1;i<a.length;i++){major=a.shift();if(!_isObject(obj)){break}if((obj=obj[major])&&_isObject(obj)){continue}break}}return ret};TsxUtils.prototype.getPropertyStringValue=function(tsxObj,propName){var tsxProp,value,ret;if(tsxProp=this._extractProp(tsxObj,propName)){value=tsxProp.node.value;if(value!==null){ret=value.type==="Literal"&&typeof value.value==="string"?value.value:null}}else{ret=null}return ret};TsxUtils.prototype.isPropertyPreactExpr=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){ret=tsxProp.node.value.type==="JSXExpressionContainer"}return ret};TsxUtils.prototype.isPropertyObjectExpr=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){if(tsxProp.node.value.type==="JSXExpressionContainer"){let expr=tsxProp.node.value.expression;ret=expr&&expr.type==="ObjectExpression"}}return ret};TsxUtils.prototype.isPropertyString=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){ret=tsxProp.node.value.type==="Literal"&&typeof tsxProp.node.value.value==="string"}return ret};TsxUtils.prototype.getAncestor=function(tsxComp,name){var o,ret;name=name||tsxComp.name;while(o=tsxComp.parent){if(o.name===name){ret=o;break}tsxComp=o}return ret||null};TsxUtils.prototype.getChildren=function(tsxComp){return tsxComp.children};TsxUtils.prototype.getDescendant=function(tsxComp,name){var childs,child,ret,i;while(childs=tsxComp.children){for(i=0;i<childs.length;i++){child=childs[i];if(child.name===name){ret=child;break}if(ret=this.getDescendant(child,name)){break}}break}return ret||null};TsxUtils.prototype.getDirectDescendant=function(tsxComp,name){var childs,child,ret,i;if(childs=tsxComp.children){for(i=0;i<childs.length;i++){child=childs[i];if(child.name===name){ret=child;break}}}return ret||null};TsxUtils.prototype.isExpressionObject=function(tsxObj,propName){var tsxProp,ret;if(tsxProp=this._extractProp(tsxObj,propName)){if(tsxProp.node.value.type==="JSXExpressionContainer"){let expr=tsxProp.node.value.expression;ret=expr.type==="ObjectExpression"}}return!!ret};TsxUtils.prototype.getExpressionObject=function(tsxObj,propName){var tsxProp,obj;if(tsxProp=this._extractProp(tsxObj,propName)){if(!tsxProp.node.value){return null}if(tsxProp.node.value.type!=="JSXExpressionContainer"){return null}let expr=tsxProp.node.value.expression;if(expr.type==="ObjectExpression"){let props,stack;props=expr.properties;obj={};stack=[];props.forEach(prop=>{_doProp(prop,obj,stack,this._fnAssert)})}}return obj||null};TsxUtils.prototype.toCamelCase=function(str){return TSX2_UTILS.toCamelCase(str)};TsxUtils.prototype.toKebabCase=function(str){return TSX2_UTILS.toKebabCase(str)};function _doProp(prop,obj,stack,fnAssert){let key,elems,propx;if(prop.type==="Property"&&(prop.key.type==="Identifier"||prop.key.type==="Literal")){if(prop.key.type==="Identifier"){key=prop.key.name}else{key=prop.key.value}if(prop.value.type==="Literal"){obj[key]=prop.value.value}else if(prop.value.type==="Identifier"){obj[key]=prop.value.name}else if(prop.value.type==="ArrayExpression"){obj[key]=[];elems=prop.value.elements;elems.forEach(elem=>{if(elem.type==="Literal"){obj[key].push(elem.value)}else if(elem.type==="ObjectExpression"){elem.properties.forEach(prop=>{stack.push(obj);obj={};propx=_doProp(prop,obj,stack,fnAssert);obj=stack.pop();obj[key].push(propx)})}})}else if(prop.value.type==="FunctionExpression"){obj[key]=prop.value.body.body}else if(prop.value.type==="ObjectExpression"){let o,p,i,objProps=prop.value.properties;stack.push(obj);obj[key]=o={};obj=o;for(i=0;i<objProps.length;i++){p=objProps[i];if(p.key.type==="Identifier"){if(p.value.type==="Literal"){o[p.key.name]=p.value.value}else if(p.value.type==="ObjectExpression"){_doProp(p,obj,stack,fnAssert);obj=stack.pop()}else if(p.value.type==="Identifier"){o[p.key.name]=p.value.name}else if(p.value.type==="ArrowFunctionExpression"){o[p.key.name]=p.value}else{fnAssert(`TsxUtils._doProp file line=${prop?.loc.start.line} ${p.value.type}`)}}}}else if(prop.value.type==="MemberExpression"){obj[key]=prop.value}else if(prop.value.type==="TemplateLiteral"){obj[key]=null}else if(prop.value.type==="LogicalExpression"){obj[key]=prop.value}else if(prop.value.type==="AssignmentPattern"){fnAssert(`TsxUtils._doProp2 file line=${prop?.loc.start.line} key=${key} prop value type=${prop.value.type}`);obj[key]="?"}else{fnAssert(`TsxUtils._doProp2 file line=${prop?.loc.start.line} key=${key} prop value type=${prop.value.type}`);obj[key]="?"}}return obj};TsxUtils.prototype.setIssuePosition=function(issue,obj){if(obj.type===TSX_COMPONENT||obj.type===TSX_PROPERTY){let loc=obj.loc;issue.setPosition(loc.start.line,loc.start.column,obj.range[0],obj.range[1])}else{issue.setPosition(0,0,0,0)}};TsxUtils.prototype.setIssuePropValuePosition=function(issue,tsxProp){if(tsxProp.type==="TsxProperty"){let loc=tsxProp.node.value.loc;issue.setPosition(loc.start.line,loc.start.column,tsxProp.node.value.range[0],tsxProp.node.value.range[1])}else{issue.setPosition(0,0,0,0)}};TsxUtils.prototype.getRawtext=function(ruleCtx,tsxRC){return ruleCtx&&tsxRC&&tsxRC.range?ruleCtx.data.substring(tsxRC.range[0],tsxRC.range[1]):""};TsxUtils.prototype._onTsxRC=function(ruleCtx,tsxRC,cb){var comps,tsxComp,ret,i;if(!(comps=tsxRC.components)){return}for(i=0;i<comps.length;i++){tsxComp=comps[i];ret=this._checkComp(ruleCtx,tsxComp,cb);if(ret===CB_END){break}};cb(ruleCtx,null)};TsxUtils.prototype._checkComp=function(ruleCtx,tsxComp,cb){var props;if(props=tsxComp.properties){let prop,ret,i;for(i=0;i<props.length;i++){prop=props[i];ret=cb(ruleCtx,prop);if(ret===CB_END||ret===CB_NEXT_COMP){return ret}};}if(tsxComp.children){tsxComp.children.forEach(child=>{this._checkComp(ruleCtx,child,cb)})}};TsxUtils.prototype.getSlotParent=function(ruleCtx,tsxProp,slotName){var parent,isOjDefer=false,ret=null;parent=tsxProp.parent;if(!(parent=parent.parent)){return}isOjDefer=parent.name==="oj-defer";if(parent&&parent.name){if(parent.name!==BODY){if(ruleCtx.utils.metaLib.isTagSlotName(parent.name,slotName)){ret=parent}if(!ret){if(isOjDefer&&parent.name===TEMPLATE||parent.name==="oj-switcher"){ret=parent}else if(parent.name===TEMPLATE||parent.name.startsWith(OJ_BIND)||parent.name===OJ_DEFER){ret=_continueUpwards(ruleCtx,parent,slotName)}}}}return ret};function _continueUpwards(ruleCtx,tsxComp,slotName){var ret=null,parent,tagName;while(parent=tsxComp.parent){tagName=parent.name;if(tagName===TEMPLATE||tagName.startsWith(OJ_BIND)||tagName===OJ_DEFER){parent=parent.parent;continue}if(parent.name!==BODY){if(ruleCtx.utils.metaLib.isTagSlotName(tagName,slotName)){ret=parent}}break}return ret};function _isObject(value){return typeof value==="object"&&!Array.isArray(value)};TsxUtils.prototype.setMetaLib=function(metaLib){this._metaLib=metaLib};TsxUtils.prototype.isCommonElem=function(elem){return HTML_UTILS.isCommonElem(elem)};TsxUtils.prototype.isCommonAttr=function(attrName){return TSX2_UTILS.isCommonProp(attrName)||this.isAriaAttr(attrName)};TsxUtils.prototype.isCommonEventAttr=function(attrName){return TSX2_UTILS.isCommonEventProp(attrName)};TsxUtils.prototype.isHtml5ObsoleteElem=function(tag){return HTML_UTILS.isHtml5ObsoleteElem(tag)};TsxUtils.prototype.isAriaAttr=function(attr){return HTML_UTILS.isAriaAttr(attr)};TsxUtils.prototype.isSelfClosingTag=function(tag){return HTML_UTILS.isSelfClosingTag(tag)};TsxUtils.prototype.isSvgElem=function(elem){return HTML_UTILS.isSvgElem(elem)};module.exports=TsxUtils;
|
package/lib/TsxUtils2.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2023, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const DOT=".";const COMMON_PROPS={"accessKey":true,"class":true,"className":true,"contentEditable":true,"contextMenu":true,"dir":true,"draggable":true,"dropZone":true,"forHtml":true,"hidden":true,"id":true,"lang":true,"role":true,"spellCheck":true,"style":true,"tabIndex":true,"title":true,"translate":true};var COMMON_EVENT_PROPS={"onAbort":true,"onAuxClick":true,"onBlur":true,"onCanPlay":true,"onCanPlayThrough":true,"onChange":true,"onClick":true,"onContextMenu":true,"onDblClick":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,"onFormChange":true,"onFormInput":true,"onInput":true,"onInvalid":true,"onKeyDown":true,"onKeyPress":true,"onKeyUp":true,"onLoad":true,"onLoadedData":true,"onLoadedMetadata":true,"onLoadStart":true,"onMouseDown":true,"onMouseMove":true,"onMouseOut":true,"onMouseOver":true,"onMouseUp":true,"onMouseWheel":true,"onPause":true,"onPlay":true,"onPlaying":true,"onProgress":true,"onRateChange":true,"onReadyStateChange":true,"onScroll":true,"onSeeked":true,"onSeeking":true,"onSelect":true,"onShow":true,"onStalled":true,"onSubmit":true,"onSuspend":true,"onTimeUpdate":true,"onVolumeChange":true,"onWaiting":true};module.exports.isCommonProp=function(propName){return COMMON_PROPS[propName]};module.exports.isCommonEventProp=function(propName){return COMMON_EVENT_PROPS[propName]};module.exports.toCamelCase=function(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)};module.exports.toKebabCase=function(str){return str.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase()};
|
package/lib/Utils.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const daysOfWeek=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];const WHITESPACE=" \t\n\r\x0B";const NL="\n";const CR="\r";const DOT=".";const SP=" ";function Utils(nd){this._nd=nd;this._tabHandler=null};Utils.prototype.isObject=function(value){return typeof value==="object"&&!Array.isArray(value)};Utils.prototype.isArrayContentsType=function(ar,type){var i,elemType,ret=true;var isAr=Array.isArray(type);for(i=0;i<ar.length;i++){elemType=this.getType(ar[i]);if(isAr&&!type.includes(elemType)||!isAr&&elemType!==type){ret=false;break}}return ret};Utils.prototype.extend=function(from,internal,to){var prop,what;to=to||{};for(prop in from){if(!internal&&(prop.startsWith("_")||prop==="$builtin")){continue}what=from[prop];if(Array.isArray(what)){to[prop]=what.slice()}else{to[prop]=what}}return to};Utils.prototype.hasAnyProps=function(obj){var ret=false;if(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}}return ret};Utils.prototype.isProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length};Utils.prototype.getProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length?obj:undefined};Utils.prototype.splitString=function(s,sep){var a=s.split(sep);a.forEach(function(val,index){a[index]=a[index].trim()});return a};Utils.prototype.getType=function(val){var t=typeof val;if(val===undefined){t="undefined"}else if(val===null){t="null"}else if(t==="object"){if(Array.isArray(val)){t="array"}else if(this.isObject(val)){t="object"}else{console.log("[ASSERT] unknown object type' "+t+"'");t="?"}}return t};Utils.prototype.format=function(msg,vars){var v,k,k2,i;for(v in vars){k="${"+v+"}";k2=new RegExp("\\$\\{"+v+"\\}","g");i=msg.indexOf(k);if(i>=0){msg=msg.replace(k2,vars[v])}}return msg};Utils.prototype.removeMarkup=function(m){var s;if(!m){return m}s=m.replace(/<[^>]+>/g,"");s=s.replace(/\s\s+/g," ");return s};Utils.prototype.getRowColFromIndex=function(data,disp,fileType,tabs){var row=1,col=1,i,c,len=data.length;var oTabs=tabs?tabs:this._tabHandler;for(i=0;i<len;i++){if(i===disp)break;c=data.charAt(i);if(c==="\n"){row++;col=1}else if(c==="\t"){if(oTabs){col=oTabs.getTabCol(col,fileType)}else{col++}}else if(c!=="\r"){col++}}return{row:row,col:col}};Utils.prototype.decommentJson=function(text){return this._nd.decomment(text)};Utils.prototype.parseJson=function(data,comments){var obj,ret;comments=typeof comments!=="undefined"?!!comments:true;if(comments){data=this._nd.decomment(data)}let x=this.eatWhitespace(data);if(x>=0){let c=data.charAt(x);if(c!=="{"&&c!=="["){return this._convertJsonPosToRowCol(`Invalid JSON - unexpected start character '${c}' at position ${x}`,data)}}try{obj=JSON.parse(data);ret={obj:obj,msg:null,startIndex:undefined,endIndex:undefined}}catch(e){if(e.toString().startsWith("SyntaxError")){ret=this._convertJsonPosToRowCol(e.message,data)}else{ret.msg=e.message}ret.obj=null}return ret};Utils.prototype._convertJsonPosToRowCol=function(msg,data){var x,n,rc;x=msg.indexOf("position");if(x<0){if(msg.startsWith("Unexpected end of JSON")){msg+=` at position ${data.length-1}`;x=msg.indexOf("position")}else{n=data.length-1;return{msg:msg,line:0,row:0,startIndex:0,endIndex:0}}}n=parseInt(msg.substring(x+8).trim());rc=this.getRowColFromIndex(data,n);x=msg.indexOf("at");if(x>=0){msg=msg.substring(0,x).trimRight()}x=msg.indexOf("token");if(x>=0){x+=6;let c=msg.charAt(x);let q=c==="'"?"\"":"'";msg=msg.substring(0,x)+q+c+q+msg.substring(x+1)}return{msg:msg,line:rc.row,col:rc.col,startIndex:n,endIndex:n}};Utils.prototype.eatLine=function(str,index){var ret,i,c;index=index||0;if(index>str.length){ret=""}for(i=index;i<str.length;i++){c=str.charAt(i);if(c=="\n"){ret=str.substring(i+1);break}}return ret};Utils.prototype.getLineStart=function(data,index){var c;if(data.length&&index>0&&index<data.length){while(--index){c=data.charAt(index);if(c===NL||c===CR){return index+1}}}return 0};Utils.prototype.getIndexToWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(this.isWhitespace(str.charAt(i))){ret=i;break}}return ret};Utils.prototype.eatWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(WHITESPACE.indexOf(str[i])<0){ret=i;break}}return ret};Utils.prototype.isWhitespace=function(c){return WHITESPACE.indexOf(c)>=0};Utils.prototype.isAlpha=function(c){return c>="a"&&c<="z"||c>="A"&&c<="Z"};Utils.prototype.isDigit=function(c){return c>="0"&&c<="9"};Utils.prototype.isAlphaNum=function(c){return this.isAlpha(c)||this.isDigit(c)};Utils.prototype.getCurrentDate=function(dateObj){var date,dayOfweek,tmp;date=dateObj?dateObj:new Date;dayOfweek=daysOfWeek[date.getDay()];date=date.toString();tmp=date.split(" ");tmp[0]=dayOfweek;return dayOfweek+" "+tmp[1]+" "+tmp[2]+", "+tmp[3]};Utils.prototype.getCurrentTime=function(dateObj){var time,hours,mins,zone;var ampm="am";time=dateObj?dateObj:new Date;hours=time.getHours();mins=time.getMinutes();if(hours>12){hours-=12;ampm="pm"}zone=time.toLocaleTimeString("en-us",{timeZoneName:"short"}).split(" ")[2];return hours+":"+(mins<=9?"0":"")+mins+ampm+" "+zone};Utils.prototype.lineWrap=function(text,width=95,clean=true){if(Array.isArray(text)){let i;for(i=0;i<text.length;i++){let s=text[i];let c=s[s.length-1];if(c!==NL&&c!==SP){text[i]=s+SP}}text=text.join("")}if(clean){text=text.replace(/\<p\>/g,NL);text=text.replace(/\<br\>/g,NL);text=text.replace(/\<b\>/g,"");text=text.replace(/\<i\>/g,"");text=text.replace(/\<\/b\>/g,"");text=text.replace(/\<\/i\>/g,"");text=text.replace(/</g,"<");text=text.replace(/>/g,">")}return this.breakLines(text,width)};Utils.prototype.breakLines=function(s,width){var lines=[];var line,start,end,c,x,y;var len=s.length;s=s.trimRight();len=s.length;if(len<width||len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}if(len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}start=0;while(start<len){x=this.eatWhitespace(s,start);if(x>0){start=x}end=start+width;line=s.substring(start,end+1);if(end>=len){if((x=line.indexOf(NL))>=0){lines.push(line.substring(0,x));start+=x+1;continue}lines.push(line);return lines}if(this.isWhitespace(line.charAt(line.length-1))){for(x=line.length-1;this.isWhitespace(s.charAt(x));x--){}x+=start}else{x=end;c=s.charAt(end+1);if(this.isAlphaNum(c)){for(;x>=start;x--){if(this.isWhitespace(s.charAt(x))){break}}}}x++;if(start<x){line=s.substring(start,x).trimRight()}else{line=s.substring(start,end).trimRight();x=end++}if((y=line.indexOf(NL))>=0){line=line.substring(0,y);x=start+y}lines.push(line);start=x}return lines};Utils.prototype.setTabHandler=function(oTabs){this._tabHandler=oTabs};module.exports=Utils;
|
|
6
|
+
const daysOfWeek=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];const WHITESPACE=" \t\n\r\x0B";const NL="\n";const CR="\r";const DOT=".";const SP=" ";function Utils(nd){this._nd=nd;this._tabHandler=null};Utils.prototype.isObject=function(value){return typeof value==="object"&&!Array.isArray(value)};Utils.prototype.isArrayContentsType=function(ar,type){var i,elemType,ret=true;var isAr=Array.isArray(type);for(i=0;i<ar.length;i++){elemType=this.getType(ar[i]);if(isAr&&!type.includes(elemType)||!isAr&&elemType!==type){ret=false;break}}return ret};Utils.prototype.extend=function(from,internal,to){var prop,what;to=to||{};for(prop in from){if(!internal&&(prop.startsWith("_")||prop==="$builtin")){continue}what=from[prop];if(Array.isArray(what)){to[prop]=what.slice()}else{to[prop]=what}}return to};Utils.prototype.hasAnyProps=function(obj){var ret=false;if(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}}return ret};Utils.prototype.isProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length};Utils.prototype.getProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length?obj:undefined};Utils.prototype.splitString=function(s,sep){var a=s.split(sep);a.forEach(function(val,index){a[index]=a[index].trim()});return a};Utils.prototype.getType=function(val){var t=typeof val;if(val===undefined){t="undefined"}else if(val===null){t="null"}else if(t==="object"){if(Array.isArray(val)){t="array"}else if(this.isObject(val)){t="object"}else{console.log("[ASSERT] unknown object type' "+t+"'");t="?"}}return t};Utils.prototype.format=function(msg,vars){var v,k,k2,i;for(v in vars){k="${"+v+"}";k2=new RegExp("\\$\\{"+v+"\\}","g");i=msg.indexOf(k);if(i>=0){msg=msg.replace(k2,vars[v])}}return msg};Utils.prototype.removeMarkup=function(m){var s;if(!m){return m}s=m.replace(/<[^>]+>/g,"");s=s.replace(/\s\s+/g," ");return s};Utils.prototype.getRowColFromIndex=function(data,disp,fileType,tabs){var row=1,col=1,i,c,len=data.length;var oTabs=tabs?tabs:this._tabHandler;for(i=0;i<len;i++){if(i===disp)break;c=data.charAt(i);if(c==="\n"){row++;col=1}else if(c==="\t"){if(oTabs){col=oTabs.getTabCol(col,fileType)}else{col++}}else if(c!=="\r"){col++}}return{row:row,col:col}};Utils.prototype.decommentJson=function(text){return this._nd.decomment(text)};Utils.prototype.parseJson=function(data,comments){var obj,ret;comments=typeof comments!=="undefined"?!!comments:true;if(comments){data=this._nd.decomment(data)}let x=this.eatWhitespace(data);if(x>=0){let c=data.charAt(x);if(c!=="{"&&c!=="["){return this._convertJsonPosToRowCol(`Invalid JSON - unexpected start character '${c}' at position ${x}`,data)}}try{obj=JSON.parse(data);ret={obj:obj,msg:null,startIndex:undefined,endIndex:undefined}}catch(e){if(e.toString().startsWith("SyntaxError")){ret=this._convertJsonPosToRowCol(e.message,data)}else{ret.msg=e.message}ret.obj=null}return ret};Utils.prototype._convertJsonPosToRowCol=function(msg,data){var x,n,rc;x=msg.indexOf("position");if(x<0){if(msg.startsWith("Unexpected end of JSON")){msg+=` at position ${data.length-1}`;x=msg.indexOf("position")}else{n=data.length-1;return{msg:msg,line:0,row:0,col:0,startIndex:0,endIndex:0}}}n=parseInt(msg.substring(x+8).trim());rc=this.getRowColFromIndex(data,n);x=msg.indexOf("at");if(x>=0){msg=msg.substring(0,x).trimRight()}x=msg.indexOf("token");if(x>=0){x+=6;let c=msg.charAt(x);let q=c==="'"?"\"":"'";msg=msg.substring(0,x)+q+c+q+msg.substring(x+1)}return{msg:msg,line:rc.row,col:rc.col,startIndex:n,endIndex:n}};Utils.prototype.eatLine=function(str,index){var ret,i,c;index=index||0;if(index>str.length){ret=""}for(i=index;i<str.length;i++){c=str.charAt(i);if(c=="\n"){ret=str.substring(i+1);break}}return ret};Utils.prototype.getLineStart=function(data,index){var c;if(data.length&&index>0&&index<data.length){while(--index){c=data.charAt(index);if(c===NL||c===CR){return index+1}}}return 0};Utils.prototype.getIndexToWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(this.isWhitespace(str.charAt(i))){ret=i;break}}return ret};Utils.prototype.eatWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(WHITESPACE.indexOf(str[i])<0){ret=i;break}}return ret};Utils.prototype.isWhitespace=function(c){return WHITESPACE.indexOf(c)>=0};Utils.prototype.isAlpha=function(c){return c>="a"&&c<="z"||c>="A"&&c<="Z"};Utils.prototype.isDigit=function(c){return c>="0"&&c<="9"};Utils.prototype.isAlphaNum=function(c){return this.isAlpha(c)||this.isDigit(c)};Utils.prototype.getCurrentDate=function(dateObj){var date,dayOfweek,tmp;date=dateObj?dateObj:new Date;dayOfweek=daysOfWeek[date.getDay()];date=date.toString();tmp=date.split(" ");tmp[0]=dayOfweek;return dayOfweek+" "+tmp[1]+" "+tmp[2]+", "+tmp[3]};Utils.prototype.getCurrentTime=function(dateObj){var time,hours,mins,zone;var ampm="am";time=dateObj?dateObj:new Date;hours=time.getHours();mins=time.getMinutes();if(hours>12){hours-=12;ampm="pm"}zone=time.toLocaleTimeString("en-us",{timeZoneName:"short"}).split(" ")[2];return hours+":"+(mins<=9?"0":"")+mins+ampm+" "+zone};Utils.prototype.lineWrap=function(text,width=95,clean=true){if(Array.isArray(text)){let i;for(i=0;i<text.length;i++){let s=text[i];let c=s[s.length-1];if(c!==NL&&c!==SP){text[i]=s+SP}}text=text.join("")}if(clean){text=text.replace(/\<p\>/g,NL);text=text.replace(/\<br\>/g,NL);text=text.replace(/\<b\>/g,"");text=text.replace(/\<i\>/g,"");text=text.replace(/\<\/b\>/g,"");text=text.replace(/\<\/i\>/g,"");text=text.replace(/</g,"<");text=text.replace(/>/g,">")}return this.breakLines(text,width)};Utils.prototype.breakLines=function(s,width){var lines=[];var line,start,end,c,x,y;var len=s.length;s=s.trimRight();len=s.length;if(len<width||len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}if(len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}start=0;while(start<len){x=this.eatWhitespace(s,start);if(x>0){start=x}end=start+width;line=s.substring(start,end+1);if(end>=len){if((x=line.indexOf(NL))>=0){lines.push(line.substring(0,x));start+=x+1;continue}lines.push(line);return lines}if(this.isWhitespace(line.charAt(line.length-1))){for(x=line.length-1;this.isWhitespace(s.charAt(x));x--){}x+=start}else{x=end;c=s.charAt(end+1);if(this.isAlphaNum(c)){for(;x>=start;x--){if(this.isWhitespace(s.charAt(x))){break}}}}x++;if(start<x){line=s.substring(start,x).trimRight()}else{line=s.substring(start,end).trimRight();x=end++}if((y=line.indexOf(NL))>=0){line=line.substring(0,y);x=start+y}lines.push(line);start=x}return lines};Utils.prototype.setTabHandler=function(oTabs){this._tabHandler=oTabs};Utils.prototype.removeLink=function(s){if(s){s=s.replace(/<a\b[^>]*>/i,"");s=s.replace(/<\/a>/i,"")}return s};module.exports=Utils;
|
package/lib/ZipUtils.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const TEMP_ZIP_TEMPLATE=
|
|
6
|
+
const TEMP_ZIP_TEMPLATE="@@ziptmp-XXXXXX.zip";var ZipUtils=function(nd,fsUtils){if(!this._unzipper){this._unzipper=require("adm-zip")}this._zip=null;this._nd=nd;this._fsUtils=fsUtils};ZipUtils.prototype.loadZip=function(zipPath){var ret;this._assertNoCurrentZip();this._zip=null;try{this._zip=new this._unzipper(zipPath);ret=true}catch(e){ret=e}return ret};ZipUtils.prototype.extractAll=function(to,zipPath,overwrite){var ret=false;try{this._assertNoCurrentZip();this._zip=null;this._zip=new this._unzipper(zipPath);if(this._zip){this._zip.extractAllTo(to,!!overwrite);ret=true}}catch(e){ret={message:e}}this._zip=null;return ret};ZipUtils.prototype.extractFileFromZip=function(filePath,zipPath){var text;try{if(zipPath){this._assertNoCurrentZip();this._zip=null;this._zip=new this._unzipper(zipPath)}if(this._zip){text=this._zip.readAsText(filePath);text=text?text.trim():""}}catch(e){text=e}return text};ZipUtils.prototype.getContents=function(zipPath){var entries,ret=[];if(typeof zipPath==="string"){try{this._assertNoCurrentZip();this._zip=null;this._zip=new this._unzipper(zipPath)}catch(e){ret=e}}if(this._zip){ret=[];entries=this._zip.getEntries();this._hierIndex=0;this._createHierarchy(entries,"",ret)}return ret};ZipUtils.prototype._createHierarchy=function(entries,subdir,ar){var entry,arDir,temp,x;for(;this._hierIndex<entries.length;this._hierIndex++){entry=entries[this._hierIndex];if(entry.isDirectory){if(entry.entryName.startsWith(subdir)||!subdir){arDir=[];temp=entry.entryName.substr(0,entry.entryName.length-1);x=temp.lastIndexOf("/");temp=x>=0?temp.substring(x+1):temp;ar.push({name:temp,path:entry.entryName,isFile:false,files:arDir});this._hierIndex++;this._createHierarchy(entries,entry.entryName,arDir)}else{this._hierIndex--;return}}else{if(entry.entryName.startsWith(subdir)||!subdir){ar.push({name:entry.name,isFile:true})}else{this._hierIndex--;return}}}};ZipUtils.prototype.writeBufferToFile=function(buffer,fpath){var ret;try{this._lastFile=fpath;this._nd.fs.writeFileSync(fpath,buffer);ret=true}catch(e){this._lastFile=null;ret=e}return ret};ZipUtils.prototype.deleteFile=function(fpath){var ret=null;try{fpath=fpath?fpath:this._lastFile;if(fpath){this._nd.fs.unlinkSync(fpath)}}catch(e){ret=e}this._zip=null;return ret};ZipUtils.prototype.getLastFilepath=function(){return this._lastFile};ZipUtils.prototype.createTempZipFilename=function(){return this._fsUtils.getUniqueFileName(TEMP_ZIP_TEMPLATE)};ZipUtils.prototype._assertNoCurrentZip=function(){if(this._zip){this._assert("loadZip but Zip EXISTS")}};module.exports=ZipUtils;
|
package/lib/checkage.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 BUILT="2023-
|
|
6
|
+
const BUILT="2023-07-08T00:29:43.897Z";function CheckAge(msgCtx){this._jetRels=-1;this._msgCtx=msgCtx}CheckAge.prototype.checkAge=function(){var curDate;var buildDate;var buildMonth;var monthsToNow;curDate=new Date;buildDate=BUILT==="@BUILT@"?curDate:new Date(BUILT);buildMonth=buildDate.getMonth()+1;monthsToNow=_getElapsedMonths(buildDate,curDate);if(!monthsToNow){return 0}this._jetRels=_getReleases(buildMonth,monthsToNow);if(this._jetRels>2){this._emitMsg(monthsToNow)}return this._jetRels};CheckAge.prototype.getJetReleaseCount=function(){return this._jetRels};CheckAge.prototype._emitMsg=function(old){var INDENT=" ".repeat(8);var s,h,p;if(this._jetRels){s=""+this._jetRels;if(this._jetRels===1){h="has";p=""}else{h="have";p="s"}}else{s="at least one";h="has";p=""}var s=`\nThis version of JAF is ${old} month${old===1?"":"s"} old, and there ${h} been ${s} scheduled public\n`+`${INDENT}major JET release${p}, together with JAF updates and fixes. It is strongly\n`+INDENT+"recommended that you install the latest version of JAF. [JAF-9100]\n";this._msgCtx.warn(s,true)};function _getElapsedMonths(start,end){return end.getMonth()-start.getMonth()+12*(end.getFullYear()-start.getFullYear())};function _getReleases(buildMonth,months){var toNextRel,releases=0;if(buildMonth===1){toNextRel=0}else if(buildMonth>1&&buildMonth<7){toNextRel=7-buildMonth}else if(buildMonth===7){toNextRel=0}else{toNextRel=13-buildMonth}if((releases=months-toNextRel)>=0){releases=1+Math.floor(releases/6)}else{releases=0}return releases};module.exports=CheckAge;
|
package/lib/cmdline.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const OUTFMT=require("../lib/outFormat");const MACROS=require("../lib/macros");const ARG_CONFIG="--config";const ARG_CONFIG_SHORT="-c";const ARG_BASE="--base";const ARG_BASE_SHORT="-b";const ARG_SEVERITY="--severity";const ARG_SEVERITY_SHORT="-s";const ARG_FORMAT="--format";const ARG_FORMAT_SHORT="-t";const ARG_FOLLOWLINKS="--followlinks";const ARG_FOLLOWLINKS_SHORT="-fl";const ARG_NOFOLLOWLINKS="--nofollowlinks";const ARG_NOFOLLOWLINKS_SHORT="-nfl";const ARG_SHOWRULES="--rules";const ARG_SHOWRULES_SHORT="-r";const ARG_SHOWRULESJSON="--rulesjson";const ARG_SHOWRULESJSON_SHORT="-rj";const ARG_SHOWRULESSONAR="--rulessonar";const ARG_SHOWRULESSONAR_SHORT="-rs";const ARG_SHOWRULES_INTERNAL="-rx";const ARG_OUTPATH="--outpath";const ARG_OUTPATH_SHORT="-o";const ARG_NO_OUT="--noout";const ARG_NO_OUT_SHORT="-no";const ARG_NOCOLOR="--nocolor";const ARG_NOCOLOR_SHORT="-nc";const ARG_NODEBUG="--nodebug";const ARG_NODEBUG_SHORT="-nd";const ARG_NOVERBOSE="--noverbose";const ARG_NOVERBOSE_SHORT="-nv";const ARG_NOEXTRA="--noextra";const ARG_NOEXTRA_SHORT="-ne";const ARG_GROUPS="--groups";const ARG_GROUPS_SHORT="-g";const ARG_GROUPS_EQ="--groups=";const ARG_GROUPS_EQ_SHORT="-g=";const ARG_MSGID="--msgid";const ARG_MSGID_SHORT="-id";const ARG_WATCH="--watch";const ARG_WATCH_SHORT="-w";const ARG_VERSION="--version";const ARG_VERSION_SHORT="-v";const ARG_JETLIST="--jetlist";const ARG_JETLIST_SHORT="-jl";const ARG_DEFLIST="--default";const ARG_DEFLIST_ALT="--deflist";const ARG_DEFLIST_SHORT="-def";const ARG_GROUPLIST="--grouplist";const ARG_GROUPLIST_SHORT="-gl";const ARG_XGROUPLIST="--xgrouplist";const ARG_XGROUPLIST_SHORT="-xgl";const ARG_DISLIST="--dislist";const ARG_DISLIST_SHORT="-dl";const ARG_DEPLIST="--deplist";const ARG_DEPLIST_SHORT="-dpl";const ARG_JETVER="--jetver";const ARG_JETVER_SHORT="-jv";const ARG_NAMESPACE_LIST="--nslist";const ARG_NAMESPACE_LIST_SHORT="-nsl";const ARG_PROFILES_LIST="--profiles";const ARG_PROFILES_LIST_SHORT="-prof";const ARG_AMDLIST="--amdlist";const ARG_AMDLIST_SHORT="-amd";const ARG_RLOLIST="--loadorder";const ARG_RLOLIST_SHORT="-rlo";const ARG_BETALIST="--betalist";const ARG_BETALIST_SHORT="-bl";const ARG_METAHIST="--metahist";const ARG_METAHIST_SHORT="-mh";const ARG_RC="--retcode";const ARG_RC_EQ="--retcode=";const ARG_RC_SHORT="-rc";const ARG_RC_EQ_SHORT="-rc=";const ARG_DRYRUN="--dryrun";const ARG_DRYRUN_SHORT="-dr";const ARG_DAC="--daconfig";const ARG_DAC_SHORT="-dac";const ARG_REG="--reg";const ARG_REG_SHORT="-reg";const ARG_HELP="--help";const ARG_HELP_SHORT="-h";const ARG_HELP_SHORT_S="-hs";const ARG_EXTRA="--extra";const ARG_EXTRA_SHORT="-e";const ARG_DEBUG="--debug";const ARG_DEBUG_SHORT="-d";const ARG_SCAFFOLD="--init";const ARG_SCAFFOLD_SHORT="-i";const ARG_SCAFFOLD_RULE="--initrule";const ARG_SCAFFOLD_RULE_SHORT="-ir";const ARG_UNIT_TEST="-ut";const ARG_OJET="--ojet";const ARG_OJET_SHORT="-ojet";const ARG_EXPERIMENTAL="--x";const ARG_EXPERIMENTAL_SHORT="-x";module.exports.checkArgs=function(nodeDeps,rtf,showHelp,showVersion,appCtx){var argLen,argOrig,arg,dontRun,temp,x,bArgsOk=true,bWantHelp=false,debugTitle;rtf.jetauditdir=nodeDeps.process.argv[1];rtf.jetauditdir=nodeDeps.path.dirname(rtf.jetauditdir);_checkBaseOptions(rtf,appCtx.colors);if(rtf.debugSet){_dumpCmdLine()}argLen=process.argv.length;for(var i=2;i<argLen;i++){argOrig=process.argv[i];arg=argOrig.toLowerCase().trim();if(arg.length===0){continue}if(arg.charAt(0)!=="-"){if(!rtf.srcStack){rtf.srcStack=[]}arg=process.argv[i];arg=_handleQuotes(arg);arg=nodeDeps.path.normalize(arg);arg=nodeDeps.path.resolve(arg);rtf.srcStack.push(arg);if(rtf.debugMode||rtf.verboseMode){if(!debugTitle){appCtx.info("Command line files specified:");debugTitle=true}appCtx.info(" "+arg)}continue}if(arg.endsWith("?")){temp=arg.replace(/[\-\?]/g,"");rtf.manCheckL=temp;rtf.isManual=true;rtf.isManPage=true;break}if(_isBaseOption(arg)){continue}else if(arg===ARG_MSGID||arg===ARG_MSGID_SHORT){rtf.msgIdMode=rtf.msgIdModeSet=true}else if(arg===ARG_VERSION||arg===ARG_VERSION_SHORT){showVersion();dontRun=true}else if(arg===ARG_HELP||arg===ARG_HELP_SHORT||arg===ARG_HELP_SHORT_S){if(i+1<argLen){temp=process.argv[i+1];if(temp.charAt(0)==="-"){showHelp();dontRun=true;if(!_isBaseOption(temp))appCtx.error(`Unexpected '${temp}'`);break}i++;if(arg===ARG_HELP||arg===ARG_HELP_SHORT){rtf.manCheckL=temp}else{rtf.manCheckS=temp}rtf.isManual=true;if(rtf.st_configSet){break}}else{showHelp();dontRun=true;break}}else if(arg===ARG_JETLIST||arg===ARG_JETLIST_SHORT){rtf.jetverList=true;break}else if(arg.startsWith(ARG_DEFLIST)||arg.startsWith(ARG_DEFLIST_SHORT)||arg.startsWith(ARG_DEFLIST_ALT)){rtf.defList=true;break}else if(arg===ARG_NAMESPACE_LIST||arg===ARG_NAMESPACE_LIST_SHORT){rtf.cmdNSList=true;break}else if(arg===ARG_PROFILES_LIST||arg===ARG_PROFILES_LIST_SHORT){rtf.profList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,false);break}else if(arg===ARG_DISLIST||arg===ARG_DISLIST_SHORT){rtf.disList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_DEPLIST||arg===ARG_DEPLIST_SHORT){rtf.depList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_AMDLIST||arg===ARG_AMDLIST_SHORT){rtf.amdList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_RLOLIST||arg===ARG_RLOLIST_SHORT){rtf.rloList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_BETALIST||arg===ARG_BETALIST_SHORT){rtf.betaList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_GROUPLIST||arg===ARG_GROUPLIST_SHORT){rtf.groupList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_XGROUPLIST||arg===ARG_XGROUPLIST_SHORT){rtf.xgroupList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true)}else if(arg===ARG_METAHIST||arg===ARG_METAHIST_SHORT){rtf.cmdMetaHist=true;break}else if(arg===ARG_CONFIG||arg===ARG_CONFIG_SHORT){i++;if(i<argLen){arg=process.argv[i];rtf.configPath=nodeDeps.path.normalize(arg);rtf.configPath=nodeDeps.path.resolve(rtf.configPath);rtf.st_configSet=true;if(rtf.isManual||rtf.xgroupList){break}}else{appCtx.error("Invalid --config option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_BASE||arg===ARG_BASE_SHORT){i++;if(i<argLen){rtf.base=process.argv[i];if(rtf.base===MACROS.cwd||appCtx.utils.getFileType(rtf.base)==="d"){rtf.st_baseSet=true}else{appCtx.error(`'--base' ${rtf.base} is not a directory or the '$jafcwd' macro!!`);bArgsOk=false;bWantHelp=true}}else{appCtx.error("Invalid --base option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_SEVERITY||arg===ARG_SEVERITY_SHORT){i++;if(i<argLen){rtf.severitySet=true;rtf.cliSev=process.argv[i]}else{appCtx.error("Invalid --severity option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_JETVER||arg===ARG_JETVER_SHORT){i++;argOrig=i<argLen?process.argv[i]:null;arg=nodeDeps.jetver.validate(argOrig);if(arg){appCtx.error(arg);bArgsOk=false;break}arg=nodeDeps.jetver.getBestVersion(argOrig);if(!arg){appCtx.error(`'${argOrig}' is not a valid JET version`);bArgsOk=false;break}rtf.jetverSet=arg;if((rtf.verboseMode||rtf.debugMode)&&arg!==argOrig){appCtx._info(`[Info]: JET version '${argOrig}' was promoted to '${arg}'`)}}else if(arg===ARG_FORMAT||arg===ARG_FORMAT_SHORT){i++;if(i<argLen){argOrig=process.argv[i];arg=argOrig.toLowerCase();if(arg!==OUTFMT.JSON&&arg!==OUTFMT.PROSE&&arg!==OUTFMT.LINE){appCtx.error(`Invalid --format(-t) option '${argOrig}'`);bArgsOk=false;bWantHelp=true}else{rtf.outFormat=arg;rtf.st_formatSet=true}}else{appCtx.error("Invalid --format option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_OUTPATH||arg===ARG_OUTPATH_SHORT){i++;if(rtf.st_outPathSet){appCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{if(i<argLen){arg=process.argv[i];arg=nodeDeps.path.normalize(arg);rtf.outPath=nodeDeps.path.resolve(arg);rtf.st_outPathSet=true}else{appCtx.error("Invalid --outPath option");bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_NO_OUT||arg===ARG_NO_OUT_SHORT){if(rtf.st_outPathSet){appCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{rtf.outPath="$noout";rtf.st_outPathSet=true}}else if(arg===ARG_FOLLOWLINKS||arg===ARG_FOLLOWLINKS_SHORT){rtf.followLinks=rtf.followLinksSet=true}else if(arg===ARG_NOFOLLOWLINKS||arg===ARG_NOFOLLOWLINKS_SHORT){rtf.followLinks=false;rtf.followLinksSet=true}else if(arg.startsWith(ARG_GROUPS_EQ)||arg.startsWith(ARG_GROUPS_EQ_SHORT)){x=arg.indexOf("=");if(temp=_convertToArray(argOrig.substring(x+1))){rtf.groupsSet=temp}else{appCtx.error(`Invalid 'groups' declaration '${argOrig}`);bArgsOk=false;bWantHelp=true}}else if(arg===ARG_GROUPS||arg===ARG_GROUPS_SHORT){rtf.groupsSet=_checkGroups(process.argv,i+1);if(!rtf.groupsSet.groups||rtf.groupsSet.groups.length===0){appCtx.error(!rtf.groupsSet.groups?`groups missing after flag ${argOrig}`:`Invalid ${argOrig} specification`);bArgsOk=false;bWantHelp=true}i=rtf.groupsSet.next;rtf.groupsSet=rtf.groupsSet.groups}else if(arg.startsWith(ARG_RC_EQ)||arg.startsWith(ARG_RC_EQ_SHORT)||arg===ARG_RC||arg===ARG_RC_SHORT){arg=argOrig;x=arg.indexOf("=");if(x>0){temp=argOrig.substring(0,x);arg=argOrig.substring(x+1)}else{temp=arg;i++;if(i<argLen){arg=process.argv[i]}else{appCtx.error(`missing arguments after '${argOrig}'`);bArgsOk=false;bWantHelp=true}}if(bArgsOk){temp=_processRetCode(temp,arg);if(temp||typeof temp==="number"){rtf.retCode=temp;rtf.st_retCodeSet=true}else{appCtx.error(`'${argOrig}' : ${arg.length?"'${arg}' is invalid":"missing argument?"}`);bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_SHOWRULES||arg===ARG_SHOWRULES_SHORT){rtf.dumpRulesSet=true}else if(arg===ARG_SHOWRULESJSON||arg===ARG_SHOWRULESJSON_SHORT){rtf.dumpRulesJsonSet=true}else if(arg===ARG_SHOWRULESSONAR||arg===ARG_SHOWRULESSONAR_SHORT){rtf.dumpRulesSonarSet=true}else if(arg===ARG_SHOWRULES_INTERNAL){rtf.dumpRulesInternalSet=true}else if(arg===ARG_DRYRUN||arg===ARG_DRYRUN_SHORT){rtf.dryRunSet=rtf.dacSet=rtf.verboseMode=rtf.verboseSet=rtf.dumpRulesSet=true}else if(arg===ARG_DAC||arg===ARG_DAC_SHORT){rtf.dacSet=true}else if(arg===ARG_REG||arg===ARG_REG_SHORT){rtf.regListenerTypesSet=true}else if(arg===ARG_UNIT_TEST){rtf.unitTest=true}else if(arg===ARG_OJET||arg===ARG_OJET_SHORT){rtf.isOJETCLI=true}else if(arg===ARG_EXPERIMENTAL||arg===ARG_EXPERIMENTAL_SHORT){rtf.experimentalSet=true}else if(arg===ARG_WATCH||arg===ARG_WATCH_SHORT){if(rtf.experimentalSet){rtf.watchSet=true}}else if(arg===ARG_SCAFFOLD||arg===ARG_SCAFFOLD_SHORT){rtf.scaffoldSet=true}else if(arg===ARG_SCAFFOLD_RULE||arg===ARG_SCAFFOLD_RULE_SHORT){i++;if(i<argLen){rtf.scaffoldRuleSet=process.argv[i]}else{appCtx.error("Invalid --initrule argument: rule name missing ");bArgsOk=false;bWantHelp=true}}else if(arg==="-z"){}else{console.log("");appCtx.error(`Invalid command flag '${argOrig}' (Use ojaf -h to get help)`);bArgsOk=false;dontRun=true}}return dontRun?"end":bArgsOk};module.exports.displayCmdLineOptionsSet=function(rtf,appCtx){var s="\n** Command line options:\n";if(rtf.dryRunSet){s+=" - Dry run ON\n"}if(rtf.dacSet){s+=" - Display active config ON\n"}if(rtf.verboseMode){s+=" - Verbose mode ON\n"}if(rtf.debugMode){s+=" - Debug mode ON\n"}if(rtf.watchSet){s+=" - watch mode ON\n"}if(rtf.groupsSet){s+=` - Groups set to ${rtf.groupsSet}\n`}if(rtf.st_retCodeSet){s+=` - retCode set to ${rtf.retCode}\n`}if(rtf.colorSet){s+=` - Color mode ${rtf.colorMode}? "ON" : "OFF"}\n`}if(rtf.msgIdModeSet){s+=` - Show msg ID's(${rtf.msgIdModeSet}? "ON" : "OFF"}\n`}if(rtf.st_formatSet){s+=` - Output in ${rtf.outFormat.toUpperCase()} format\n`}if(rtf.st_configSet){s+=` - Config set to ${rtf.configPath}\n`}if(rtf.severitySet){s+=` - Severity set to '${rtf.severity}'\n`}if(rtf.st_outPathSet){s+=` - Outpath set to ${rtf.outPath==="$noout"?"'none'":rtf.outPath}\n`}if(rtf.st_baseSet){s+=` - Base set to ${rtf.base}\n`}if(rtf.jetverSet){s+=` - JET version set to ${rtf.jetverSet}\n`}if(rtf.followLinksSet){s+=` - following stylesheet links is ${rtf.followLinks?"ON":"OFF"}\n`}if(rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumRulesSonarSet){s+=" - Dump Rules ON\n"}appCtx.console(s+"\n")};module.exports.isCmdLineOptionsSet=function(rtf){return rtf.verboseMode||rtf.debugMode||rtf.colorSet||rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumpRulesSonarSet||rtf.dumpRulesInternalSet||rtf.msgIdModeSet||rtf.severitySet||rtf.watchSet||rtf.jetverSet||rtf.followLinksSet||rtf.dryRunSet||rtf.jetverList||rtf.cmdNSList||rtf.groupList||rtf.xgroupList||rtf.disList||rtf.cmdMetaHist||rtf.amdList||rtf.rloList||rtf.betaList||rtf.profList||rtf.st_baseSet||rtf.st_formatSet||rtf.st_configSet||rtf.st_outPathSet||rtf.st_retCodeSet};function _checkBaseOptions(rtf,clr){var i,arg,argLen=process.argv.length;for(i=2;i<argLen;i++){arg=process.argv[i];if(arg.length===0||arg.charAt(0)!=="-"){continue}arg=arg.toLowerCase();if(arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT){rtf.verboseMode=rtf.verboseSet=true}else if(arg===ARG_NOEXTRA||arg===ARG_NOEXTRA_SHORT||arg===ARG_NOVERBOSE||arg===ARG_NOVERBOSE_SHORT){rtf.verboseMode=false;rtf.verboseSetVeto=true}else if(arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT){rtf.debugMode=rtf.debugSet=true;rtf.debugMode=rtf.debugSet=rtf.verboseMode=true}else if(arg===ARG_NODEBUG||arg===ARG_NODEBUG_SHORT){rtf.debugMode=false;rtf.debugSetVeto=true}else if(arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT){rtf.colorMode=false;rtf.colorSet=true;clr.enable(false)}}};function _isBaseOption(arg){return arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT||arg===ARG_NOEXTRA||arg===ARG_NOEXTRA_SHORT||arg===ARG_NOVERBOSE||arg===ARG_NOVERBOSE_SHORT||arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT||arg===ARG_NODEBUG||arg===ARG_NODEBUG_SHORT||arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT};function _checkGroups(args,i){var arg,a,x,last,bound,groups;x=i;for(;;i++){if(i>=args.length||args[i].charAt(0)==="-"||last){break}arg=args[i].trim();if(x===i){bound=arg.startsWith("[")||arg.startsWith("(")}last=bound&&(arg.endsWith("]")||arg.endsWith(")"));arg=arg.replace(/[\[\(\)\]]/g,"").trim();if(!arg.length){break}arg=arg.replace(/,/g," ");arg=arg.replace(/ +(?= )/g,"").trim();if(!groups){groups=[]}a=arg.split(" ");groups=groups.concat(a)}return{next:bound?i:x,groups:groups}};function _processRetCode(arg,val){var temp,ret;if(val==="auto"||val==="errors"){ret=val}else{temp=parseInt(val);if(!isNaN(temp)){ret=temp}else{if(temp=_convertToArray(val)){ret=temp}}}return ret};function checkNextArg(i,argLen,error,argType){var temp,lcTemp;if(i+1<argLen){temp=process.argv[i+1];lcTemp=temp.toLowerCase();if(temp.charAt(0)==="-"){if(!_isBaseOption(temp)&&lcTemp!==ARG_CONFIG&&lcTemp!==ARG_CONFIG_SHORT){error(`Unexpected '${temp}' - expected nothing, or a ${argType?"built-in pack prefix":"profile name"}`)}temp=undefined}}return temp};function _convertToArray(s){var a,n,i;if(s.charAt(0)==="["){s=s.substring(1);if(!s.length){return null}}if(s.charAt(s.length-1)==="]"){s=s.substring(0,s.length-1)}s=s.trim();if(!s.length){return null}s=s.replace(/\,/g," ");s=s.replace(/\s\s+/g," ").trim();a=s.split(" ");n=0;for(i=0;i<a.length;i++){if(a[i].length){n++}else{a=a.splice(i,1);i--}}return n?a:null};function _handleQuotes(s){return s.replace(/[\"\']/g,"")};function _dumpCmdLine(){var s="";for(var i=0;i<process.argv.length;i++){s+=`[${i}]: |${process.argv[i]}|\n`}console.log(s)}
|
|
6
|
+
const OUTFMT=require("../lib/outFormat");const MACROS=require("../lib/macros");const ARG_CONFIG="--config";const ARG_CONFIG_SHORT="-c";const ARG_BASE="--base";const ARG_BASE_SHORT="-b";const ARG_SEVERITY="--severity";const ARG_SEVERITY_SHORT="-s";const ARG_FORMAT="--format";const ARG_FORMAT_SHORT="-t";const ARG_FOLLOWLINKS="--followlinks";const ARG_FOLLOWLINKS_SHORT="-fl";const ARG_NOFOLLOWLINKS="--nofollowlinks";const ARG_NOFOLLOWLINKS_SHORT="-nfl";const ARG_SHOWRULES="--rules";const ARG_SHOWRULES_SHORT="-r";const ARG_SHOWRULESJSON="--rulesjson";const ARG_SHOWRULESJSON_SHORT="-rj";const ARG_SHOWRULESSONAR="--rulessonar";const ARG_SHOWRULESSONAR_SHORT="-rs";const ARG_SHOWRULES_INTERNAL="-rx";const ARG_OUTPATH="--outpath";const ARG_OUTPATH_SHORT="-o";const ARG_NO_OUT="--noout";const ARG_NO_OUT_SHORT="-no";const ARG_NOCOLOR="--nocolor";const ARG_NOCOLOR_SHORT="-nc";const ARG_NODEBUG="--nodebug";const ARG_NODEBUG_SHORT="-nd";const ARG_NOVERBOSE="--noverbose";const ARG_NOVERBOSE_SHORT="-nv";const ARG_NOEXTRA="--noextra";const ARG_NOEXTRA_SHORT="-ne";const ARG_GROUPS="--groups";const ARG_GROUPS_SHORT="-g";const ARG_GROUPS_EQ="--groups=";const ARG_GROUPS_EQ_SHORT="-g=";const ARG_MSGID="--msgid";const ARG_MSGID_SHORT="-id";const ARG_WATCH="--watch";const ARG_WATCH_SHORT="-w";const ARG_VERSION="--version";const ARG_VERSION_SHORT="-v";const ARG_JETLIST="--jetlist";const ARG_JETLIST_SHORT="-jl";const ARG_DEFLIST="--default";const ARG_DEFLIST_ALT="--deflist";const ARG_DEFLIST_SHORT="-def";const ARG_GROUPLIST="--grouplist";const ARG_GROUPLIST_SHORT="-gl";const ARG_XGROUPLIST="--xgrouplist";const ARG_XGROUPLIST_SHORT="-xgl";const ARG_DISLIST="--dislist";const ARG_DISLIST_SHORT="-dl";const ARG_DEPLIST="--deplist";const ARG_DEPLIST_SHORT="-dpl";const ARG_JETVER="--jetver";const ARG_JETVER_SHORT="-jv";const ARG_MAINT="--maintenance";const ARG_MAINT_SHORT="-mnt";const ARG_NAMESPACE_LIST="--nslist";const ARG_NAMESPACE_LIST_SHORT="-nsl";const ARG_PROFILES_LIST="--profiles";const ARG_PROFILES_LIST_SHORT="-prof";const ARG_AMDLIST="--amdlist";const ARG_AMDLIST_SHORT="-amd";const ARG_RLOLIST="--loadorder";const ARG_RLOLIST_SHORT="-rlo";const ARG_BETALIST="--betalist";const ARG_BETALIST_SHORT="-bl";const ARG_METAHIST="--metahist";const ARG_METAHIST_SHORT="-mh";const ARG_RC="--retcode";const ARG_RC_EQ="--retcode=";const ARG_RC_SHORT="-rc";const ARG_RC_EQ_SHORT="-rc=";const ARG_DRYRUN="--dryrun";const ARG_DRYRUN_SHORT="-dr";const ARG_DAC="--daconfig";const ARG_DAC_SHORT="-dac";const ARG_REG="--reg";const ARG_REG_SHORT="-reg";const ARG_HELP="--help";const ARG_HELP_SHORT="-h";const ARG_HELP_SHORT_S="-hs";const ARG_EXTRA="--extra";const ARG_EXTRA_SHORT="-e";const ARG_DEBUG="--debug";const ARG_DEBUG_SHORT="-d";const ARG_SCAFFOLD="--init";const ARG_SCAFFOLD_SHORT="-i";const ARG_SCAFFOLD_RULE="--initrule";const ARG_SCAFFOLD_RULE_SHORT="-ir";const ARG_MIGRATOR="--migrator";const ARG_MIGRATOR_SHORT="-mig";const ARG_UNIT_TEST="-ut";const ARG_OJET="--ojet";const ARG_OJET_SHORT="-ojet";const ARG_EXPERIMENTAL="--x";const ARG_EXPERIMENTAL_SHORT="-x";const MIGRATOR_LOG="migrator.log";const BAD_CONFIG_ARG="Invalid --config option";module.exports.checkArgs=function(nodeDeps,rtf,showHelp,showVersion,appCtx){var argLen,argOrig,arg,dontRun,temp,x,bArgsOk=true,bWantHelp=false,debugTitle,rc;rtf.jetauditdir=nodeDeps.process.argv[1];rtf.jetauditdir=nodeDeps.path.dirname(rtf.jetauditdir);_checkBaseOptions(rtf,appCtx.colors);if(!(rc=_checkMigrator(nodeDeps,rtf,appCtx))){return rc}if(rtf.debugSet){_dumpCmdLine()}if(rtf.migrator){return rc}argLen=process.argv.length;for(var i=2;i<argLen;i++){argOrig=process.argv[i];arg=argOrig.toLowerCase().trim();if(arg.length===0){continue}if(arg.charAt(0)!=="-"){if(!rtf.srcStack){rtf.srcStack=[]}arg=process.argv[i];arg=_handleQuotes(arg);arg=nodeDeps.path.normalize(arg);arg=nodeDeps.path.resolve(arg);rtf.srcStack.push(arg);if(rtf.debugMode||rtf.verboseMode){if(!debugTitle){appCtx.info("Command line files specified:");debugTitle=true}appCtx.info(" "+arg)}continue}if(arg.endsWith("?")){temp=arg.replace(/[\-\?]/g,"");rtf.manCheckL=temp;rtf.isManual=true;rtf.isManPage=true;break}if(_isBaseOption(arg)){continue}else if(arg===ARG_MSGID||arg===ARG_MSGID_SHORT){rtf.msgIdMode=rtf.msgIdModeSet=true}else if(arg===ARG_VERSION||arg===ARG_VERSION_SHORT){showVersion();dontRun=true}else if(arg===ARG_HELP||arg===ARG_HELP_SHORT||arg===ARG_HELP_SHORT_S){if(i+1<argLen){temp=process.argv[i+1];if(temp.charAt(0)==="-"){showHelp();dontRun=true;if(!_isBaseOption(temp))appCtx.error(`Unexpected '${temp}'`);break}i++;if(arg===ARG_HELP||arg===ARG_HELP_SHORT){rtf.manCheckL=temp}else{rtf.manCheckS=temp}rtf.isManual=true;if(rtf.st_configSet){break}}else{showHelp();dontRun=true;break}}else if(arg===ARG_JETLIST||arg===ARG_JETLIST_SHORT){rtf.jetverList=true;break}else if(arg.startsWith(ARG_DEFLIST)||arg.startsWith(ARG_DEFLIST_SHORT)||arg.startsWith(ARG_DEFLIST_ALT)){rtf.defList=true;break}else if(arg===ARG_NAMESPACE_LIST||arg===ARG_NAMESPACE_LIST_SHORT){rtf.cmdNSList=true;break}else if(arg===ARG_PROFILES_LIST||arg===ARG_PROFILES_LIST_SHORT){rtf.profList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,false);break}else if(arg===ARG_DISLIST||arg===ARG_DISLIST_SHORT){rtf.disList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_DEPLIST||arg===ARG_DEPLIST_SHORT){rtf.depList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_AMDLIST||arg===ARG_AMDLIST_SHORT){rtf.amdList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_RLOLIST||arg===ARG_RLOLIST_SHORT){rtf.rloList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_BETALIST||arg===ARG_BETALIST_SHORT){rtf.betaList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_GROUPLIST||arg===ARG_GROUPLIST_SHORT){rtf.groupList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true);break}else if(arg===ARG_XGROUPLIST||arg===ARG_XGROUPLIST_SHORT){rtf.xgroupList=true;rtf.cmdArg=checkNextArg(i,argLen,appCtx.error,true)}else if(arg===ARG_MAINT||arg===ARG_MAINT_SHORT){rtf.maintenance=true;break}else if(arg===ARG_METAHIST||arg===ARG_METAHIST_SHORT){rtf.cmdMetaHist=true;break}else if(arg===ARG_CONFIG||arg===ARG_CONFIG_SHORT){i++;if(i<argLen){arg=process.argv[i];rtf.configPath=nodeDeps.path.normalize(arg);rtf.configPath=nodeDeps.path.resolve(rtf.configPath);rtf.st_configSet=true;if(rtf.isManual||rtf.xgroupList){break}}else{appCtx.error(BAD_CONFIG_ARG);bArgsOk=false;bWantHelp=true}}else if(arg===ARG_BASE||arg===ARG_BASE_SHORT){i++;if(i<argLen){rtf.base=process.argv[i];if(rtf.base===MACROS.cwd||appCtx.utils.getFileType(rtf.base)==="d"){rtf.st_baseSet=true}else{appCtx.error(`'--base' ${rtf.base} is not a directory or the '$jafcwd' macro!!`);bArgsOk=false;bWantHelp=true}}else{appCtx.error("Invalid --base option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_SEVERITY||arg===ARG_SEVERITY_SHORT){i++;if(i<argLen){rtf.severitySet=true;rtf.cliSev=process.argv[i]}else{appCtx.error("Invalid --severity option");bArgsOk=false;bWantHelp=true}}else if(arg.startsWith(ARG_JETVER)||arg.startsWith(ARG_JETVER_SHORT)){let o=_checkArgValue(arg,i,appCtx,null,"JET version semver");if(!o.rc){return false}i=o.index;argOrig=o.value;if(arg=nodeDeps.jetver.validate(argOrig)){appCtx.error(arg);bArgsOk=false;break}arg=nodeDeps.jetver.getBestVersion(argOrig);if(!arg){appCtx.error(`${o.cmd}: '${argOrig}' is not a valid JET version`);bArgsOk=false;break}rtf.jetverSet=arg;if((rtf.verboseMode||rtf.debugMode)&&arg!==argOrig){appCtx.info(`[Info]: JET version '${argOrig}' was promoted to '${arg}'`)}}else if(arg===ARG_FORMAT||arg===ARG_FORMAT_SHORT){i++;if(i<argLen){argOrig=process.argv[i];arg=argOrig.toLowerCase();if(arg!==OUTFMT.JSON&&arg!==OUTFMT.PROSE&&arg!==OUTFMT.LINE){appCtx.error(`Invalid --format(-t) option '${argOrig}'`);bArgsOk=false;bWantHelp=true}else{rtf.outFormat=arg;rtf.st_formatSet=true}}else{appCtx.error("Invalid --format option");bArgsOk=false;bWantHelp=true}}else if(arg===ARG_OUTPATH||arg===ARG_OUTPATH_SHORT){i++;if(rtf.st_outPathSet){appCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{if(i<argLen){arg=process.argv[i];arg=nodeDeps.path.normalize(arg);rtf.outPath=nodeDeps.path.resolve(arg);rtf.st_outPathSet=true}else{appCtx.error("Invalid --outPath option");bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_NO_OUT||arg===ARG_NO_OUT_SHORT){if(rtf.st_outPathSet){appCtx.error("--outPath and --noout are mutually exclusive");bArgsOk=false;bWantHelp=true}else{rtf.outPath="$noout";rtf.st_outPathSet=true}}else if(arg===ARG_FOLLOWLINKS||arg===ARG_FOLLOWLINKS_SHORT){rtf.followLinks=rtf.followLinksSet=true}else if(arg===ARG_NOFOLLOWLINKS||arg===ARG_NOFOLLOWLINKS_SHORT){rtf.followLinks=false;rtf.followLinksSet=true}else if(arg.startsWith(ARG_GROUPS_EQ)||arg.startsWith(ARG_GROUPS_EQ_SHORT)){x=arg.indexOf("=");if(temp=_convertToArray(argOrig.substring(x+1))){rtf.groupsSet=temp}else{appCtx.error(`Invalid 'groups' declaration '${argOrig}`);bArgsOk=false;bWantHelp=true}}else if(arg===ARG_GROUPS||arg===ARG_GROUPS_SHORT){rtf.groupsSet=_checkGroups(process.argv,i+1);if(!rtf.groupsSet.groups||rtf.groupsSet.groups.length===0){appCtx.error(!rtf.groupsSet.groups?`groups missing after flag ${argOrig}`:`Invalid ${argOrig} specification`);bArgsOk=false;bWantHelp=true}i=rtf.groupsSet.next;rtf.groupsSet=rtf.groupsSet.groups}else if(arg.startsWith(ARG_RC_EQ)||arg.startsWith(ARG_RC_EQ_SHORT)||arg===ARG_RC||arg===ARG_RC_SHORT){arg=argOrig;if((x=arg.indexOf("="))>0){temp=argOrig.substring(0,x);arg=argOrig.substring(x+1)}else{temp=arg;i++;if(i<argLen){arg=process.argv[i]}else{appCtx.error(`missing arguments after '${argOrig}'`);bArgsOk=false;bWantHelp=true}}if(bArgsOk){temp=_processRetCode(temp,arg);if(temp||typeof temp==="number"){rtf.retCode=temp;rtf.st_retCodeSet=true}else{appCtx.error(`'${argOrig}' : ${arg.length?"'${arg}' is invalid":"missing argument?"}`);bArgsOk=false;bWantHelp=true}}}else if(arg===ARG_SHOWRULES||arg===ARG_SHOWRULES_SHORT){rtf.dumpRulesSet=true}else if(arg===ARG_SHOWRULESJSON||arg===ARG_SHOWRULESJSON_SHORT){rtf.dumpRulesJsonSet=true}else if(arg===ARG_SHOWRULESSONAR||arg===ARG_SHOWRULESSONAR_SHORT){rtf.dumpRulesSonarSet=true}else if(arg===ARG_SHOWRULES_INTERNAL){rtf.dumpRulesInternalSet=true}else if(arg===ARG_DRYRUN||arg===ARG_DRYRUN_SHORT){rtf.dryRunSet=rtf.dacSet=rtf.verboseMode=rtf.verboseSet=rtf.dumpRulesSet=true}else if(arg===ARG_DAC||arg===ARG_DAC_SHORT){rtf.dacSet=true}else if(arg===ARG_REG||arg===ARG_REG_SHORT){rtf.regListenerTypesSet=true}else if(arg===ARG_OJET||arg===ARG_OJET_SHORT){rtf.isOJETCLI=true}else if(arg.startsWith(ARG_EXPERIMENTAL)||arg.startsWith(ARG_EXPERIMENTAL_SHORT)){rtf.experimentalSet=true;if((x=arg.indexOf("="))>0){if((arg=argOrig.substring(x+1))==="tsx"){rtf.experimental=arg}}}else if(arg===ARG_WATCH||arg===ARG_WATCH_SHORT){if(rtf.experimentalSet){rtf.watchSet=true}}else if(arg===ARG_SCAFFOLD||arg===ARG_SCAFFOLD_SHORT){rtf.scaffoldSet=true}else if(arg===ARG_SCAFFOLD_RULE||arg===ARG_SCAFFOLD_RULE_SHORT){i++;if(i<argLen){rtf.scaffoldRuleSet=process.argv[i]}else{appCtx.error("Invalid --initrule argument: rule name missing ");bArgsOk=false;bWantHelp=true}}else if(arg==="-z"){}else{console.log("");appCtx.error(`Invalid command flag '${argOrig}' (Use ojaf -h to get help)`);bArgsOk=false;dontRun=true}}return dontRun?"end":bArgsOk};module.exports.displayCmdLineOptionsSet=function(rtf,appCtx){var s="\n** Command line options:\n";if(rtf.dryRunSet){s+=" - Dry run ON\n"}if(rtf.dacSet){s+=" - Display active config ON\n"}if(rtf.verboseMode){s+=" - Verbose mode ON\n"}if(rtf.debugMode){s+=" - Debug mode ON\n"}if(rtf.watchSet){s+=" - watch mode ON\n"}if(rtf.groupsSet){s+=` - Groups set to ${rtf.groupsSet}\n`}if(rtf.st_retCodeSet){s+=` - retCode set to ${rtf.retCode}\n`}if(rtf.colorSet){s+=` - Color mode ${rtf.colorMode}? "ON" : "OFF"}\n`}if(rtf.msgIdModeSet){s+=` - Show msg ID's(${rtf.msgIdModeSet}? "ON" : "OFF"}\n`}if(rtf.st_formatSet){s+=` - Output in ${rtf.outFormat.toUpperCase()} format\n`}if(rtf.st_configSet){s+=` - Config set to ${rtf.configPath}\n`}if(rtf.severitySet){s+=` - Severity set to '${rtf.severity}'\n`}if(rtf.st_outPathSet){s+=` - Outpath set to ${rtf.outPath==="$noout"?"'none'":rtf.outPath}\n`}if(rtf.st_baseSet){s+=` - Base set to ${rtf.base}\n`}if(rtf.jetverSet){s+=` - JET version set to ${rtf.jetverSet}\n`}if(rtf.followLinksSet){s+=` - following stylesheet links is ${rtf.followLinks?"ON":"OFF"}\n`}if(rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumRulesSonarSet){s+=" - Dump Rules ON\n"}appCtx.console(s+"\n")};module.exports.isCmdLineOptionsSet=function(rtf){return rtf.verboseMode||rtf.debugMode||rtf.colorSet||rtf.dumpRulesSet||rtf.dumpRulesJsonSet||rtf.dumpRulesSonarSet||rtf.dumpRulesInternalSet||rtf.msgIdModeSet||rtf.severitySet||rtf.watchSet||rtf.jetverSet||rtf.followLinksSet||rtf.dryRunSet||rtf.jetverList||rtf.cmdNSList||rtf.groupList||rtf.xgroupList||rtf.disList||rtf.cmdMetaHist||rtf.amdList||rtf.rloList||rtf.betaList||rtf.profList||rtf.maintenance||rtf.st_baseSet||rtf.st_formatSet||rtf.st_configSet||rtf.st_outPathSet||rtf.st_retCodeSet};function _checkBaseOptions(rtf,clr){var i,arg,argLen=process.argv.length;for(i=2;i<argLen;i++){arg=process.argv[i];if(arg.length===0||arg.charAt(0)!=="-"){continue}arg=arg.toLowerCase();if(arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT){rtf.verboseMode=rtf.verboseSet=true}else if(arg===ARG_NOEXTRA||arg===ARG_NOEXTRA_SHORT||arg===ARG_NOVERBOSE||arg===ARG_NOVERBOSE_SHORT){rtf.verboseMode=false;rtf.verboseSetVeto=true}else if(arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT){rtf.debugMode=rtf.debugSet=true;rtf.debugMode=rtf.debugSet=rtf.verboseMode=true}else if(arg===ARG_NODEBUG||arg===ARG_NODEBUG_SHORT){rtf.debugMode=false;rtf.debugSetVeto=true}else if(arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT){rtf.colorMode=false;rtf.colorSet=true;clr.enable(false)}else if(arg===ARG_UNIT_TEST){rtf.unitTest=true}}};function _isBaseOption(arg){return arg===ARG_EXTRA||arg===ARG_EXTRA_SHORT||arg===ARG_NOEXTRA||arg===ARG_NOEXTRA_SHORT||arg===ARG_NOVERBOSE||arg===ARG_NOVERBOSE_SHORT||arg===ARG_DEBUG||arg===ARG_DEBUG_SHORT||arg===ARG_NODEBUG||arg===ARG_NODEBUG_SHORT||arg===ARG_NOCOLOR||arg===ARG_NOCOLOR_SHORT||arg===ARG_UNIT_TEST};function _checkGroups(args,i){var arg,a,x,last,bound,groups;x=i;for(;;i++){if(i>=args.length||args[i].charAt(0)==="-"||last){break}arg=args[i].trim();if(x===i){bound=arg.startsWith("[")||arg.startsWith("(")}last=bound&&(arg.endsWith("]")||arg.endsWith(")"));arg=arg.replace(/[\[\(\)\]]/g,"").trim();if(!arg.length){break}arg=arg.replace(/,/g," ");arg=arg.replace(/ +(?= )/g,"").trim();if(!groups){groups=[]}a=arg.split(" ");groups=groups.concat(a)}return{next:bound?i:x,groups:groups}};function _checkMigrator(nodeDeps,rtf,appCtx){var i,arg,origArg,argLen=process.argv.length;for(i=2;i<argLen;i++){origArg=process.argv[i];if(origArg.length===0||origArg.charAt(0)!=="-"){continue}arg=origArg.toLowerCase();if(rtf.migrator=arg===ARG_MIGRATOR||arg===ARG_MIGRATOR_SHORT){break}}if(!rtf.migrator){return true}for(i=2;i<argLen;i++){origArg=process.argv[i];if(origArg.length===0||origArg.charAt(0)!=="-"){continue}arg=origArg.toLowerCase();if(arg===ARG_MIGRATOR||arg===ARG_MIGRATOR_SHORT){continue}else if(arg===ARG_DRYRUN||arg===ARG_DRYRUN_SHORT){rtf.dryRunSet=true}else if(arg===ARG_VERSION||arg===ARG_VERSION_SHORT){rtf.help=true}else if(arg.startsWith(ARG_OUTPATH)||arg.startsWith(ARG_OUTPATH_SHORT)){let o=_checkArgValue(arg,i,appCtx,null,"path");if(!o.rc){return false}i=o.index;rtf.outPath=_checkMigratorOutPath(o.value,nodeDeps,appCtx);if(!rtf.outPath){return false}}else if(arg.startsWith(ARG_JETVER)||arg.startsWith(ARG_JETVER_SHORT)){let o=_checkArgValue(arg,i,appCtx,null,"JET version semver argument");if(!o.rc){return false}i=o.index;origArg=o.value;if(arg=nodeDeps.jetver.validate(origArg)){appCtx.error(`${o.cmd}: ${arg}`);return false}arg=nodeDeps.jetver.getBestVersion(origArg);if(!arg){appCtx.error(`${o.cmd}: '${origArg}' is not a valid JET version`);return false}rtf.jetverSet=arg;if((rtf.verboseMode||rtf.debugMode)&&arg!==origArg){appCtx.info(`[Info]: JET version '${origArg}' was promoted to '${arg}'`)}}else if(arg.startsWith(ARG_CONFIG)||arg.startsWith(ARG_CONFIG_SHORT)){let o=_checkArgValue(arg,i,appCtx,null,"path");if(!o.rc){return false}i=o.index;arg=o.value;rtf.configPath=nodeDeps.path.resolve(nodeDeps.path.normalize(arg));let ft=appCtx.fsUtils.getFileTypeSync(rtf.configPath);if(ft==="f"){rtf.st_configSet=true}else if(ft==="d"){appCtx.error(`${o.cmd} : path is a directory (should be a file) - ${rtf.configPath}`);return false}else{appCtx.error(`${o.cmd} : config file not found - ${rtf.configPath}`);return false}}else if(_isBaseOption(arg)){continue}else if(rtf.migrator){appCtx.error(`Unexpected or unknown arg '${origArg}'`);return false}}if(!rtf.outPath){let path=nodeDeps.path;rtf.outPath=path.resolve(path.normalize(path.join(".",MIGRATOR_LOG)))}if(!rtf.configPath){rtf.configPath=null}return true};function _checkMigratorOutPath(arg,nodeDeps,appCtx){var path=nodeDeps.path;if(arg==="."||arg===".."||arg.endsWith("/")||arg.endsWith("\\")){arg=path.join(arg,MIGRATOR_LOG)}else if(!arg){arg=MIGRATOR_LOG}arg=path.resolve(path.normalize(arg));if(appCtx.fsUtils.getFileType(arg)==="d"){appCtx.error(`--outPath : is a dir, expected a filename - '${arg}'`);arg=null}return arg};function _checkArgValue(arg,i,appCtx,argType,what){var cmd,x;var retObj={value:null,origarg:arg,index:i,rc:true};if((x=arg.indexOf("="))>=0){cmd=retObj.cmd=arg.substring(0,x);arg=arg.substring(x+1)}else{cmd=retObj.cmd=arg;arg=++i<process.argv.length?process.argv[i]:null;retObj.index=i;if(arg&&arg.startsWith("-")){appCtx.error(`${cmd}: missing ${what} argument`);retObj.rc=false;return retObj}}if(!arg){appCtx.error(`Invalid ${cmd} option`);retObj.rc=false;return retObj}if(argType){let at=argType.charAt(0);if(at==="f"||at==="d"){let pt=appCtx.fsUtils.getFileType(arg);if(argType==="fe"||argType==="de"){if(pt==="f"||pt==="d"){if(at==="f"&&pt==="d"){appCtx.error(`${cmd} : expected a file (not a directory) '${arg}'`);retObj.rc=false}else if(at==="d"&&pt==="f"){appCtx.error(`${cmd} : expected a directory (not a file)) '${arg}'`);retObj.rc=false}}else{appCtx.error(`${cmd} : ${at==="d"?"directory":"file"} does not exist '${arg}'`);retObj.rc=false}}}}retObj.value=arg;return retObj};function _processRetCode(arg,val){var temp,ret;if(val==="auto"||val==="errors"){ret=val}else{temp=parseInt(val);if(!isNaN(temp)){ret=temp}else{if(temp=_convertToArray(val)){ret=temp}}}return ret};function checkNextArg(i,argLen,error,argType){var temp,lcTemp;if(i+1<argLen){temp=process.argv[i+1];lcTemp=temp.toLowerCase();if(temp.charAt(0)==="-"){if(!_isBaseOption(temp)&&lcTemp!==ARG_CONFIG&&lcTemp!==ARG_CONFIG_SHORT){error(`Unexpected '${temp}' - expected nothing, or a ${argType?"built-in pack prefix":"profile name"}`)}temp=undefined}}return temp};function _convertToArray(s){var a,n,i;if(s.charAt(0)==="["){s=s.substring(1);if(!s.length){return null}}if(s.charAt(s.length-1)==="]"){s=s.substring(0,s.length-1)}s=s.trim();if(!s.length){return null}s=s.replace(/\,/g," ");s=s.replace(/\s\s+/g," ").trim();a=s.split(" ");n=0;for(i=0;i<a.length;i++){if(a[i].length){n++}else{a=a.splice(i,1);i--}}return n?a:null};function _handleQuotes(s){return s.replace(/[\"\']/g,"")};function _dumpCmdLine(){var s="";for(var i=0;i<process.argv.length;i++){s+=`[${i}]: |${process.argv[i]}|\n`}console.log(s)};
|