@oracle/oraclejet-audit 14.1.4 → 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/AST_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 NT=require("./AstNodeTypes");const Scope=require("./Scope");const COMMON_DOC_METHODS={"getElementsByClassName":true,"getElementsByTagName":true,"getElementsByTagNameNS":true,"getElementById":true,"getElementsByName":true,"querySelector":true,"querySelectorAll":true,"createElement":true,"createElementNS":true};const LOC="loc";const RANGE="range";const PARENT="parent";var AST=function(data,file,fileType,nd,ecmaVer,comments,msgCtx,config){var opts={ecmaVersion:ecmaVer,comment:comments};if(fileType==="tsx"){opts.jsx=true}opts.loc=true;opts.range=true;opts.errorOnUnknownASTType=true;opts.project="D:/vsprojects/JetAuditDev/tsconfig/tsconfig.json";this._ast=nd.tsparse.parse(data,opts);this._data=data;this._file=file;this._fileType=fileType;this._tlib=null;this._scope=null;this._utils=null;this._program=null;this._isComments=comments;this._msgCtx=msgCtx;this._config=config;this._nd=nd};AST.prototype.walk=function(callback){try{this._walkAddParent(callback)}catch(e){console.log(`JAF internal TS/TSX WALK ERROR: ${e}`)}};AST.prototype.getAst=function(){return this._ast};AST.prototype.getFilePath=function(){return this._file};AST.prototype.getFileType=function(){return this._fileTpe};AST.prototype.getRawComments=function(){return this._ast.comments};AST.prototype.getNodeFromIndex=function(index){return _getNodeFromIndex2(this._ast,index)};function _getNodeFromIndex2(node,index){var body,n,i,ret=null;if(!node){return null}if(index===node.range[0]){return node}if(index<node.range[0]||index>node.range[1]){return null}if(node.body){body=node.body;if(Array.isArray(body)){for(i=0;i<body.length;i++){n=body[i];if(index<n.range[0]){ret=n}else{ret=_getNodeFromIndex2(n,index)}if(ret){if(ret===-1){ret=null}break}}}else{ret=_getNodeFromIndex2(body,index);if(ret){if(ret===-1){ret=null}}}}else{if(node.type==="IfStatement"){ret=_getNodeFromIndex2(node.consequent,index)}else{ret=node}}return ret};AST.prototype.getUtils=function(){if(!this._utils){this._utils={getBlock:this.getBlock.bind(this),getBody:this.getBody.bind(this),getProgram:this.getProgram.bind(this),getContainingFunctionName:this.getContainingFunctionName.bind(this),isFuncArg:this.isFuncArg.bind(this),getScopes:this._createVarScopes.bind(this),getNodeTypes:_getNodeTypes,isCommonDocApi:this.isCommonDocApi,parseDefine:this.parseDefine.bind(this),parseImport:this.parseImport.bind(this)}}return this._utils};function _getNodeTypes(){return NT};AST.prototype.getBlock=function(node){var block;if(!node){if(!this._program){node=this._ast;if(node.type!==NT.PROGRAM){node=null}this._program=node}else{node=this._program}block=node}else{while(node){if(node.type){if(node.type===NT.BLOCK_STMT||node.type===NT.PROGRAM){block=node;break}}node=node.parent}}return block};AST.prototype.getBody=function(node){var block=this.getBlock(node);return block?block.body:block};AST.prototype.getFunctionBody=function(node){var block;if(!node){if(!this._program){node=this._ast;if(node.type!==NT.PROGRAM){node=null}this._program=node}else{node=this._program}block=node}else{while(node){if(node.type){if(node.type===NT.FUNC_DECLARATION||node.type===NT.PROGRAM){block=node;break}}node=node.parent}}return block};AST.prototype.getProgram=function(){return this._ast.type===NT.PROGRAM?this._ast:null};AST.prototype.getContainingFunctionName=function(node){var body=this.getFunctionBody(node);return body&&body.id?body.id.name:undefined};AST.prototype._createVarScopes=function(){if(!this._scope){this._scope=new Scope(this._msgCtx,this._config,this._file,this._nd);this._scopeStacks=this._scope.build(this._ast);this._accessor=this._scope.getAccessor()}return this._accessor};AST.prototype.getData=function(){return this._data};AST.prototype.isFuncArg=function(node,varName){var args,arg,n,j,ret=false;var n=node;while(n.type&&n.type!==NT.FUNC_DECLARATION){n=n.parent;if(!n||!n.type){n=null;break}}if(n){args=n.params;for(j=0;j<args.length;j++){arg=args[j];if(arg.type===NT.IDENTIFIER){if(arg.name===varName){ret=true;break}}}}return ret};AST.prototype.isCommonDocApi=function(method){return COMMON_DOC_METHODS[method]};AST.prototype.parseDefine=function(node,obj){var modules,names,len,i;if(!node.arguments||node.arguments.length<2){return null}modules=node.arguments[0].elements;names=node.arguments[1].params;obj=obj||null;if(modules&&names&&modules.length){len=Math.min(modules.length,names.length);obj=obj?obj:{};for(i=0;i<len;i++){obj[names[i].name]=modules[i].value}}return obj};AST.prototype.parseImport=function(node,obj){var source,specifiers,spec,name,i;obj=obj||{};source=node.source&&node.source.value;if(node.specifiers){specifiers=node.specifiers;for(var i=0;i<specifiers.length;i++){spec=specifiers[i];if((spec.type===NT.IMPORT_DEF_SPECIFIER||spec.type===NT.IMPORT_SPECIFIER)&&spec.local){name=spec.local.name;obj[name]=source}}}return obj};AST.prototype._walkAddParent=function(fn){var stack=[this._ast],i,j,key,len,node,child,subchild;for(i=0;i<stack.length;i+=1){node=stack[i];if(node.type==="Line"||node.type==="EmptyStatement"){continue}fn(node);for(key in node){if(key!==PARENT){if(key===RANGE||key===LOC){continue}child=node[key];if(child instanceof Array){for(j=0,len=child.length;j<len;j+=1){subchild=child[j];if(subchild){subchild.parent=node;stack.push(subchild)}}}else if(child!=void 0&&typeof child.type==="string"){child.parent=node;stack.push(child)}}}}};module.exports=AST;
|
|
6
|
+
const NT=require("./AstNodeTypes");const Scope=require("./Scope");const COMMON_DOC_METHODS={"getElementsByClassName":true,"getElementsByTagName":true,"getElementsByTagNameNS":true,"getElementById":true,"getElementsByName":true,"querySelector":true,"querySelectorAll":true,"createElement":true,"createElementNS":true};const LOC="loc";const RANGE="range";const PARENT="parent";var AST=function(data,file,fileType,nd,ecmaVer,comments,msgCtx,config){var opts={ecmaVersion:ecmaVer,comment:comments};if(fileType==="tsx"){opts.jsx=true;opts.comment=true}opts.loc=true;opts.range=true;opts.errorOnUnknownASTType=true;opts.project="D:/vsprojects/JetAuditDev/tsconfig/tsconfig.json";this._ast=nd.tsparse.parse(data,opts);this._data=data;this._file=file;this._fileType=fileType;this._tlib=null;this._scope=null;this._utils=null;this._program=null;this._isComments=comments;this._msgCtx=msgCtx;this._config=config;this._nd=nd};AST.prototype.walk=function(callback){try{this._walkAddParent(callback)}catch(e){console.log(`JAF internal TS/TSX WALK ERROR: ${e}`)}};AST.prototype.getAst=function(){return this._ast};AST.prototype.getFilePath=function(){return this._file};AST.prototype.getFileType=function(){return this._fileTpe};AST.prototype.getRawComments=function(){return this._ast.comments};AST.prototype.getNodeFromIndex=function(index){return _getNodeFromIndex2(this._ast,index)};function _getNodeFromIndex2(node,index){var body,n,i,ret=null;if(!node){return null}if(index===node.range[0]){return node}if(index<node.range[0]||index>node.range[1]){return null}if(node.body){body=node.body;if(Array.isArray(body)){for(i=0;i<body.length;i++){n=body[i];if(index<n.range[0]){ret=n}else{ret=_getNodeFromIndex2(n,index)}if(ret){if(ret===-1){ret=null}break}}}else{ret=_getNodeFromIndex2(body,index);if(ret){if(ret===-1){ret=null}}}}else{if(node.type==="IfStatement"){ret=_getNodeFromIndex2(node.consequent,index)}else{ret=node}}return ret};AST.prototype.getUtils=function(){if(!this._utils){this._utils={getBlock:this.getBlock.bind(this),getBody:this.getBody.bind(this),getProgram:this.getProgram.bind(this),getContainingFunctionName:this.getContainingFunctionName.bind(this),isFuncArg:this.isFuncArg.bind(this),getScopes:this._createVarScopes.bind(this),getNodeTypes:_getNodeTypes,isCommonDocApi:this.isCommonDocApi,parseDefine:this.parseDefine.bind(this),parseImport:this.parseImport.bind(this)}}return this._utils};function _getNodeTypes(){return NT};AST.prototype.getBlock=function(node){var block;if(!node){if(!this._program){node=this._ast;if(node.type!==NT.PROGRAM){node=null}this._program=node}else{node=this._program}block=node}else{while(node){if(node.type){if(node.type===NT.BLOCK_STMT||node.type===NT.PROGRAM){block=node;break}}node=node.parent}}return block};AST.prototype.getBody=function(node){var block=this.getBlock(node);return block?block.body:block};AST.prototype.getFunctionBody=function(node){var block;if(!node){if(!this._program){node=this._ast;if(node.type!==NT.PROGRAM){node=null}this._program=node}else{node=this._program}block=node}else{while(node){if(node.type){if(node.type===NT.FUNC_DECLARATION||node.type===NT.PROGRAM){block=node;break}}node=node.parent}}return block};AST.prototype.getProgram=function(){return this._ast.type===NT.PROGRAM?this._ast:null};AST.prototype.getContainingFunctionName=function(node){var body=this.getFunctionBody(node);return body&&body.id?body.id.name:undefined};AST.prototype._createVarScopes=function(){if(!this._scope){this._scope=new Scope(this._msgCtx,this._config,this._file,this._nd);this._scopeStacks=this._scope.build(this._ast);this._accessor=this._scope.getAccessor()}return this._accessor};AST.prototype.getData=function(){return this._data};AST.prototype.isFuncArg=function(node,varName){var args,arg,n,j,ret=false;var n=node;while(n.type&&n.type!==NT.FUNC_DECLARATION){n=n.parent;if(!n||!n.type){n=null;break}}if(n){args=n.params;for(j=0;j<args.length;j++){arg=args[j];if(arg.type===NT.IDENTIFIER){if(arg.name===varName){ret=true;break}}}}return ret};AST.prototype.isCommonDocApi=function(method){return COMMON_DOC_METHODS[method]};AST.prototype.parseDefine=function(node,obj){var modules,names,len,i;if(!node.arguments||node.arguments.length<2){return null}modules=node.arguments[0].elements;names=node.arguments[1].params;obj=obj||null;if(modules&&names&&modules.length){len=Math.min(modules.length,names.length);obj=obj?obj:{};for(i=0;i<len;i++){obj[names[i].name]=modules[i].value}}return obj};AST.prototype.parseImport=function(node,obj){var source,specifiers,spec,name,i;obj=obj||{};source=node.source&&node.source.value;if(node.specifiers){specifiers=node.specifiers;for(var i=0;i<specifiers.length;i++){spec=specifiers[i];if((spec.type===NT.IMPORT_DEF_SPECIFIER||spec.type===NT.IMPORT_SPECIFIER)&&spec.local){name=spec.local.name;obj[name]=source}}}return obj};AST.prototype._walkAddParent=function(fn){var stack=[this._ast],i,j,key,len,node,child,subchild;for(i=0;i<stack.length;i+=1){node=stack[i];if(node.type==="Line"||node.type==="EmptyStatement"){continue}fn(node);for(key in node){if(key!==PARENT){if(key===RANGE||key===LOC){continue}child=node[key];if(child instanceof Array){for(j=0,len=child.length;j<len;j+=1){subchild=child[j];if(subchild){subchild.parent=node;stack.push(subchild)}}}else if(child!=void 0&&typeof child.type==="string"){child.parent=node;stack.push(child)}}}}};module.exports=AST;
|
package/lib/Cli.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 _cmdLine=require("./cmdline");const SUP="\xB9";const ENV_JAF_COLOR="JAF_COLOR";const ENV_JAF_COLOUR="JAF_COLOUR";var Cli=function(nd,cwd,appCtx){this._nd=nd;this._cwd=cwd;this._appCtx=appCtx;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._rtf=null;this._clr=appCtx.colors;this._manual=null;this._groupList=null};Cli.prototype.checkArgs=function(rtf,fnShowVersion){this._rtf=rtf;this._showVersion=fnShowVersion;return _cmdLine.checkArgs(this._nd,rtf,this.showHelp.bind(this),fnShowVersion,this._appCtx)};Cli.prototype.checkImmedCmds=function(rtf){var ret=1;if(rtf.cmdMetaHist){let metahist=require("./metahist");metahist.show(this._nd,this._fsUtils)}else if(rtf.isManual){if(!this._manual){this._manual=require("./manual")}if(this._manual.showBuiltinMsgHelp(this._nd,rtf.manCheckL,rtf.isManPage,this._appCtx)){return 1}ret=-1}else if(rtf.jetverList){this._showJetVerList()}else if(rtf.defList){let defList=require("./deflist");defList.showList(this._nd,this._appCtx.colors)}else if(rtf.cmdNSList){let nslist=require("./nslist");nslist.showNamespaces()}else if(rtf.groupList){if(!this._grouplist){this._grouplist=require("./grouplist")}this._grouplist.showBuiltinGroups(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.disList){let dislist=require("./dislist");dislist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.depList){let deplist=require("./deplist");deplist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.profList){let proflist=require("./proflist");proflist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.amdList){let amdlist=require("./amdlist");amdlist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.rloList){let rlolist=require("./rlolist");rlolist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.betaList){let betalist=require("./betalist");betalist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.scaffoldRuleSet){return this._nd.scaffoldRule.genRule(this._cwd,rtf.scaffoldRuleSet,this._nd,this._fsUtils)?1:-1}else{ret=0}return ret};Cli.prototype.checkEnvColor=function(){var env,theme;if((env=process.env[ENV_JAF_COLOR])||(env=process.env[ENV_JAF_COLOUR])){env=env.replace(/["']/g,"").toLowerCase().charAt(0);if(env==="y"||env==="t"||env==="d"||env==="l"){theme=env==="l"?"light":"dark"}else{theme="no"}}return theme};Cli.prototype.showExternalGroups=function(ruleSets){if(!this._grouplist){this._grouplist=require("./grouplist")}this._grouplist.showExternalGroups(ruleSets,this._rtf.cmdArg,this._nd,this._appCtx)};Cli.prototype.displayCmdLineOptionsSet=function(){if(this._rtf.verboseMode&&_cmdLine.isCmdLineOptionsSet(this._rtf)){_cmdLine.displayCmdLineOptionsSet(this._rtf,this._appCtx)}};Cli.prototype.showHelp=function(){let help=require("./help");help(this._showVersion,this._appCtx)};Cli.prototype.manualCheckForNonJet=function(rules){if(this._rtf.isManual){if(!this._manual){this._manual=require("./manual")}return this._manual.showExternalMsgHelp(rules,this._rtf.manCheckL,this._rtf.manCheckS,this._nd,this._appCtx)}return false};Cli.prototype._showJetVerList=function(){let keys,ver,a,built,isDefVer,list=this._nd.jetver.getVersions(),indent=" \u2022 ";let clr=this._clr;let sup=clr.BRIGHTYELLOW(SUP);keys=Object.keys(list).sort(function(a,b){var va=a.split(".");var vb=b.split(".");va.forEach(function(v,i,a){a[i]=parseInt(v)});vb.forEach(function(v,i,a){a[i]=parseInt(v)});if(va[0]>vb[0]){return 1}if(va[0]<vb[0]){return-1}if(va[1]>vb[1]){return 1}if(va[1]<vb[1]){return-1}if(va[2]>vb[2]){return 1}if(va[2]<vb[2]){return-1}return 0}).reverse();console.log("\n"+" JET versions supported:");const DEFAULTS=require("./defaults");keys.forEach(function(verName){ver=list[verName];a=verName.split(".");a.forEach(function(s,x){a[x]=parseInt(s)});if(a[0]<10){verName=" "+verName}built=" ("+ver.date+" "+ver.time+")";if(isDefVer=verName===DEFAULTS.JETVER){let def=" Default";built+=clr.BRIGHTYELLOW(def)+sup}verName=isDefVer?clr.BRIGHTYELLOW(verName):clr.CYAN(verName);console.log(indent+verName+built)});let footnote=clr.BRIGHTYELLOW("Default config 'jetVer' value if not specified.");console.log(`\n${sup} ${footnote}`)};Cli.prototype.dumpRules=function(rules,outPath){var ret=false;if(!(this._rtf.dumpRulesSet||this._rtf.dumpRulesJsonSet||this._rtf.dumpRulesSonarSet||this._rtf.dumpRulesInternalSet)){return ret}let ro;if(this._rtf.dumpRulesJsonSet){ro=rules.getRulesJson(true)}else if(this._rtf.dumpRulesSonarSet){ro=rules.getRulesSonar()}else{ro=rules.getRulesProse(this._rtf.dumpRulesInternalSet)}if(ro){if(outPath){let OutFile=require("../lib/outfile");OutFile.
|
|
6
|
+
const _cmdLine=require("./cmdline");const SUP="\xB9";const ENV_JAF_COLOR="JAF_COLOR";const ENV_JAF_COLOUR="JAF_COLOUR";var Cli=function(nd,cwd,appCtx){this._nd=nd;this._cwd=cwd;this._appCtx=appCtx;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._rtf=null;this._clr=appCtx.colors;this._manual=null;this._groupList=null};Cli.prototype.checkArgs=function(rtf,fnShowVersion){this._rtf=rtf;this._showVersion=fnShowVersion;return _cmdLine.checkArgs(this._nd,rtf,this.showHelp.bind(this),fnShowVersion,this._appCtx)};Cli.prototype.checkImmedCmds=function(rtf,JafVersion,fnShowVersion,fnOpenWriter){var ret=1;if(rtf.migrator){let mig=require("./migrator");mig.run(this._cwd,rtf,this._appCtx,fnOpenWriter,JafVersion,fnShowVersion)}else if(rtf.cmdMetaHist){let metahist=require("./metahist");metahist.show(this._nd,this._fsUtils)}else if(rtf.isManual){if(!this._manual){this._manual=require("./manual")}if(this._manual.showBuiltinMsgHelp(this._nd,rtf.manCheckL,rtf.isManPage,this._appCtx)){return 1}ret=-1}else if(rtf.jetverList){this._showJetVerList()}else if(rtf.defList){let defList=require("./deflist");defList.showList(this._nd,this._appCtx.colors)}else if(rtf.cmdNSList){let nslist=require("./nslist");nslist.showNamespaces()}else if(rtf.groupList){if(!this._grouplist){this._grouplist=require("./grouplist")}this._grouplist.showBuiltinGroups(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.disList){let dislist=require("./dislist");dislist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.depList){let deplist=require("./deplist");deplist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.profList){let proflist=require("./proflist");proflist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.amdList){let amdlist=require("./amdlist");amdlist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.rloList){let rlolist=require("./rlolist");rlolist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.betaList){let betalist=require("./betalist");betalist.show(this._nd,rtf.cmdArg,this._appCtx)}else if(rtf.scaffoldRuleSet){return this._nd.scaffoldRule.genRule(this._cwd,rtf.scaffoldRuleSet,this._nd,this._fsUtils)?1:-1}else{ret=0}return ret};Cli.prototype.checkEnvColor=function(){var env,theme;if((env=process.env[ENV_JAF_COLOR])||(env=process.env[ENV_JAF_COLOUR])){env=env.replace(/["']/g,"").toLowerCase().charAt(0);if(env==="y"||env==="t"||env==="d"||env==="l"){theme=env==="l"?"light":"dark"}else{theme="no"}}return theme};Cli.prototype.showExternalGroups=function(ruleSets){if(!this._grouplist){this._grouplist=require("./grouplist")}this._grouplist.showExternalGroups(ruleSets,this._rtf.cmdArg,this._nd,this._appCtx)};Cli.prototype.displayCmdLineOptionsSet=function(){if(this._rtf.verboseMode&&_cmdLine.isCmdLineOptionsSet(this._rtf)){_cmdLine.displayCmdLineOptionsSet(this._rtf,this._appCtx)}};Cli.prototype.showHelp=function(){let help=require("./help");help(this._showVersion,this._appCtx)};Cli.prototype.manualCheckForNonJet=function(rules){if(this._rtf.isManual){if(!this._manual){this._manual=require("./manual")}return this._manual.showExternalMsgHelp(rules,this._rtf.manCheckL,this._rtf.manCheckS,this._nd,this._appCtx)}return false};Cli.prototype.dumpMaintenance=function(metaLib){if(this._rtf.maintenance){if(!this._maint){this._maint=require("./maint")}return this._maint.showMaintenance(metaLib,this._appCtx)}return false};Cli.prototype._showJetVerList=function(){let keys,ver,a,built,isDefVer,list=this._nd.jetver.getVersions(),indent=" \u2022 ";let clr=this._clr;let sup=clr.BRIGHTYELLOW(SUP);keys=Object.keys(list).sort(function(a,b){var va=a.split(".");var vb=b.split(".");va.forEach(function(v,i,a){a[i]=parseInt(v)});vb.forEach(function(v,i,a){a[i]=parseInt(v)});if(va[0]>vb[0]){return 1}if(va[0]<vb[0]){return-1}if(va[1]>vb[1]){return 1}if(va[1]<vb[1]){return-1}if(va[2]>vb[2]){return 1}if(va[2]<vb[2]){return-1}return 0}).reverse();console.log("\n"+" JET versions supported:");const DEFAULTS=require("./defaults");keys.forEach(function(verName){ver=list[verName];a=verName.split(".");a.forEach(function(s,x){a[x]=parseInt(s)});if(a[0]<10){verName=" "+verName}built=" ("+ver.date+" "+ver.time+")";if(isDefVer=verName===DEFAULTS.JETVER){let def=" Default";built+=clr.BRIGHTYELLOW(def)+sup}verName=isDefVer?clr.BRIGHTYELLOW(verName):clr.CYAN(verName);console.log(indent+verName+built)});let footnote=clr.BRIGHTYELLOW("Default config 'jetVer' value if not specified.");console.log(`\n${sup} ${footnote}`)};Cli.prototype.dumpRules=function(rules,outPath){var ret=false;if(!(this._rtf.dumpRulesSet||this._rtf.dumpRulesJsonSet||this._rtf.dumpRulesSonarSet||this._rtf.dumpRulesInternalSet)){return ret}let ro;if(this._rtf.dumpRulesJsonSet){ro=rules.getRulesJson(true)}else if(this._rtf.dumpRulesSonarSet){ro=rules.getRulesSonar()}else{ro=rules.getRulesProse(this._rtf.dumpRulesInternalSet)}if(ro){if(outPath){let OutFile=require("../lib/outfile");OutFile.writeFileSync(this._nd,outPath,ro)}else{if(this._rtf.dumpRulesJsonSet){console.log(JSON.stringify(ro,null,3))}else{console.log(ro)}}ret=true}return ret};Cli.prototype.displayFinalStats=function(stats,severity,fnConsole,fnInfo,unitTest,useStderr,elapsed){var CliStats=require("./cliStats");var cliStats=new CliStats(this._nd,stats,severity,fnConsole,fnInfo,unitTest,this._appCtx,useStderr);cliStats.displayStatsAndHisto(elapsed);cliStats.displayErrorsAndAsserts()};module.exports=Cli;
|
package/lib/Components.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";const COMPONENT_JSON="component.json";const PROPERTIES="properties";const PROP_SLOTS="slots";const PROP_DYNAMIC_SLOTS="dynamicSlots";const PROP_PROPS="props";const PROP_EVENTS="events";const PROP_STYLECLASSES="styleClasses";const PROP_IMPLEMENTS="implements";const PROP_REQUIRED="required";const PROP_FOLDER="folder";const PROP_VERSION="version";const PROP_UNSUP_THEME="unsupTheme";const PROP_STATUS="status";const PROP_SUBCOMPONENT_TYPE="subcomponentType";const PROP_TYPE="type";const PROP_PACK="pack";const PROPERTY_VALUE="propertyValue";const PROPERTY_TYPE="propertyType";const PACK_PRIVATE="packPrivate";const DEPRECATED="deprecated";const MAINTENANCE="maintenance";const SUPERSEDES="supersedes";const DYNAMIC_FORM_ELEM="DynamicFormElement";const DYNAMIC_TABLE_ELEM="DynamicTableElement";const VB_FRAGMENT_ELEM="VbFragmentElement";const OJ_C="oj-c";const DOT=".";const DASH_CHANGED="-changed";const REGXPR=/string|number|object|array|boolean|[\|.<>]/gi;function Components(nd,runMode,cwd,compSvcs,urlBase,urls,filePaths,metaLib,ojcPack,jetCore,runOpts,msgCtx,appCtx){this._nd=nd;this._tagLookup={};this._jetTagLookup={};this._styleLookup={};this._ignored={};this._maintenance=null;this._supersedes=null;this._meta={};this._path=null;this._reqAttrs=null;this._metaLib=metaLib;this._ojcPack=ojcPack;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._compSvcs=compSvcs;this._isAMD=runMode==="amd";this._cwd=cwd;this._error=msgCtx.error;this._warn=msgCtx.warn;this._debug=msgCtx.debug;this._info=msgCtx.info;this._msg=msgCtx.msg;this._console=msgCtx.console;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._count=0;this._isOk=true;this._runOpts=runOpts;this._init(urlBase,urls,filePaths,jetCore)};Components.prototype.isTag=function(tagName){return!!this._tagLookup[_removeChevrons(tagName)]};Components.prototype.isJetTag=function(tagName){return!!this._jetTagLookup[_removeChevrons(tagName)]};Components.prototype.isKnownTag=function(tagName){tagName=_removeChevrons(tagName);return this._jetTagLookup[tagName]||this._tagLookup[tagName]};Components.prototype.isTagAttr=function(tagName,attrName){return this.isTagProp(tagName,attrName)||this.isJetTagProp(tagName,attrName)};Components.prototype.isJetTagAttr=function(tagName,attrName){return this.isJetTagProp(tagName,attrName)};Components.prototype.isTagDeprecated=function(tag){var comp,stats,status,ret=null;tag=_removeChevrons(tag);if(comp=this._tagLookup[tag]||this._jetTagLookup[tag]){if(stats=comp.status){for(status of stats){if(status.type===DEPRECATED&&!status.hasOwnProperty("target")){ret=status;break}}}}return ret};Components.prototype.isTagAttrDeprecated=function(tagName,attrName){var prop,status,stats,o,ret=null;if((prop=this.getAnyTagProp(tagName,attrName))&&(stats=prop.status)){ret=[];for(status of stats){if(status.type===DEPRECATED){o={type:DEPRECATED};if(status.hasOwnProperty("target")){o.target=status.target}if(status.hasOwnProperty("description")){o.description=status.description}if(status.hasOwnProperty("since")){o.since=status.since}if(status.hasOwnProperty("value")){o.value=status.value}ret.push(o)}}ret=ret.length?ret:null}return ret};Components.prototype.isTagEventDeprecated=function(tagName,event){var prop,status=null;if(prop=this.getAnyTagEvent(tagName,event)){status=prop.status}return status};Components.prototype.isTagAttrTranslatable=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.translatable};Components.prototype.isTagAttrReadOnly=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.readonly};Components.prototype.isTagProp=function(tagName,propName){return!!this.getTagProp(tagName,propName)};Components.prototype.isJetTagProp=function(tagName,propName){return!!this.getJetTagProp(tagName,propName)};Components.prototype.getTagProp=function(tagName,propName){var ret;if(this.isTag(tagName)){ret=this._getTagProp(tagName,propName,false)}return ret?ret:null};Components.prototype.getJetTagProp=function(tagName,propName){var ret;if(this.isJetTag(tagName)){ret=this._getTagProp(tagName,propName,true)}return ret?ret:null};Components.prototype.getAnyTagProp=function(tagName,propName){return this._getTagProp(tagName,propName,true)||this._getTagProp(tagName,propName,false)};Components.prototype._getTagProp=function(tagName,propName,isOJC){var tag,props,list;list=isOJC?this._jetTagLookup:this._tagLookup;tag=list[_removeChevrons(tagName)];props=tag?tag[PROP_PROPS]:null;if(props){propName=propName.charAt(0)===":"?propName.substring(1):propName;propName=_deCamelCaseProp(propName)}return props?props[propName]:null};Components.prototype.getTagPropType=function(tagName,propName){var prop,ret;if(prop=this.getTagProp(tagName,propName)){ret=prop?prop.type:undefined}return ret};Components.prototype.getAnyTagEvent=function(tag,event){return this._getTagEvent(tag,event,true)||this._getTagEvent(tag,event,false)};Components.prototype._getTagEvent=function(tagName,eventName,isOJC){var tag,events,event,list;list=isOJC?this._jetTagLookup:this._tagLookup;tag=list[_removeChevrons(tagName)];if(events=tag?tag[PROP_EVENTS]:null){if(!(event=events[eventName])){if(eventName.endsWith(DASH_CHANGED)){eventName=eventName.substring(0,eventName.length-DASH_CHANGED.length);event=events[eventName.replace(DASH_CHANGED,"")]}}}return event?event.status:null};Components.prototype.getUserComponentMetadata=function(tag){return this._meta[tag]||null};Components.prototype.getUserComponentPropMetadata=function(tagName,propName){var comp,sofar,props;tagName=_removeChevrons(tagName);if(!(comp=this._meta[tagName])||!(props=comp.properties)){return null}let subprops=propName.split(DOT);if(subprops.length===1){return props[propName]||null}sofar=comp;let nextprop,i;for(i=0;i<subprops.length;i++){nextprop=subprops[i];if(sofar.hasOwnProperty(PROPERTIES)){sofar=sofar.properties[nextprop]||null;if(!sofar){break}}else{sofar=null;break}}return sofar};Components.prototype.getTagMetadata=function(tag){tag=_removeChevrons(tag);return this._tagLookup[tag]||this._jetTagLookup[tag]};Components.prototype.getJetTag=function(tag){var meta;return(meta=this._jetTagLookup[tag])?meta:null};Components.prototype.isTagEvent=function(tagName,eventName){var propName,o,b;o=this._tagLookup[tagName]||this._jetTagLookup[tagName];if(o){if(eventName.startsWith("on-")){b=o.events&&o.events[eventName];if(b)return b;if(o.implements&&(o.implements.includes(DYNAMIC_FORM_ELEM)||o.implements.includes(DYNAMIC_TABLE_ELEM)||o.implements.includes(VB_FRAGMENT_ELEM))){return true}if(eventName.endsWith(DASH_CHANGED)){if(o.props){propName=eventName.replace(DASH_CHANGED,"").substring(3);return!!o.props[propName]}}}}return false};Components.prototype.isTagStyle=function(tag,style){var meta;if(meta=this._tagLookup[tag]||this._jetTagLookup[tag]){let styles,sc;if(styles=meta.styleClasses){if(sc=styles[style]){return true}}}return false};Components.prototype.isStyle=function(style){return!!this._styleLookup[style]};Components.prototype.getStyleMetadata=function(style){var tag,styles,sc,ret=null;if(tag=this._styleLookup[style]){if(styles=this._tagLookup[tag].styleClasses){if(sc=styles[style]){ret={tag:tag,meta:sc}}}}return ret};Components.prototype.getStyleSelector=function(style){var sm=this.getStyleMetadata(style);return sm&&sm.meta?sm.meta.styleSelector:null};Components.prototype.hasTagSlotName=function(tagName,slotName){var o=this._tagLookup[tagName]||this._jetTagLookup[tagName];return!!(o&&o.slots&&o.slots[slotName])};Components.prototype.getPreferredSlotContent=function(tag,slotName,impls){var o,slot,prefContent=null,comps=null,content;if(this._utils.hasAnyProps(impls)){if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){if(o.slots){if(slot=o.slots[slotName]){if(prefContent=slot.preferredContent){prefContent.forEach(impl=>{if(content=impls[impl]){if(!comps){comps=[]}comps.push(...content)}})}}}}}return prefContent||comps?{interfaces:prefContent,components:comps}:null};Components.prototype.getTagSlotMetadata=function(tag,slot){var o,ret;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){if(o.slots){if(slot=o.slots[slot]){ret=slot}}}return ret};Components.prototype.hasTagDynamicSlot=function(tag){var o,ret=false;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){if(o.hasOwnProperty(PROP_DYNAMIC_SLOTS)){ret=true}}return ret};Components.prototype.hasTagAttrValues=function(tagName,attrName){var prop,ret=false;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){ret=!!prop.enumValues}return ret};Components.prototype.isTagAttrValue=function(tagName,attrName,value){var prop,ret;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){if(prop&&prop.enumValues){ret=prop.enumValues.indexOf(value)>=0}}return ret};Components.prototype.isTagAttrEnumDeprecated=function(tag,attr,val){var prop,stats,status,ret=null;if(prop=this.getAnyTagProp(tag,attr)){if(stats=prop.status){for(status of stats){if(status.type===DEPRECATED&&status.target===PROPERTY_VALUE){if(status.value&&status.value.includes(val)){ret={type:DEPRECATED};if(status.hasOwnProperty("target")){ret.target=status.target}if(status.hasOwnProperty("description")){ret.description=status.description}if(status.hasOwnProperty("since")){ret.since=status.since}if(status.hasOwnProperty("value")){ret.value=status.value}break}}}}}return ret};Components.prototype.isTagSupportedInTheme=function(tag,theme){var o,unsup,ret=true;if(o=this.getTagMetadata(tag)){unsup=o[PROP_UNSUP_THEME];if(unsup){ret=!unsup.includes(theme)}}return ret};Components.prototype.isAttrSupportedInTheme=function(tag,attr,theme){var prop,unsup,ret=true;if(prop=this.getAnyTagProp(tag,attr)){if(unsup=prop[PROP_UNSUP_THEME]){ret=!unsup.includes(theme)}}return ret};Components.prototype.isTagPackPrivate=function(tag){var o,ret;tag=_removeChevrons(tag);if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o[PROP_SUBCOMPONENT_TYPE]===PACK_PRIVATE}return ret};Components.prototype.getSubcomponentType=function(tag){var o,ret;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o[PROP_SUBCOMPONENT_TYPE]}return ret||null};Components.prototype.getRequiredProps=function(tagName){var tag,props,prop,propName,obj,ret=null;tagName=_removeChevrons(tagName);if(this._reqAttrs){let r=this._reqAttrs[tagName];if(r){return typeof r==="boolean"?null:r}}tag=this._tagLookup[tagName]||this._jetTagLookup[tagName];if(tag&&tag.props){if(!this._reqAttrs){this._reqAttrs={}}if(!this._reqAttrs[tagName]){this._reqAttrs[tagName]=true}props=tag.props;for(propName in props){prop=props[propName];if(prop.required){if(!obj){obj=[]}obj.push(_deCamelCaseProp(propName))}}}if(obj&&obj.length){let i,j,p;for(i=0;i<obj.length;i++){if(p=obj[i]){p+=".";for(j=i+1;j<obj.length;j++){if(obj[j].startsWith(p)){obj.splice(i,1);i--;break}}}}this._reqAttrs[tagName]=obj;ret=obj}return ret};Components.prototype.getRequiredAttrs=function(tagName){return this.getRequiredProps(tagName)};Components.prototype.getInterfaces=function(tag){var o,ret;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o.implements}return ret||null};Components.prototype.getUserNames=function(){var name,a=[];for(name in this._tagLookup){a.push({name:name,version:this._tagLookup[name].version})}return a};Components.prototype.getJetNames=function(){var name,a=[];for(name in this._jetTagLookup){a.push({name:name,version:this._jetTagLookup[name].version})}return a};Components.prototype.getCount=function(){return this._count};Components.prototype.isTagMaintenance=function(tag){return this._maintenance&&this._maintenance.has(tag)};Components.prototype.isTagSupersedes=function(tag){return this._supersedes&&this._supersedes.has(tag)};Components.prototype.getTagMaintenanceStatus=function(tag){return this.getTagStatus(tag,MAINTENANCE)};Components.prototype.getTagSupersedesStatus=function(tag){return this.getTagStatus(tag,SUPERSEDES)};Components.prototype.getTagStatus=function(tag,type){var ret=null;if(type===SUPERSEDES&&this.isTagSupersedes(tag)||type===MAINTENANCE&&this.isTagMaintenance(tag)||type===DEPRECATED&&this.isTagDeprecated(tag)){let comp,arStat,i;if(comp=this._tagLookup[tag]||this._jetTagLookup[tag]){arStat=comp.status;for(i=0;i<arStat.length;i++){if(arStat[i].type===type){ret=arStat[i];break}}}}return ret};Components.prototype.isRuleIgnored=function(compName,ruleName){var ret,ar;if(ar=this._ignored[compName]){ret=ar.includes(ruleName)}return!!ret};Components.prototype.isOk=function(){return this._isOk};Components.prototype._init=function(base,urls,filePaths,jetCore){if(this._isAMD){this._processJetCorePack();return}if(base){base=base.trim();if(base.charAt(base.length-1)!=="/"){base=base+"/"}}else{base=""}this._processFilePaths(filePaths);this._processUrls(base,urls);this._processJetCorePack();this._createStyleLookup();this._processJetCore(jetCore)};Components.prototype._processFilePaths=function(filePaths){var obj,compEntry,fpath,i,j;if(!filePaths){return}this._console("\nPre-processing user-declared web component metadata...");for(i=0;i<filePaths.length;i++){compEntry=filePaths[i];var dirStack=this._nd.glob.sync(compEntry);for(j=0;j<dirStack.length;j++){fpath=dirStack[j];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg="-".repeat(70)+"\n"+(this._runOpts.isDryRun?"* ":"")+"processing component path '"+fpath+"' ...";if(this._runOpts.isDryRun){console.log(msg)}else{this._debug(msg)}}if(fpath.toLowerCase().endsWith(".zip")){obj=this._compSvcs._extractComponentJsonFromZip(fpath);if(obj.obj){this.processComponentJson(obj.obj,fpath,true)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+fpath)}else if(obj.error){this._error("Failed to unzip '"+fpath+"'")}continue}if(this._isComponentJsonPath(fpath)){if(obj=this._readComponentJson(fpath)){if(obj.type&&obj.type==="pack"){continue}this.processComponentJson(obj,this._nd.path.dirname(fpath),true)}continue}this._recurse(fpath)}}if(this._isDebug){this._debug("-".repeat(70))}};Components.prototype._recurse=function(fpath){var dirs,inFile,obj,i;try{dirs=this._nd.fs.readdirSync(fpath);if(this._isDebug){this._debug(` processing ${fpath} ${dirs.length} component dirs ...`)}for(i=0;i<dirs.length;i++){inFile=dirs[i];if(inFile===COMPONENT_JSON){inFile=this._nd.path.join(fpath,COMPONENT_JSON);if(this._isDebug){this._debug(" processing "+inFile+"...")}obj=this._readComponentJson(inFile);if(obj){if(!obj.type||obj.type==="composite"){this.processComponentJson(obj,fpath,true)}}else{return}}var curPath=this._nd.path.join(fpath,inFile);if(this._fsUtils.getFileType(curPath)==="d"){this._recurse(curPath)}}}catch(e){this._error("Component check failed - "+e);this._isOk=false}};Components.prototype._processUrls=function(base,urls){var url,i;if(!urls){return}for(i=0;i<urls.length;i++){url=urls[i];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg;msg="-".repeat(70)+"\nprocessing URL '"+url+"'";if(this._runOpts.isDryRun){console.log(msg);continue}else{this._debug(msg)}}if(_isRelativeUrl(url)){url=base+url;if(_isRelativeUrl(url)){this._error("component URL incomplete - '"+url+"'");continue}}this._processUrl(url)}};Components.prototype._processUrl=function(url){var resp,obj,rc,tempFile,tmp;try{resp=this._compSvcs.loadUrl(url);if(resp.eCode==="ETIMEDOUT"){this._error("config.componentUrls - request timed-out for '"+url+"'");this._isOk=false;return}try{if(resp.type==="json"){if(resp.body){obj=JSON.parse(resp.body);if(!this.processComponentJson(obj,url,false)){this._isOk=false}}else{this._error("Server responded with "+resp.statusCode+" URL: '"+url+"'")}}else if(resp.type=="zip"){rc=this._compSvcs.writeZipBufferToFile(resp.body);if(typeof rc==="boolean"&&rc){tempFile=this._compSvcs.getLastZipFilePath();obj=this._compSvcs.extractComponentJsonFromZip(tempFile);if(obj.obj){this.processComponentJson(obj.obj,url,true)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+url)}else if(obj.error){this._error("Failed to unzip '"+url+"'")}this._compSvcs.deleteZipFile(tempFile)}else{this._error("Failed to create local temp zip file from URL '"+url+"' : rc.message");this._isOk=false}}else{tmp=typeof resp.type==="string"?resp.type:"?";this._error("Server responded with unexpected data ('"+tmp+"') : '"+url+"'");this._isOk=false}}catch(e){this._error("Invalid JSON - URL '"+url+"' : "+e);this._isOk=false}}catch(e1){this._error("URL access failed "+(e1.message.includes("ENOTFOUND")?"(NOT FOUND)":"")+" - URL '"+url+"'");this._isOk=false}};Components.prototype._processJetCorePack=function(){var comps,comp;if(comps=this._ojcPack.getComponents()){for(comp in comps){this.processComponentJson(comps[comp],"oj-c")}}};Components.prototype.processComponentJson=function(obj,fromLocation){var comp,props,events,event,eventName,compName,metaObj;var isOJC;compName=obj.pack?obj.pack+"-"+obj.name:obj.name;isOJC=obj.pack===OJ_C;if(!this._isAMD){if(this._runOpts.isDryRun){console.log(" Would have processed '"+fromLocation+"'");return}if(obj.type&&obj.type==="pack"){return this._processJetPack(obj,fromLocation)}if(!isOJC){if(!this._compSvcs.validateComponentJson(obj,fromLocation)){this._isOk=false;return false}}}if(this._tagLookup[compName]||this._jetTagLookup[compName]){this._warn(`Ignoring duplicate component '${compName}' at '${fromLocation}'`);return true}if(!isOJC){this._meta[compName]=obj}if(isOJC){this._jetTagLookup[compName]=comp={}}else{this._tagLookup[compName]=comp={}}comp[PROP_FOLDER]=fromLocation;comp[PROP_VERSION]=obj.version;if(obj.extension&&obj.extension.audit&&obj.extension.audit.ignore){let ar;if((ar=obj.extension.audit.ignore)&&ar.length){this._ignored[compName]=[...ar]}}if(obj.hasOwnProperty(PROP_SLOTS)){comp[PROP_SLOTS]=obj[PROP_SLOTS]}if(obj.hasOwnProperty(PROP_DYNAMIC_SLOTS)){comp[PROP_DYNAMIC_SLOTS]=true}if(obj.properties){comp[PROP_PROPS]=props={};this._extractProps(props,null,obj.properties,obj.name)}if(obj.events){comp[PROP_EVENTS]=events={};for(event in obj.events){eventName=_deCamelCaseEvent(event);events[eventName]=obj.events[event];metaObj=obj.events}}if(obj.implements){comp[PROP_IMPLEMENTS]=obj.implements;this._metaLib.processImplements(compName,obj.implements)}if(obj.status){let status,i;metaObj=obj.status;for(i=0;i<metaObj.length;i++){status=metaObj[i];if(status.type===MAINTENANCE){if(!this._maintenance){this._maintenance=new Set}this._maintenance.add(compName)}else if(status.type===SUPERSEDES){if(!this._supercedes){this._supersedes=new Set}this._supersedes.add(compName)}}}if(obj.extension&&obj.extension.theme&&obj.extension.theme.unsupportedThemes){comp[PROP_UNSUP_THEME]=obj.extension.theme.unsupportedThemes}if(obj.hasOwnProperty(PROP_SUBCOMPONENT_TYPE)){comp[PROP_SUBCOMPONENT_TYPE]=obj[PROP_SUBCOMPONENT_TYPE]}if(obj.type){comp[PROP_TYPE]=obj.type}if(obj.pack){comp[PROP_PACK]=obj.pack}if(obj.hasOwnProperty("required")){comp[PROP_REQUIRED]=obj.required}if(obj.status){comp[PROP_STATUS]=obj.status}if(obj.styleClasses){comp[PROP_STYLECLASSES]=this._extractStyles(obj.styleClasses)}this._count++;return true};Components.prototype._extractProps=function(propObj,propSoFar,properties,name,rdonly){var prop,newProp,thisProp,soFar,obj;for(prop in properties){newProp=_deCamelCaseProp(prop);soFar=(propSoFar?propSoFar+DOT:"")+newProp;propObj[soFar]=obj={};thisProp=properties[prop];if(thisProp.hasOwnProperty("enumValues")){if(Array.isArray(thisProp.enumValues)){obj.enumValues=thisProp.enumValues}else{this._error(`Web component '${name}' property '${soFar}' has invalid 'enumValues' in component.json`)}}if(thisProp.hasOwnProperty("status")){obj.status=thisProp.status}if(thisProp.hasOwnProperty("type")){obj.type=thisProp.type}if(thisProp.required){obj.required=true}if(thisProp.extension&&thisProp.extension.theme&&thisProp.extension.theme.unsupportedThemes){obj[PROP_UNSUP_THEME]=thisProp.extension.theme.unsupportedThemes}if(thisProp.hasOwnProperty("translatable")){obj.translatable=true}if(typeof thisProp.readonly==="boolean"){obj.readonly=thisProp.readOnly}else{if(rdonly){obj.readonly=true}}if(thisProp.hasOwnProperty("properties")){obj.properties=true;this._extractProps(propObj,soFar,thisProp.properties,name,obj.readonly)}}};Components.prototype._extractStyles=function(styleClasses){var so,si,obj,ret={},i,j;if(!Array.isArray(styleClasses)){return ret}for(i=0;i<styleClasses.length;i++){so=styleClasses[i];if(so.kind==="class"){ret[so.name]=this._extractStyleClass(so)}else if(so.kind==="set"&&so.styleItems&&Array.isArray(so.styleItems)){ret[so.name]=obj={kind:"set"};if(so.status){obj.status=so.status}obj.styleClasses={};for(j=0;j<so.styleItems.length;j++){si=so.styleItems[j];obj.styleClasses[si.name]=this._extractStyleClass(si)}}else if(so.kind==="template"){}}return ret};Components.prototype._extractStyleClass=function(so){var obj={};if(so.styleSelector){obj.styleSelector=so.styleSelector}if(so.status){obj.status=so.status}return obj};Components.prototype._processJetPack=function(obj,fromLocation){var deps,dep,urlKey,depUrl,msg,i;if(this._runOpts.isDryRun||this._runOpts.isDebug){msg="processing JET Pack "+obj.name+" (version: "+obj.version+") : '"+fromLocation+"'";if(this._runOpts.isDryRun){console.log("* "+msg);return}else{this._debug(msg)}}if(!fromLocation.includes("http")){this._error("JET packs loaded via config 'components' property (file based) are currently not supported");return false}i=fromLocation.indexOf(obj.name);if(i>=0){urlKey=fromLocation.substring(0,i)}else{this._error("Cannot handle Jet Pack URL format to load dependencies : "+fromLocation)}deps=obj.dependencies;if(deps){for(dep in deps){depUrl=urlKey+dep+"/versions/"+obj.dependencies[dep]+"/content/component.json";if(this._isDebug){this._debug(` processing dependency ${dep} ${obj.dependencies[dep]}`)}this._processUrls("",[depUrl])}}return false};Components.prototype._processJetCore=function(jetCorePath){var files,file,obj,i;if(!jetCorePath){return}this._console("-".repeat(70)+"\nPerforming schema analysis on JET Core components (dt) using '"+this._compSvcs.getSchemaName()+"'...");try{files=this._nd.fs.readdirSync(jetCorePath);this._console(` processing ${files.length} $jetCore components...`);for(i=0;i<files.length;i++){file=files[i];if(file.endsWith(".json")){file=this._nd.path.join(jetCorePath,file);try{obj=this._readComponentJson(file);if(obj){this._compSvcs.validateComponentJson(obj,file)}}catch(e){}}}}catch(e1){this._error("!!! $JetCore Component check failed - "+e1)}this._console(" processing "+(files?files.length+" ":"")+"$jetCore components completed");this._console("-".repeat(70))};Components.prototype._createStyleLookup=function(){var tag,o,scl,st;for(tag in this._tagLookup){o=this._tagLookup[tag];if(scl=o.styleClasses){for(st in scl){this._styleLookup[st]=tag}}}};Components.prototype._readComponentJson=function(inFile){var obj=null;if(this._isDebug){this._debug(` loading '${inFile}'`)}obj=this._nd.jsonLoader.load(inFile,this._nd,this._error,false,this._utils);if(!obj){this._isOk=false}return obj};Components.prototype._isComponentJsonPath=function(filePath){return filePath.toLowerCase().endsWith(COMPONENT_JSON)};Components.prototype.dumpComponentNames=function(){var names;names=this.getUserNames();if(!names.length){this._console("[info]: No valid user web components declared!","I")}else{this._console("[info] :--------- Declared Web Components ---------","I");this._dumpComponentNames(names);this._console("[info]: -------- End Declared Web Components ---------\n","I")}names=this.getJetNames();if(!names.length){this._console("[info]: No valid user JET Core Pack components declared!","I")}else{this._console("[info] :--------- Declared JET OJ-C Pack Web Components ---------","I");this._dumpComponentNames(names);this._console("[info]: -------- End Declared OJ-C Pack Web Components ---------\n","I")}};Components.prototype._dumpComponentNames=function(names){var meta,obj,i;for(i=0;i<names.length;i++){obj=names[i];this._console(` ${obj.name} (${obj.version})`,"I");meta=this.getTagMetadata(obj.name);if(meta.implements){this._console(` Impls: ${meta.implements.join(",")}`)}}};function _deCamelCaseProp(str){return str.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase()};function _deCamelCaseEvent(str){return"on-"+_deCamelCaseProp(str)};function _isRelativeUrl(url){url=url.toLowerCase();return!(url.indexOf("http://")===0||url.indexOf("https://")===0)};function _removeChevrons(tagName){if(tagName){let len=tagName.length-1;let start=tagName.charAt(0)==="<"?1:0;let end=tagName.charAt(len)===">"?len:++len;tagName=tagName.substring(start,end)}return tagName};module.exports=Components;
|
|
6
|
+
"use strict";const COMPONENT_JSON="component.json";const PROPERTIES="properties";const PROP_SLOTS="slots";const PROP_DYNAMIC_SLOTS="dynamicSlots";const PROP_PROPS="props";const PROP_EVENTS="events";const PROP_STYLECLASSES="styleClasses";const PROP_IMPLEMENTS="implements";const PROP_REQUIRED="required";const PROP_FOLDER="folder";const PROP_VERSION="version";const PROP_UNSUP_THEME="unsupTheme";const PROP_STATUS="status";const PROP_SUBCOMPONENT_TYPE="subcomponentType";const PROP_TYPE="type";const PROP_PACK="pack";const PROPERTY_VALUE="propertyValue";const PROPERTY_TYPE="propertyType";const PACK_PRIVATE="packPrivate";const DEPRECATED="deprecated";const MAINTENANCE="maintenance";const SUPERSEDES="supersedes";const ANTIPATTERN="antiPattern";const DYNAMIC_FORM_ELEM="DynamicFormElement";const DYNAMIC_TABLE_ELEM="DynamicTableElement";const VB_FRAGMENT_ELEM="VbFragmentElement";const OJ_C="oj-c";const DOT=".";const DASH_CHANGED="-changed";const FT_HTML="html";const FT_TSX="tsx";const REGXPR=/string|number|object|array|boolean|[\|.<>]/gi;function Components(nd,runMode,cwd,compSvcs,urlBase,urls,filePaths,metaLib,ojcPack,jetCore,runOpts,msgCtx,appCtx){this._nd=nd;this._tagLookup={};this._jetTagLookup={};this._styleLookup={};this._ignored={};this._maintenance=null;this._supersedes=null;this._antiPattern=null;this._meta={};this._path=null;this._reqAttrs=null;this._metaLib=metaLib;this._ojcPack=ojcPack;this._utils=appCtx.utils;this._fsUtils=appCtx.fsUtils;this._curFileType=null;this._compSvcs=compSvcs;this._isAMD=runMode==="amd";this._cwd=cwd;this._error=msgCtx.error;this._warn=msgCtx.warn;this._debug=msgCtx.debug;this._info=msgCtx.info;this._msg=msgCtx.msg;this._console=msgCtx.console;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._count=0;this._isOk=true;this._runOpts=runOpts;this._init(urlBase,urls,filePaths,jetCore)};Components.prototype.isTag=function(tagName){return!!this._tagLookup[_removeChevrons(tagName)]};Components.prototype.isJetTag=function(tagName){return!!this._jetTagLookup[_removeChevrons(tagName)]};Components.prototype.isKnownTag=function(tagName){tagName=_removeChevrons(tagName);return this._jetTagLookup[tagName]||this._tagLookup[tagName]};Components.prototype.isTagAttr=function(tagName,attrName){return this.isTagProp(tagName,attrName)||this.isJetTagProp(tagName,attrName)};Components.prototype.isJetTagAttr=function(tagName,attrName){return this.isJetTagProp(tagName,attrName)};Components.prototype.isTagDeprecated=function(tag){var comp,stats,status,ret=null;tag=_removeChevrons(tag);if(comp=this._tagLookup[tag]||this._jetTagLookup[tag]){if(stats=comp.status){for(status of stats){if((!status.type||status.type===DEPRECATED)&&!status.hasOwnProperty("target")){ret=status;if(ret.description){ret.description=this._utils.removeLink(ret.description)}break}}}}return ret};Components.prototype.isTagAttrDeprecated=function(tagName,attrName){var prop,status,stats,o,ret=null;if((prop=this.getAnyTagProp(tagName,attrName))&&(stats=prop.status)){ret=[];for(status of stats){if(!status.type||status.type===DEPRECATED){o={type:DEPRECATED};if(status.hasOwnProperty("target")){o.target=status.target}if(status.hasOwnProperty("description")){o.description=status.description}if(status.hasOwnProperty("since")){o.since=status.since}if(status.hasOwnProperty("value")){o.value=status.value}ret.push(o)}}ret=ret.length?ret:null}return ret};Components.prototype.isTagEventDeprecated=function(tagName,event){var prop,status,stat,dep,ret;if(prop=this.getAnyTagEvent(tagName,event)){if(status=prop.status){for(let i=0;i<status.length;i++){dep=status[i];if(!dep.type||dep.type===DEPRECATED){ret=stat;break}}}}return ret?ret:null};Components.prototype.isTagAttrTranslatable=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.translatable};Components.prototype.isTagAttrReadOnly=function(tag,attr){var prop=this.getAnyTagProp(tag,attr);return prop&&prop.readonly};Components.prototype.isTagProp=function(tagName,propName){return!!this.getTagProp(tagName,propName)};Components.prototype.isJetTagProp=function(tagName,propName){return!!this.getJetTagProp(tagName,propName)};Components.prototype.getTagProp=function(tagName,propName){var ret;if(this.isTag(tagName)){ret=this._getTagProp(tagName,propName,false)}return ret?ret:null};Components.prototype.getJetTagProp=function(tagName,propName){var ret;if(this.isJetTag(tagName)){ret=this._getTagProp(tagName,propName,true)}return ret?ret:null};Components.prototype.getAnyTagProp=function(tagName,propName){return this._getTagProp(tagName,propName,true)||this._getTagProp(tagName,propName,false)};Components.prototype._getTagProp=function(tagName,propName,isOJC){var tag,props,list;list=isOJC?this._jetTagLookup:this._tagLookup;tag=list[_removeChevrons(tagName)];props=tag?tag[PROP_PROPS]:null;if(props){propName=propName.charAt(0)===":"?propName.substring(1):propName;if(this._curFileType!=="tsx"){propName=_propToCamelCase(propName)}}return props?props[propName]:null};Components.prototype.getTagPropType=function(tagName,propName){var prop,ret;if(prop=this.getTagProp(tagName,propName)){ret=prop?prop.type:undefined}return ret};Components.prototype.getAnyTagEvent=function(tag,event){return this._getTagEvent(tag,event,true)||this._getTagEvent(tag,event,false)};Components.prototype._getTagEvent=function(tagName,eventName,isOJC){var tag,events,event,list;list=isOJC?this._jetTagLookup:this._tagLookup;tag=list[_removeChevrons(tagName)];if(events=tag?tag[PROP_EVENTS]:null){if(!(event=events[eventName])){if(eventName.endsWith(DASH_CHANGED)){eventName=eventName.substring(0,eventName.length-DASH_CHANGED.length);if(this._curFileType!=="tsx"){eventName=_propToCamelCase(eventName)}}event=events[eventName]}}return event?event.status:null};Components.prototype.getComponentMetadata=function(tag){return this._meta[tag]||null};Components.prototype.getComponentPropMetadata=function(tagName,propName){var comp,sofar,props;tagName=_removeChevrons(tagName);if(!(comp=this._meta[tagName])||!(props=comp.properties)){return null}let subprops=propName.split(DOT);if(this._curFileType===FT_HTML){subprops.forEach((subprop,i,ar)=>{ar[i]=_propToCamelCase(subprop)})}if(subprops.length===1){return props[propName]||null}sofar=comp;let nextprop,i;for(i=0;i<subprops.length;i++){nextprop=subprops[i];if(sofar.hasOwnProperty(PROPERTIES)){sofar=sofar.properties[nextprop]||null;if(!sofar){break}}else{sofar=null;break}}return sofar};Components.prototype.getTagMetadata=function(tag){tag=_removeChevrons(tag);return this._tagLookup[tag]||this._jetTagLookup[tag]};Components.prototype.getJetTag=function(tag){var meta;return(meta=this._jetTagLookup[tag])?meta:null};Components.prototype.getMaintenanceTags=function(){return this._maintenance};Components.prototype.isTagEvent=function(tagName,eventName){var propName,o,b;o=this._tagLookup[tagName]||this._jetTagLookup[tagName];if(o){if(eventName.startsWith("on-")){b=o.events&&o.events[eventName];if(b)return b;if(o.implements&&(o.implements.includes(DYNAMIC_FORM_ELEM)||o.implements.includes(DYNAMIC_TABLE_ELEM)||o.implements.includes(VB_FRAGMENT_ELEM))){return true}if(eventName.endsWith(DASH_CHANGED)){if(o.props){propName=eventName.replace(DASH_CHANGED,"").substring(3);propName=_propToCamelCase(propName);return!!o.props[propName]}}}}return false};Components.prototype.isTagStyle=function(tag,style){var meta,ret=false;if(meta=this._tagLookup[tag]||this._jetTagLookup[tag]){let styles;if(styles=meta.styleClasses){ret=!!styles[style]}}return ret};Components.prototype.isJetStyle=function(style){var tag,ret=false;if(tag=this._styleLookup[style]){ret=!!this._jetTagLookup[tag]}return ret};Components.prototype.isStyle=function(style){return!!this._styleLookup[style]};Components.prototype.getStyleMetadata=function(style){var tag,styles,sc,ret=null;if(tag=this._styleLookup[style]){if(styles=this._tagLookup[tag].styleClasses){if(sc=styles[style]){ret={tag:tag,meta:sc}}}}return ret};Components.prototype.getStyleSelector=function(style){var sm=this.getStyleMetadata(style);return sm&&sm.meta?sm.meta.styleSelector:null};Components.prototype.hasTagSlotName=function(tagName,slotName){var o=this._tagLookup[tagName]||this._jetTagLookup[tagName];return!!(o&&o.slots&&o.slots[slotName])};Components.prototype.getPreferredSlotContent=function(tag,slotName,impls){var o,slot,prefContent=null,comps=null,content;if(this._utils.hasAnyProps(impls)){if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){if(o.slots){slotName=slotName?slotName:"";if(slot=o.slots[slotName]){if(prefContent=slot.preferredContent){prefContent.forEach(impl=>{if(content=impls[impl]){if(!comps){comps=[]}comps.push(...content)}})}}}}}return prefContent||comps?{interfaces:prefContent,components:comps}:null};Components.prototype.getTagSlotMetadata=function(tag,slot){var o,ret;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){if(o.slots){slot=slot?slot:"";if(slot=o.slots[slot]){ret=slot}}}return ret};Components.prototype.hasTagDynamicSlot=function(tag){var o,ret=false;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o.hasOwnProperty(PROP_DYNAMIC_SLOTS)}return ret};Components.prototype.hasTagAttrValues=function(tagName,attrName){var prop,ret=false;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){ret=!!prop.enumValues}return ret};Components.prototype.isTagAttrValue=function(tagName,attrName,value){var prop,ret;if((prop=this.getTagProp(tagName,attrName))||(prop=this.getJetTagProp(tagName,attrName))){if(prop&&prop.enumValues){ret=prop.enumValues.indexOf(value)>=0}}return!!ret};Components.prototype.isTagAttrEnumDeprecated=function(tag,attr,val){var prop,stats,status,ret=null;if(prop=this.getAnyTagProp(tag,attr)){if(stats=prop.status){for(status of stats){if((!status.type||status.type===DEPRECATED)&&status.target===PROPERTY_VALUE){if(status.value&&status.value.includes(val)){ret={type:DEPRECATED};if(status.hasOwnProperty("target")){ret.target=status.target}if(status.hasOwnProperty("description")){ret.description=status.description}if(status.hasOwnProperty("since")){ret.since=status.since}if(status.hasOwnProperty("value")){ret.value=status.value}break}}}}}return ret};Components.prototype.isTagSupportedInTheme=function(tag,theme){var o,unsup,ret=true;if(o=this.getTagMetadata(tag)){unsup=o[PROP_UNSUP_THEME];if(unsup){ret=!unsup.includes(theme)}}return ret};Components.prototype.isAttrSupportedInTheme=function(tag,attr,theme){var prop,unsup,ret=true;if(prop=this.getAnyTagProp(tag,attr)){if(unsup=prop[PROP_UNSUP_THEME]){ret=!unsup.includes(theme)}}return ret};Components.prototype.isTagPackPrivate=function(tag){var o,ret;tag=_removeChevrons(tag);if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o[PROP_SUBCOMPONENT_TYPE]===PACK_PRIVATE}return ret};Components.prototype.getSubcomponentType=function(tag){var o,ret;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o[PROP_SUBCOMPONENT_TYPE]}return ret||null};Components.prototype.getRequiredProps=function(tagName){var tag,props,prop,propName,obj,ret=null;tagName=_removeChevrons(tagName);if(this._reqAttrs){let r=this._reqAttrs[tagName];if(r){return typeof r==="boolean"?null:r}}tag=this._tagLookup[tagName]||this._jetTagLookup[tagName];if(tag&&tag.props){if(!this._reqAttrs){this._reqAttrs={}}if(!this._reqAttrs[tagName]){this._reqAttrs[tagName]=true}props=tag.props;for(propName in props){prop=props[propName];if(prop.required){if(!obj){obj=[]}obj.push(propName)}}}if(obj&&obj.length){let i,j,p;for(i=0;i<obj.length;i++){if(p=obj[i]){p+=".";for(j=i+1;j<obj.length;j++){if(obj[j].startsWith(p)){obj.splice(i,1);i--;break}}}}this._reqAttrs[tagName]=obj;ret=obj}return ret};Components.prototype.getRequiredAttrs=function(tagName){return this.getRequiredProps(tagName)};Components.prototype.getInterfaces=function(tag){var o,ret;if(o=this._tagLookup[tag]||this._jetTagLookup[tag]){ret=o.implements}return ret||null};Components.prototype.getUserNames=function(){var name,a=[];for(name in this._tagLookup){a.push({name:name,version:this._tagLookup[name].version})}return a};Components.prototype.getJetNames=function(){var name,a=[];for(name in this._jetTagLookup){a.push({name:name,version:this._jetTagLookup[name].version})}return a};Components.prototype.getCount=function(){return this._count};Components.prototype.isTagMaintenance=function(tag){return this._maintenance&&this._maintenance.has(tag)};Components.prototype.isTagSupersedes=function(tag){return this._supersedes&&this._supersedes.has(tag)};Components.prototype.isTagAntiPattern=function(tag){return this._antiPattern&&this._antiPattern.has(tag)};Components.prototype.getTagMaintenanceStatus=function(tag){return this.getTagStatus(tag,MAINTENANCE)};Components.prototype.getTagSupersedesStatus=function(tag){return this.getTagStatus(tag,SUPERSEDES)};Components.prototype.getTagAntiPatternStatus=function(tag){return this.getTagStatus(tag,ANTIPATTERN)};Components.prototype.getTagStatus=function(tag,type){var ret=null;if(type===SUPERSEDES&&this.isTagSupersedes(tag)||type===MAINTENANCE&&this.isTagMaintenance(tag)||type===DEPRECATED&&this.isTagDeprecated(tag)||type===ANTIPATTERN&&this.isTagAntiPattern(tag)){let comp,arStat,stat,i;if(comp=this._tagLookup[tag]||this._jetTagLookup[tag]){arStat=comp.status;for(i=0;i<arStat.length;i++){stat=arStat[i];if(stat.type===type||type===DEPRECATED&&!stat.type){ret=stat;break}}}}return ret};Components.prototype.isRuleIgnored=function(compName,ruleName){var ret,ar;if(ar=this._ignored[compName]){ret=ar.includes(ruleName)}return!!ret};Components.prototype.isOk=function(){return this._isOk};Components.prototype.setCurFileType=function(ft){this._curFileType=ft};Components.prototype._init=function(base,urls,filePaths,jetCore){if(this._isAMD){this._processJetCorePack();return}if(base){base=base.trim();if(base.charAt(base.length-1)!=="/"){base=base+"/"}}else{base=""}this._processFilePaths(filePaths);this._processUrls(base,urls);this._processJetCorePack();this._createStyleLookup();this._processJetCore(jetCore)};Components.prototype._processFilePaths=function(filePaths){var obj,compEntry,fpath,i,j;if(!filePaths){return}this._console("\nPre-processing user-declared web component metadata...");for(i=0;i<filePaths.length;i++){compEntry=filePaths[i];var dirStack=this._nd.glob.sync(compEntry);for(j=0;j<dirStack.length;j++){fpath=dirStack[j];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg="-".repeat(70)+"\n"+(this._runOpts.isDryRun?"* ":"")+"processing component path '"+fpath+"' ...";if(this._runOpts.isDryRun){console.log(msg)}else{this._debug(msg)}}if(fpath.toLowerCase().endsWith(".zip")){obj=this._compSvcs._extractComponentJsonFromZip(fpath);if(obj.obj){this.processComponentJson(obj.obj,fpath,true)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+fpath)}else if(obj.error){this._error("Failed to unzip '"+fpath+"'")}continue}if(this._isComponentJsonPath(fpath)){if(obj=this._readComponentJson(fpath)){if(obj.type&&obj.type==="pack"){continue}this.processComponentJson(obj,this._nd.path.dirname(fpath),true)}continue}this._recurse(fpath)}}if(this._isDebug){this._debug("-".repeat(70))}};Components.prototype._recurse=function(fpath){var dirs,inFile,obj,i;try{dirs=this._nd.fs.readdirSync(fpath);if(this._isDebug){this._debug(` processing ${fpath} ${dirs.length} component dirs ...`)}for(i=0;i<dirs.length;i++){inFile=dirs[i];if(inFile===COMPONENT_JSON){inFile=this._nd.path.join(fpath,COMPONENT_JSON);if(this._isDebug){this._debug(" processing "+inFile+"...")}obj=this._readComponentJson(inFile);if(obj){if(!obj.type||obj.type==="composite"){this.processComponentJson(obj,fpath,true)}}else{return}}var curPath=this._nd.path.join(fpath,inFile);if(this._fsUtils.getFileType(curPath)==="d"){this._recurse(curPath)}}}catch(e){this._error("Component check failed - "+e);this._isOk=false}};Components.prototype._processUrls=function(base,urls){var url,i;if(!urls){return}for(i=0;i<urls.length;i++){url=urls[i];if(this._runOpts.isDryRun||this._runOpts.isDebug){let msg;msg="-".repeat(70)+"\nprocessing URL '"+url+"'";if(this._runOpts.isDryRun){console.log(msg);continue}else{this._debug(msg)}}if(_isRelativeUrl(url)){url=base+url;if(_isRelativeUrl(url)){this._error("component URL incomplete - '"+url+"'");continue}}this._processUrl(url)}};Components.prototype._processUrl=function(url){var resp,obj,rc,tempFile,tmp;try{resp=this._compSvcs.loadUrl(url);if(resp.eCode==="ETIMEDOUT"){this._error("config.componentUrls - request timed-out for '"+url+"'");this._isOk=false;return}try{if(resp.type==="json"){if(resp.body){obj=JSON.parse(resp.body);if(!this.processComponentJson(obj,url,false)){this._isOk=false}}else{this._error("Server responded with "+resp.statusCode+" URL: '"+url+"'")}}else if(resp.type=="zip"){rc=this._compSvcs.writeZipBufferToFile(resp.body);if(typeof rc==="boolean"&&rc){tempFile=this._compSvcs.getLastZipFilePath();obj=this._compSvcs.extractComponentJsonFromZip(tempFile);if(obj.obj){this.processComponentJson(obj.obj,url,true)}else if(obj.msg){this._error("Failed to parse component.json : "+obj.msg+" - "+url)}else if(obj.error){this._error("Failed to unzip '"+url+"'")}this._compSvcs.deleteZipFile(tempFile)}else{this._error("Failed to create local temp zip file from URL '"+url+"' : rc.message");this._isOk=false}}else{tmp=typeof resp.type==="string"?resp.type:"?";this._error("Server responded with unexpected data ('"+tmp+"') : '"+url+"'");this._isOk=false}}catch(e){this._error("Invalid JSON - URL '"+url+"' : "+e);this._isOk=false}}catch(e1){this._error("URL access failed "+(e1.message.includes("ENOTFOUND")?"(NOT FOUND)":"")+" - URL '"+url+"'");this._isOk=false}};Components.prototype._processJetCorePack=function(){var comps,comp;if(comps=this._ojcPack.getComponents()){for(comp in comps){this.processComponentJson(comps[comp],"oj-c")}}};Components.prototype.processComponentJson=function(obj,fromLocation){var comp,props,events,event,eventName,compName,metaObj;var isOJC;compName=obj.pack?obj.pack+"-"+obj.name:obj.name;isOJC=obj.pack===OJ_C;if(!this._isAMD){if(this._runOpts.isDryRun){console.log(" Would have processed '"+fromLocation+"'");return}if(obj.type&&obj.type==="pack"){return this._processJetPack(obj,fromLocation)}if(!isOJC){if(!this._compSvcs.validateComponentJson(obj,fromLocation)){this._isOk=false;return false}}}if(this._tagLookup[compName]||this._jetTagLookup[compName]){this._warn(`Ignoring duplicate component '${compName}' at '${fromLocation}'`);return true}this._meta[compName]=obj;if(isOJC){this._jetTagLookup[compName]=comp={}}else{this._tagLookup[compName]=comp={}}comp[PROP_FOLDER]=fromLocation;comp[PROP_VERSION]=obj.version;if(obj.extension&&obj.extension.audit&&obj.extension.audit.ignore){let ar;if((ar=obj.extension.audit.ignore)&&ar.length){this._ignored[compName]=[...ar]}}if(obj.hasOwnProperty(PROP_SLOTS)){comp[PROP_SLOTS]=obj[PROP_SLOTS]}if(obj.hasOwnProperty(PROP_DYNAMIC_SLOTS)){comp[PROP_DYNAMIC_SLOTS]=obj[PROP_DYNAMIC_SLOTS]}if(obj.properties){comp[PROP_PROPS]=props={};this._extractProps(props,null,obj.properties,obj.name)}if(obj.events){comp[PROP_EVENTS]=events={};for(event in obj.events){eventName=_propEventToKebabCase(event);events[eventName]=obj.events[event];metaObj=obj.events}}if(obj.implements){comp[PROP_IMPLEMENTS]=obj.implements;this._metaLib.processImplements(compName,obj.implements)}if(obj.status){let status,i;metaObj=obj.status;for(i=0;i<metaObj.length;i++){status=metaObj[i];if(status.type===MAINTENANCE){if(!this._maintenance){this._maintenance=new Set}this._maintenance.add(compName)}else if(status.type===SUPERSEDES){if(!this._supercedes){this._supersedes=new Set}this._supersedes.add(compName)}else if(status.type===ANTIPATTERN){if(!this._antiPattern){this._antiPattern=new Set}this._antiPattern.add(compName)}}}if(obj.extension&&obj.extension.theme&&obj.extension.theme.unsupportedThemes){comp[PROP_UNSUP_THEME]=obj.extension.theme.unsupportedThemes}if(obj.hasOwnProperty(PROP_SUBCOMPONENT_TYPE)){comp[PROP_SUBCOMPONENT_TYPE]=obj[PROP_SUBCOMPONENT_TYPE]}if(obj.type){comp[PROP_TYPE]=obj.type}if(obj.pack){comp[PROP_PACK]=obj.pack}if(obj.hasOwnProperty("required")){comp[PROP_REQUIRED]=obj.required}if(obj.status){comp[PROP_STATUS]=obj.status}if(obj.styleClasses){comp[PROP_STYLECLASSES]=this._extractStyles(obj.styleClasses)}this._count++;return true};Components.prototype._extractProps=function(propObj,propSoFar,properties,name,rdonly){var prop,thisProp,soFar,obj;for(prop in properties){soFar=(propSoFar?propSoFar+DOT:"")+prop;propObj[soFar]=obj={};thisProp=properties[prop];if(thisProp.hasOwnProperty("enumValues")){if(Array.isArray(thisProp.enumValues)){obj.enumValues=thisProp.enumValues}else{this._error(`Web component '${name}' property '${soFar}' has invalid 'enumValues' in component.json`)}}if(thisProp.hasOwnProperty("status")){obj.status=thisProp.status}if(thisProp.hasOwnProperty("type")){obj.type=thisProp.type}if(thisProp.required){obj.required=true}if(thisProp.extension&&thisProp.extension.theme&&thisProp.extension.theme.unsupportedThemes){obj[PROP_UNSUP_THEME]=thisProp.extension.theme.unsupportedThemes}if(thisProp.hasOwnProperty("translatable")){obj.translatable=true}if(typeof thisProp.readonly==="boolean"){obj.readonly=thisProp.readOnly}else{if(rdonly){obj.readonly=true}}if(thisProp.hasOwnProperty("properties")){obj.properties=true;this._extractProps(propObj,soFar,thisProp.properties,name,obj.readonly)}}};Components.prototype._extractStyles=function(styleClasses){var so,si,obj,ret={},i,j;if(!Array.isArray(styleClasses)){return ret}for(i=0;i<styleClasses.length;i++){so=styleClasses[i];if(so.kind==="class"){ret[so.name]=this._extractStyleClass(so)}else if(so.kind==="set"&&so.styleItems&&Array.isArray(so.styleItems)){ret[so.name]=obj={kind:"set"};if(so.status){obj.status=so.status}obj.styleClasses={};for(j=0;j<so.styleItems.length;j++){si=so.styleItems[j];obj.styleClasses[si.name]=this._extractStyleClass(si)}}else if(so.kind==="template"){}}return ret};Components.prototype._extractStyleClass=function(so){var obj={};if(so.styleSelector){obj.styleSelector=so.styleSelector}if(so.status){obj.status=so.status}return obj};Components.prototype._processJetPack=function(obj,fromLocation){var deps,dep,urlKey,depUrl,msg,i;if(this._runOpts.isDryRun||this._runOpts.isDebug){msg="processing JET Pack "+obj.name+" (version: "+obj.version+") : '"+fromLocation+"'";if(this._runOpts.isDryRun){console.log("* "+msg);return}else{this._debug(msg)}}if(!fromLocation.includes("http")){this._error("JET packs loaded via config 'components' property (file based) are currently not supported");return false}i=fromLocation.indexOf(obj.name);if(i>=0){urlKey=fromLocation.substring(0,i)}else{this._error("Cannot handle Jet Pack URL format to load dependencies : "+fromLocation)}deps=obj.dependencies;if(deps){for(dep in deps){depUrl=urlKey+dep+"/versions/"+obj.dependencies[dep]+"/content/component.json";if(this._isDebug){this._debug(` processing dependency ${dep} ${obj.dependencies[dep]}`)}this._processUrls("",[depUrl])}}return false};Components.prototype._processJetCore=function(jetCorePath){var files,file,obj,i;if(!jetCorePath){return}this._console("-".repeat(70)+"\nPerforming schema analysis on JET Core components (dt) using '"+this._compSvcs.getSchemaName()+"'...");try{files=this._nd.fs.readdirSync(jetCorePath);this._console(` processing ${files.length} $jetCore components...`);for(i=0;i<files.length;i++){file=files[i];if(file.endsWith(".json")){file=this._nd.path.join(jetCorePath,file);try{obj=this._readComponentJson(file);if(obj){this._compSvcs.validateComponentJson(obj,file)}}catch(e){}}}}catch(e1){this._error("!!! $JetCore Component check failed - "+e1)}this._console(" processing "+(files?files.length+" ":"")+"$jetCore components completed");this._console("-".repeat(70))};Components.prototype._createStyleLookup=function(){var tag,o,scl,st;for(tag in this._tagLookup){o=this._tagLookup[tag];if(scl=o.styleClasses){for(st in scl){this._styleLookup[st]=tag}}}};Components.prototype._readComponentJson=function(inFile){var obj=null;if(this._isDebug){this._debug(` loading '${inFile}'`)}obj=this._nd.jsonLoader.load(inFile,this._nd,this._error,false,this._utils);if(!obj){this._isOk=false}return obj};Components.prototype._isComponentJsonPath=function(filePath){return filePath.toLowerCase().endsWith(COMPONENT_JSON)};Components.prototype.dumpComponentNames=function(){var names;names=this.getUserNames();if(!names.length){this._console("[info]: No valid user web components declared!","I")}else{this._console("[info] :--------- Declared Web Components ---------","I");this._dumpComponentNames(names);this._console("[info]: -------- End Declared Web Components ---------\n","I")}names=this.getJetNames();if(!names.length){this._console("[info]: No valid user JET Core Pack components declared!","I")}else{this._console("[info] :--------- Declared JET OJ-C Pack Web Components ---------","I");this._dumpComponentNames(names);this._console("[info]: -------- End Declared OJ-C Pack Web Components ---------\n","I")}};Components.prototype._dumpComponentNames=function(names){var meta,obj,i;for(i=0;i<names.length;i++){obj=names[i];this._console(` ${obj.name} (${obj.version})`,"I");meta=this.getTagMetadata(obj.name);if(meta.implements){this._console(` Impls: ${meta.implements.join(",")}`)}}};function _propToKebabCase(str){return str.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase()};function _propEventToKebabCase(str){return"on-"+_propToKebabCase(str)};function _propToCamelCase(str){var parts,i;function _camelCase(str){return str.replace(/(?:^\w|[A-Z]|\b\w)/g,function(word,index){return index==0?word.toLowerCase():word.toUpperCase()}).replace(/-|\s+/g,"")};parts=str.split(DOT);for(i=0;i<parts.length;i++){parts[i]=_camelCase(parts[i])}return parts.join(DOT)};function _isRelativeUrl(url){url=url.toLowerCase();return!(url.indexOf("http://")===0||url.indexOf("https://")===0)};function _removeChevrons(tagName){if(tagName){let len=tagName.length-1;let start=tagName.charAt(0)==="<"?1:0;let end=tagName.charAt(len)===">"?len:++len;tagName=tagName.substring(start,end)}return tagName};module.exports=Components;
|
package/lib/Config.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 Helper=require("./ConfigLib");const MACROS=require("../lib/macros");const DEFAULTS=require("./defaults");var JET_VERSIONS;const TYPE_BOOLEAN="boolean";const AT_INCLUDE="@include(";const QUOTE="\"";const TSCONFIG="tsconfig.json";var Config=function(nd,base,iniPath,fnApplyMacros,rules,severity,cliGroups,cliSev,msgCtx,modeCtx,utils,fsUtils,cbDebug){this._path=iniPath;this._dir=null;this._config=null;this._tsCfgObj=null;this._preBuilt=false;this._isOJET=modeCtx.isOJET;this._isCLI=modeCtx.isCLI;this._isAPI=modeCtx.isAPI;this._isAMD=modeCtx.isAMD;this._isCliMode=modeCtx.isCLI||modeCtx.isOJETCLI;this._rules=rules;this._utils=utils;this._fsUtils=fsUtils;this._severity=severity;this._helper=new Helper(this,nd,severity,utils,fsUtils,msgCtx,modeCtx);this.applyMacros=fnApplyMacros;this._bErrors=false;this._console=msgCtx.console;this._error=msgCtx.error;this._warn=msgCtx.warn;this._info=msgCtx.info;this._debug=msgCtx.debug;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;JET_VERSIONS=nd.jetver.getVersions();this._cliGroups=cliGroups;this._cliSev=cliSev;this._nd=nd;if(iniPath){this._init(base,iniPath,cbDebug)}};Config.prototype.getConfig=function(){var tmp=JSON.parse(JSON.stringify(this._config));if(tmp._sev){delete tmp._sev}return tmp};Config.prototype.getFiles=function(){return this._config.files};Config.prototype.getExclude=function(){return this._config.exclude};Config.prototype.getOptions=function(){return this._config.options};Config.prototype.getJetVer=function(){return this._config.jetVer};Config.prototype.getComponentsBaseUrl=function(){return this._config.componentsBaseUrl};Config.prototype.getComponentsBase=function(){return this._config.componentsBase};Config.prototype.getComponents=function(){return this._config.components};Config.prototype.getComponentUrls=function(){return this._config.componentUrls};Config.prototype.getJetCorePack=function(){return this._config.jetCorePack};Config.prototype.getComponentOptions=function(){return this._config.componentOptions};Config.prototype.getTypescript=function(){return this._config.typescript};Config.prototype.getTsConfig=function(){var ret;if(this._config.typescript){ret=this._config.typescript.tsconfig}return ret};Config.prototype.getMarkdownOptions=function(){return this._config.markdownOptions};Config.prototype.getTsConfigObj=function(){return this._tsCfgObj};Config.prototype.getOutPath=function(){return this._config.outPath};Config.prototype.getRulePacks=function(){return this._config.rulePacks};Config.prototype.getRuleMods=function(){return this._config.ruleMods};Config.prototype.getEnable=function(){return this._config.ruleMods&&this._config.ruleMods.enable?this._config.ruleMods.enable:undefined};Config.prototype.getDisable=function(){return this._config.ruleMods&&this._config.ruleMods.disable?this._config.ruleMods.disable:undefined};Config.prototype.getRuleDescriptions=function(){return this._config.ruleDescriptions};Config.prototype.getRulesFired=function(){return this._config.rulesFired};Config.prototype.getGroups=function(){return this._config.groups};Config.prototype.setGroups=function(groups){this._config.groups=groups};Config.prototype.getDefGroups=function(){return this._config.defGroups};Config.prototype.getRunRuleNames=function(){return this._config.ruleNames};Config.prototype.isBuiltinJetRules=function(){return this._config.builtinJetRules};Config.prototype.isBuiltinCspRules=function(){return this._config.builtinCspRules};Config.prototype.isBuiltinJetWcRules=function(){return this._config.builtinJetWcRules};Config.prototype.isBuiltinJetWcOracleRules=function(){return this._config.builtinJetWcOracleRules};Config.prototype.isBuiltinSpocRules=function(){return this._config.builtinSpocRules};Config.prototype.isBuiltinOjcMigrationRules=function(){return this._config.builtinOjcMigrationRules};Config.prototype.isBuiltinWebDriverTestRules=function(){return this._config.builtinWebDriverTestRules};Config.prototype.getMessages=function(){return this._config.messages};Config.prototype.setMessages=function(msgid,state){return this._helper.setMessages(msgid,state)};Config.prototype.getFollowLinks=function(){return this._config.followLinks};Config.prototype.getFormat=function(){return this._config.format};Config.prototype.getProseFormat=function(){return this._config.proseFormat};Config.prototype.getLineFormat=function(){return this._config.lineFormat};Config.prototype.getBase=function(){return this._config.base};Config.prototype.getStylesets=function(){return this._config.stylesets};Config.prototype.getNameSpaces=function(){return this._config.nameSpaces};Config.prototype.getCommon=function(){return this._config.common||{}};Config.prototype.getSeverity=function(){return this._config.severity};Config.prototype.setSeverity=function(severity){return this._config.severity=severity};Config.prototype.getSevMap=function(){return this._config.sevMap};Config.prototype.getTheme=function(){return this._config.theme};Config.prototype.getComments=function(){return this._config.comments};Config.prototype.getEcmaVer=function(){return this._config.ecmaVer};Config.prototype.getTabs=function(){return this._config.tabs};Config.prototype.getTitle=function(){return this._config.title};Config.prototype.getRetCode=function(){var ret,o;if(this._config&&this._config.options){o=this._config.options;if(o.retCode!==undefined){ret=o.retCode}else if(o.rc!==undefined){ret=o.rc}else{ret="auto"}}else{ret="auto"}return ret};Config.prototype.isOk=function(){return!this._bErrors};Config.prototype.getUserDefs=function(){return this._config.userDefs};Config.prototype.getAppendFileList=function(){return this._helper.getAddFileList()};Config.prototype.getJetPagesOnly=function(){return this._config.jetPagesOnly};Config.prototype.getTempDir=function(){return this._config.tempDir};Config.prototype.getOrigConfig=function(){return this._origConfig};Config.prototype.get$JetCore=function(){return this._config.$JetCore};Config.prototype._init=function(base,iniPath,cbDebug){var i,s,val,val2,bUseDefaults=false;if(typeof iniPath==="string"){this._dir=this._nd.path.dirname(iniPath);bUseDefaults=this._loadConfig(iniPath);if(this._bErrors){return}}else{this._config=iniPath;this._dir=this._nd.process.cwd();this._preBuilt=true}this._origConfig=this._config;this._config=_cloneConfig(this._config);this._helper.setConfig(this._config,this._preBuilt?null:iniPath,this._dir);if(this._config.options){this._isVerbose=!!this._config.options.verbose;this._isDebug=!!this._config.options.debug;let opStat=cbDebug(this._isVerbose,this._isDebug);this._isVerbose=opStat.verbose;this._isDebug=opStat.debug;this._helper.setDebugStatus(this._isVerbose,this._isDebug)}if(!this._checkProperties()){this._bErrors=true;return}if(base){this._config.base=base}if(!this._config.base){this._config.base=this._dir}if(this._config.base===MACROS.cwd){this._config.base=this._nd.process.cwd()}if(!this._cleanBase()){return}if(!bUseDefaults&&!this._isOJET){this._info("[Info]: Analyzing "+(typeof iniPath==="string"?"config '"+iniPath+"'":"pre-built config object"),"I",true)}if(this._config.extends){if(!this._helper.processExtends()){this._bErrors=true;return}}if(typeof this._config.builtinJetRules!==TYPE_BOOLEAN){this._config.builtinJetRules=true}if(typeof this._config.builtinCspRules!==TYPE_BOOLEAN){this._config.builtinCspRules=false}if(typeof this._config.builtinJetWcRules!==TYPE_BOOLEAN){this._config.builtinJetWcRules=false}if(typeof this._config.builtinJetWcOracleRules!==TYPE_BOOLEAN){this._config.builtinJetWcOracleRules=false}if(typeof this._config.builtinWebDriverTestRules!==TYPE_BOOLEAN){this._config.builtinWebDriverTestRules=false}if(this._config.builtinSpocRules){if(typeof this._config.builtinSpocRules!==TYPE_BOOLEAN){this._error("Config entry 'builtinSpocRules' must be a boolean!");this._bErrors=true;return}if(this._config.builtinSpocRules){this._config.builtinJetRules=this._config.builtinJetWcRules=this._config.builtinJetWcOracleRules=false}}if(this._config.builtinOjcMigrationRules){if(typeof this._config.builtinOjcMigrationRules!==TYPE_BOOLEAN){this._error("Config entry 'builtinOjcMigrationRules' must be a boolean!");this._bErrors=true;return}else{this._config.builtinJetRules=this._config.builtinJetWcRules=this._config.builtinJetWcOracleRules=this._config.builtinCspRules=this._config.builtinSpocRules=false}}else{this._config.builtinOjcMigrationRules=false}this._config.jetPagesOnly=!!this._config.jetPagesOnly;if(!this._config.files){this._config.files=[]}if(!this._config.options){this._config.options={}}if(this._config.jetVer){val=this._config.jetVer;if(typeof val!=="string"){this._error("Config entry 'jetVer' is not a string!");this._bErrors=true;return}val=val.trim();val2=val.split(".");for(i=0;i<val2.length;i++){if(i===0&&val2[0].charAt(0).toLowerCase()==="v"){val2[0]=val2[0].substring(1)}s=parseInt(val2[i]);if(isNaN(s)){let part=["major","minor","patch"];this._error(`Config entry 'jetVer' --> '${val}' : '${part[i]}' value is invalid`);this._bErrors=true;return}val2[i]=""+s}val=val2.join(".");if(val2.length!==3||val2[2]==="0"){s=val2.length===3;val2=this._nd.jetver.getBestVersion(val,val2);if(!val2){s=s?`Config entry 'jetVer' --> '${val}' cannot be resolved to a supported JET version`:`Config entry 'jetVer' --> '${val}' is not a supported JET version`;this._error(s);this._bErrors=true;return}val=val2}if(!JET_VERSIONS[val]){this._error(`Config entry 'jetVer' --> '${val}' is not a supported JET version!`);this._bErrors=true;return}this._config.jetVer=val}else{this._config.jetVer=DEFAULTS.JETVER}if(!this._helper.processJetCorePack()){this._bErrors=true;return}if(!this._helper.processWebComponents()){this._bErrors=true;return}if(!this._helper.processRulePacks()){this._bErrors=true;return}if(!this._helper.processRuleMods()){this._bErrors=true;return}if(!this._helper.processFormat()){this._bErrors=true;return}if(!this._helper.processProseFormat()){this._bErrors=true;return}if(!this._helper.processLineFormat()){this._bErrors=true;return}if(!this._helper.processRuleDescriptions()){this._bErrors=true;return}if(!this._helper.processRulesFired()){this._bErrors=true;return}if(!this._helper.processSevMap()){this._bErrors=true;return}if(!this._helper.processSeverity(this._cliSev)){this._bErrors=true;return}if(!this._helper.processGroups(this._cliGroups)){this._bErrors=true;return}if(!this._helper.processDefGroups()){this._bErrors=true;return}if(!this._helper.processRuleNames()){this._bErrors=true;return}if(this._config.followLinks==null){this._config.followLinks=true}else{this._config.followLinks=!!this._config.followLinks}if(!Array.isArray(this._config.files)){this._error("Config entry 'files' is not an array!");this._bErrors=true;return}if(!this._helper.validateFileList(this._config.files)){this._bErrors=true;return}if(this._config.exclude){if(!Array.isArray(this._config.exclude)){this._error("Config entry 'exclude' is not an array!");this._bErrors=true;return}if(!this._helper.validateFileList(this._config.exclude)){this._bErrors=true;return}}else if(this._config.excludes){this._error("Config property 'excludes' found - did you mean 'exclude'?");this._bErrors=true;return}if(!this._helper.processAddFileList()){this._bErrors=true;return}if(this._config.stylesets){val=this._config.stylesets;if(!Array.isArray(val)){this._error("Config property 'stylesets' is not an array!");this._bErrors=true;return}}if(this._isAMD&&this._config.tempDir){this._error("Config entry 'tempDir' is not valid in AMD mode!");this._bErrors=true;return}if(this._config.tempDir){if(typeof this._config.tempDir!=="string"){this._error("Config property 'tempDir' is not a string!");this._bErrors=true;return}if(this._config.tempDir.startsWith(".")){this._config.tempDir=this._nd.path.resolve(this._nd.process.cwd(),this._config.tempDir)}}if(!this._helper.processTypeScript()){this._bErrors=true;return}if(!this._helper.processMarkdownOpts()){this._bErrors=true;return}if(!this._helper.processMessages()){this._bErrors=true;return}if(!this._helper.processNameSpaces()){this._bErrors=true;return}if(!this._helper.processTheme()){this._bErrors=true;return}if(!this._helper.processComments()){this._bErrors=true;return}if(!this._helper.processEcmaVer()){this._bErrors=true;return}if(!this._helper.processOptions()){this._bErrors=true;return}if(!this._helper.processTitle()){this._bErrors=true;return}if(!this._helper.processRetCode()){this._bErrors=true;return}if(!this._config.extends){this._cleanConfigPaths()}if(this._config.typescript&&(val=this._config.typescript.tsconfig)){if(!(this._tsCfgObj=this._loadTsConfig(val))){this._bErrors=true;return}}};Config.prototype.validateRetCode=function(val,cb){return this._helper.validateRetCode(val,cb)};Config.prototype._cleanConfigPaths=function(){var src,i,ftype,dir;var nd=this._nd;var base=this._config.base;function _resolve(fp){if(!nd.path.isAbsolute(fp)){fp=nd.path.normalize(fp);fp=nd.path.resolve(base,fp)}return fp};if(!this._config.extends){this._info("[Info]: Using config base '"+this._config.base+"'","I")}if(src=this._config.files){for(i=0;i<src.length;i++){if(!src[i].startsWith("http")){src[i]=_resolve(src[i])}}}if(src=this._config.exclude){for(i=0;i<src.length;i++){src[i]=_resolve(src[i])}}if(src=this._config.components){for(i=0;i<src.length;i++){src[i]=_resolve(src[i])}}src=this._config.outPath;if(src&&src!=="$noout"){this._config.outPath=_resolve(src)}src=this._config.rulePacks;if(src){for(i=0;i<src.length;i++){if(!nd.path.isAbsolute(src[i].path)){dir=nd.path.normalize(src[i].path);src[i].path=nd.path.resolve(this._config.base,dir)}if(src[i].path.endsWith(".zip")){continue}ftype=this._fsUtils.getFileType(src[i].path);if(ftype!=="d"){this._error("'rulePacks (entry "+(i+1)+"): path' is not a directory - \""+src[i].path+"\"");this._bErrors=true;return}}}if(this._config.typescript&&this._config.typescript.tsconfig)src=this._config.typescript.tsconfig;if(src&&typeof src==="string"){if(!nd.path.isAbsolute(src)){dir=nd.path.normalize(src);dir=nd.path.resolve(this._config.base,dir)}else{dir=src}if(!dir.endsWith(TSCONFIG)){dir=nd.path.join(dir,TSCONFIG)}this._config.typescript.tsconfig=dir}if(src=this._config.jetCorePack){this._config.jetCorePack=_resolve(src)}if(this._bErrors){return};};Config.prototype._cleanBase=function(){var p,ft;var nd=this._nd;p=this._config.base;p=nd.path.normalize(p);p=nd.path.resolve(this._dir,p);ft=this._fsUtils.getFileType(p);if(ft!=="d"){this._error(`Config file 'base' is not a directory - '${p}'`);this._bErrors=true;return false}p=nd.path.join(p,"/");this._config.base=p;this._info(`[Info]: Using Config base '${p}'`,"I");return true};Config.prototype._loadConfig=function(iniPath){var data,stats,bUseDefaults=false,msg;var nd=this._nd;try{stats=nd.fs.statSync(iniPath);if(!stats.isFile()){this._warn("\n[Warn]: Config file '"+iniPath+"' not found. Using defaults.\n");bUseDefaults=true}else{data=nd.fs.readFileSync(iniPath,"utf8");data=nd.decomment(data);data=this.processIncludes(data,iniPath);data=this.processTokens(data);if(this._bErrors){return}if(this._isDebug){if(!data){console.log("NO CONFIG DATA")}else{var a=data.split("\n");console.log("------------- Config Raw Text...");for(var i=0;i<a.length;i++){console.log(i+1+"] "+a[i])}console.log("-".repeat(40))}}if(data){this._config=JSON.parse(nd.decomment(data))}else{this._bErrors=true}}}catch(e){this._bErrors=true;if(e.code){if(e.message.startsWith("ENOENT:")){this._warn("\nConfig file \""+iniPath+"\" not found - using defaults.\n");this._bErrors=false;bUseDefaults=true}}else if(e.toString().startsWith("SyntaxError")){msg=_convertMsgToRowCol(e.message,data,this._utils)}else{msg=e.message}if(msg){msg=msg.replace(/\r/g,"");msg=msg.replace(/ +(?= )/g,"");this._error("Config parse error");this._error("Config file '"+iniPath+"' - "+msg)}}if(this._bErrors){return}if(bUseDefaults){this._config={exclude:["./**/*-min.js","./**/*-min.css","./**/node_modules/**/*.*"],builtinJetRules:true,builtinCspRules:false,builtinJetWcRules:false,builtinJetWcOracleRules:false,builtinOjcMigrationRules:false,followLinks:true,severity:this._severity.ALL,format:"prose",ecmaVer:DEFAULTS.ECMAVER,options:{verbose:false,color:true}}}return bUseDefaults};Config.prototype._checkProperties=function(){return this._helper.checkPropNames()};Config.prototype._loadTsConfig=function(fp){return this._nd.jsonLoader.load(fp,this._nd,m=>{this._error(`Error loading tsconfig : ${m}.`);this._bErrors=true},false,this._utils)};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)+"row "+rc.row+", col "+rc.col};Config.prototype.processTokens=function(data){const TOKENS="\"tokens\"";var token,sub,start,end,json,toks,count,subst,rc,x,n;if(this._isDebug){this._debug("Performing config 'tokens' substitution...")}x=data.indexOf(TOKENS);if(x<0)return data;x+=TOKENS.length;n=this._expect(data,x,":",true);if(n<0){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: expected ':' after property "+TOKENS+" on line "+rc.row+" position "+rc.col+".");this._bErrors=true;return}n=this._expect(data,n,"{");if(n<0){rc=this._utils.getRowColFromIndex(data,n);this._error("Config: expected '{' after property "+TOKENS+" on line "+rc.row+".");this._bErrors=true;return}start=n;end=data.indexOf("}",start);if(end<0){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: "+TOKENS+" property syntax error (on/after line "+rc.row+").");this._bErrors=true;return}json=data.substring(start,end+1);try{toks=JSON.parse(json)}catch(e){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: syntax error "+TOKENS+" property (on/after line "+rc.row+").");this._bErrors=true;return}subst=0;count=0;for(token in toks){if(token.charAt(0)!=="@"){this._error("Config: token '"+token+"' : must be prefixed with '@'");this._bErrors=true;return}sub=toks[token];token=token.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");token=new RegExp(token,"g");if(this._isVerbose||this._isDebug){n=data.match(token).length;subst+=n>1?--n:0}data=data.replace(token,sub);count++}if(count){try{start=data.indexOf(TOKENS);start=this._expect(data,start+TOKENS.length,":",true);start=this._expect(data,start,"{");end=data.indexOf("}",start+1);data=data.substring(0,start)+json+data.substring(end+1);if(this._isVerbose||this._isDebug){this._info("[Info]: "+subst+" config token substitution"+(subst!==1?"s":"")+" performed with "+count+" token"+(count!==1?"s":"")+".")}}catch(e){this._error("Config: \"tokens\" substitution failed - review \"tokens\" property value");this._bErrors=true}}return data};Config.prototype._expect=function(data,x,s,bump){var ret=-1;x=this._utils.eatWhitespace(data,x);if(x>=0&&data.substr(x,s.length)===s){ret=x+(bump?s.length:0)}return ret};Config.prototype.processIncludes=function(data,filepath,chain){var a,i,line,x,path,comma;var inserts,insert,incPath;var nd=this._nd;if(this._isDebug){this._debug("Checking for "+(chain?"sub ":"")+"@include. . .")}if((i=data.indexOf(AT_INCLUDE))<0||data.charAt(i-1)==="_"){if(this._isDebug){this._debug("No "+(chain?"sub ":"")+"@include found")}return data}inserts=[];a=data.split("\n");for(i=0;i<a.length;i++){line=a[i];x=line.indexOf(AT_INCLUDE);if(x<0){continue}path=_extractStringFromLine(line,x+AT_INCLUDE.length,this._utils);if(!path){this._error("Config - @include syntax error"+(chain?" in '"+filepath+"'":"!"));return null}incPath=nd.path.normalize(path);incPath=nd.path.resolve(this._dir,incPath);comma=_isTrailingComma(line,x+AT_INCLUDE.length,this._utils);try{if(this._isDebug){this._debug("Reading @include -> "+incPath)}insert=nd.fs.readFileSync(incPath,"utf8")}catch(e){this._error("Config @include - "+e);return null}if(!insert){this._error("Config - @include '"+incPath+"' not found!");return null}insert=this.processIncludes(insert,incPath,true);if(insert){inserts.push(i);inserts.push(insert+(comma?",":""))}else if(insert===null){return null}}if(inserts&&inserts.length){for(i=0;i<inserts.length;i++){a[inserts[i]]=inserts[++i]}}return a.join("\n")};function _extractStringFromLine(data,start,utils){var c,xEnd,wantQuote,antiQuote;start=utils.eatWhitespace(data,start);if(start<0){return null}c=data.charAt(start);wantQuote=c===QUOTE||c==="'"?c:null;if(wantQuote){antiQuote=c===QUOTE?"'":QUOTE;start++}for(xEnd=start;xEnd<data.length;xEnd++){c=data.charAt(xEnd);if(c===")"||wantQuote&&c===wantQuote){break}else if(c==="\n"||wantQuote&&c===antiQuote||!wantQuote&&(c===QUOTE||c==="'")){xEnd=-1;break}}if(xEnd<0||xEnd>=data.length||wantQuote&&data.charAt(xEnd)!==wantQuote){return null}data=data.substring(start,xEnd).trim();return data?data:null};function _isTrailingComma(s,x,utils){var n,ret=false;n=s.indexOf(")",x);if(n<0){return false}n=utils.eatWhitespace(s,n+1);if(n>=0){ret=s.charAt(n)===","}return ret};function _cloneConfig(o){return JSON.parse(JSON.stringify(o))};module.exports=Config;
|
|
6
|
+
const Helper=require("./ConfigLib");const MACROS=require("../lib/macros");const DEFAULTS=require("./defaults");var JET_VERSIONS;const TYPE_BOOLEAN="boolean";const AT_INCLUDE="@include(";const QUOTE="\"";const TSCONFIG="tsconfig.json";var Config=function(nd,base,iniPath,fnApplyMacros,rules,severity,cliGroups,cliSev,msgCtx,modeCtx,utils,fsUtils,cbDebug){this._path=iniPath;this._dir=null;this._config=null;this._tsCfgObj=null;this._preBuilt=false;this._isOJET=modeCtx.isOJET;this._isCLI=modeCtx.isCLI;this._isAPI=modeCtx.isAPI;this._isAMD=modeCtx.isAMD;this._isCliMode=modeCtx.isCLI||modeCtx.isOJETCLI;this._rules=rules;this._utils=utils;this._fsUtils=fsUtils;this._severity=severity;this._helper=new Helper(this,nd,severity,utils,fsUtils,msgCtx,modeCtx);this.applyMacros=fnApplyMacros;this._bErrors=false;this._console=msgCtx.console;this._error=msgCtx.error;this._warn=msgCtx.warn;this._info=msgCtx.info;this._debug=msgCtx.debug;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;JET_VERSIONS=nd.jetver.getVersions();this._cliGroups=cliGroups;this._cliSev=cliSev;this._nd=nd;if(iniPath){this._init(base,iniPath,cbDebug)}};Config.prototype.getConfig=function(){var tmp=JSON.parse(JSON.stringify(this._config));if(tmp._sev){delete tmp._sev}return tmp};Config.prototype.getFiles=function(){return this._config.files};Config.prototype.getExclude=function(){return this._config.exclude};Config.prototype.getOptions=function(){return this._config.options};Config.prototype.getJetVer=function(){return this._config.jetVer};Config.prototype.getComponentsBaseUrl=function(){return this._config.componentsBaseUrl};Config.prototype.getComponentsBase=function(){return this._config.componentsBase};Config.prototype.getComponents=function(){return this._config.components};Config.prototype.getComponentUrls=function(){return this._config.componentUrls};Config.prototype.getJetCorePack=function(){return this._config.jetCorePack};Config.prototype.getComponentOptions=function(){return this._config.componentOptions};Config.prototype.getTypescript=function(){return this._config.typescript};Config.prototype.getTsConfig=function(){var ret;if(this._config.typescript){ret=this._config.typescript.tsconfig}return ret};Config.prototype.getMarkdownOptions=function(){return this._config.markdownOptions};Config.prototype.getTsConfigObj=function(){return this._tsCfgObj};Config.prototype.getOutPath=function(){return this._config.outPath};Config.prototype.getRulePacks=function(){return this._config.rulePacks};Config.prototype.getRuleMods=function(){return this._config.ruleMods};Config.prototype.getEnable=function(){return this._config.ruleMods&&this._config.ruleMods.enable?this._config.ruleMods.enable:undefined};Config.prototype.getDisable=function(){return this._config.ruleMods&&this._config.ruleMods.disable?this._config.ruleMods.disable:undefined};Config.prototype.getRuleDescriptions=function(){return this._config.ruleDescriptions};Config.prototype.getRulesFired=function(){return this._config.rulesFired};Config.prototype.getGroups=function(){return this._config.groups};Config.prototype.setGroups=function(groups){this._config.groups=groups};Config.prototype.getDefGroups=function(){return this._config.defGroups};Config.prototype.getRunRuleNames=function(){return this._config.ruleNames};Config.prototype.isBuiltinJetRules=function(){return this._config.builtinJetRules};Config.prototype.isBuiltinCspRules=function(){return this._config.builtinCspRules};Config.prototype.isBuiltinJetWcRules=function(){return this._config.builtinJetWcRules};Config.prototype.isBuiltinJetWcOracleRules=function(){return this._config.builtinJetWcOracleRules};Config.prototype.isBuiltinSpocRules=function(){return this._config.builtinSpocRules};Config.prototype.isBuiltinOjcMigrationRules=function(){return this._config.builtinOjcMigrationRules};Config.prototype.isBuiltinWebDriverTestRules=function(){return this._config.builtinWebDriverTestRules};Config.prototype.getMessages=function(){return this._config.messages};Config.prototype.setMessages=function(msgid,state){return this._helper.setMessages(msgid,state)};Config.prototype.getFollowLinks=function(){return this._config.followLinks};Config.prototype.getFormat=function(){return this._config.format};Config.prototype.getProseFormat=function(){return this._config.proseFormat};Config.prototype.getLineFormat=function(){return this._config.lineFormat};Config.prototype.getBase=function(){return this._config.base};Config.prototype.getStylesets=function(){return this._config.stylesets};Config.prototype.getNameSpaces=function(){return this._config.nameSpaces};Config.prototype.getCommon=function(){return this._config.common||{}};Config.prototype.getSeverity=function(){return this._config.severity};Config.prototype.setSeverity=function(severity){return this._config.severity=severity};Config.prototype.getSevMap=function(){return this._config.sevMap};Config.prototype.getTheme=function(){return this._config.theme};Config.prototype.getComments=function(){return this._config.comments};Config.prototype.getEcmaVer=function(){return this._config.ecmaVer};Config.prototype.getTabs=function(){return this._config.tabs};Config.prototype.getTitle=function(){return this._config.title};Config.prototype.getRetCode=function(){var ret,o;if(this._config&&this._config.options){o=this._config.options;if(o.retCode!==undefined){ret=o.retCode}else if(o.rc!==undefined){ret=o.rc}else{ret="auto"}}else{ret="auto"}return ret};Config.prototype.isOk=function(){return!this._bErrors};Config.prototype.getUserDefs=function(){return this._config.userDefs};Config.prototype.getAppendFileList=function(){return this._helper.getAddFileList()};Config.prototype.getJetPagesOnly=function(){return this._config.jetPagesOnly};Config.prototype.getTempDir=function(){return this._config.tempDir};Config.prototype.getOrigConfig=function(){return this._origConfig};Config.prototype.get$JetCore=function(){return this._config.$JetCore};Config.prototype._init=function(base,iniPath,cbDebug){var i,s,val,val2,bUseDefaults=false;if(typeof iniPath==="string"){this._dir=this._nd.path.dirname(iniPath);bUseDefaults=this._loadConfig(iniPath);if(this._bErrors){return}}else{this._config=iniPath;this._dir=this._nd.process.cwd();this._preBuilt=true}this._origConfig=this._config;this._config=_cloneConfig(this._config);this._helper.setConfig(this._config,this._preBuilt?null:iniPath,this._dir);if(this._config.options){this._isVerbose=!!this._config.options.verbose;this._isDebug=!!this._config.options.debug;let opStat=cbDebug(this._isVerbose,this._isDebug);this._isVerbose=opStat.verbose;this._isDebug=opStat.debug;this._helper.setDebugStatus(this._isVerbose,this._isDebug)}if(!this._checkProperties()){this._bErrors=true;return}if(base){this._config.base=base}if(!this._config.base){this._config.base=this._dir}if(this._config.base===MACROS.cwd){this._config.base=this._nd.process.cwd()}if(!this._cleanBase()){return}if(!bUseDefaults&&!this._isOJET){this._info("[Info]: Analyzing "+(typeof iniPath==="string"?"config '"+iniPath+"'":"pre-built config object"),"I",true)}if(this._config.extends){if(!this._helper.processExtends()){this._bErrors=true;return}}if(this._config?.options?.experimental&&this._config.options.experimental!=="tsx"){this._error("Config entry 'experimental' - invalid value!");this._bErrors=true;return}if(typeof this._config.builtinJetRules!==TYPE_BOOLEAN){this._config.builtinJetRules=true}if(typeof this._config.builtinCspRules!==TYPE_BOOLEAN){this._config.builtinCspRules=false}if(typeof this._config.builtinJetWcRules!==TYPE_BOOLEAN){this._config.builtinJetWcRules=false}if(typeof this._config.builtinJetWcOracleRules!==TYPE_BOOLEAN){this._config.builtinJetWcOracleRules=false}if(typeof this._config.builtinWebDriverTestRules!==TYPE_BOOLEAN){this._config.builtinWebDriverTestRules=false}if(this._config.builtinSpocRules){if(typeof this._config.builtinSpocRules!==TYPE_BOOLEAN){this._error("Config entry 'builtinSpocRules' must be a boolean!");this._bErrors=true;return}if(this._config.builtinSpocRules){this._config.builtinJetRules=this._config.builtinJetWcRules=this._config.builtinJetWcOracleRules=false}}if(this._config.builtinOjcMigrationRules){if(typeof this._config.builtinOjcMigrationRules!==TYPE_BOOLEAN){this._error("Config entry 'builtinOjcMigrationRules' must be a boolean!");this._bErrors=true;return}else{this._config.builtinJetRules=this._config.builtinJetWcRules=this._config.builtinJetWcOracleRules=this._config.builtinCspRules=this._config.builtinSpocRules=false}}else{this._config.builtinOjcMigrationRules=false}this._config.jetPagesOnly=!!this._config.jetPagesOnly;if(!this._config.files){this._config.files=[]}if(!this._config.options){this._config.options={}}if(this._config.jetVer){val=this._config.jetVer;if(typeof val!=="string"){this._error("Config entry 'jetVer' is not a string!");this._bErrors=true;return}val=val.trim();val2=val.split(".");for(i=0;i<val2.length;i++){if(i===0&&val2[0].charAt(0).toLowerCase()==="v"){val2[0]=val2[0].substring(1)}s=parseInt(val2[i]);if(isNaN(s)){let part=["major","minor","patch"];this._error(`Config entry 'jetVer' --> '${val}' : '${part[i]}' value is invalid`);this._bErrors=true;return}val2[i]=""+s}val=val2.join(".");if(val2.length!==3||val2[2]==="0"){s=val2.length===3;val2=this._nd.jetver.getBestVersion(val,val2);if(!val2){s=s?`Config entry 'jetVer' --> '${val}' cannot be resolved to a supported JET version`:`Config entry 'jetVer' --> '${val}' is not a supported JET version`;this._error(s);this._bErrors=true;return}val=val2}if(!JET_VERSIONS[val]){this._error(`Config entry 'jetVer' --> '${val}' is not a supported JET version!`);this._bErrors=true;return}this._config.jetVer=val}else{this._config.jetVer=DEFAULTS.JETVER}if(!this._helper.processJetCorePack()){this._bErrors=true;return}if(!this._helper.processWebComponents()){this._bErrors=true;return}if(!this._helper.processRulePacks()){this._bErrors=true;return}if(!this._helper.processRuleMods()){this._bErrors=true;return}if(!this._helper.processFormat()){this._bErrors=true;return}if(!this._helper.processProseFormat()){this._bErrors=true;return}if(!this._helper.processLineFormat()){this._bErrors=true;return}if(!this._helper.processRuleDescriptions()){this._bErrors=true;return}if(!this._helper.processRulesFired()){this._bErrors=true;return}if(!this._helper.processSevMap()){this._bErrors=true;return}if(!this._helper.processSeverity(this._cliSev)){this._bErrors=true;return}if(!this._helper.processGroups(this._cliGroups)){this._bErrors=true;return}if(!this._helper.processDefGroups()){this._bErrors=true;return}if(!this._helper.processRuleNames()){this._bErrors=true;return}if(this._config.followLinks==null){this._config.followLinks=true}else{this._config.followLinks=!!this._config.followLinks}if(!Array.isArray(this._config.files)){this._error("Config entry 'files' is not an array!");this._bErrors=true;return}if(!this._helper.validateFileList(this._config.files)){this._bErrors=true;return}if(this._config.exclude){if(!Array.isArray(this._config.exclude)){this._error("Config entry 'exclude' is not an array!");this._bErrors=true;return}if(!this._helper.validateFileList(this._config.exclude)){this._bErrors=true;return}}else if(this._config.excludes){this._error("Config property 'excludes' found - did you mean 'exclude'?");this._bErrors=true;return}if(!this._helper.processAddFileList()){this._bErrors=true;return}if(this._config.stylesets){val=this._config.stylesets;if(!Array.isArray(val)){this._error("Config property 'stylesets' is not an array!");this._bErrors=true;return}}if(this._isAMD&&this._config.tempDir){this._error("Config entry 'tempDir' is not valid in AMD mode!");this._bErrors=true;return}if(this._config.tempDir){if(typeof this._config.tempDir!=="string"){this._error("Config property 'tempDir' is not a string!");this._bErrors=true;return}if(this._config.tempDir.startsWith(".")){this._config.tempDir=this._nd.path.resolve(this._nd.process.cwd(),this._config.tempDir)}}if(!this._helper.processTypeScript()){this._bErrors=true;return}if(!this._helper.processMarkdownOpts()){this._bErrors=true;return}if(!this._helper.processMessages()){this._bErrors=true;return}if(!this._helper.processNameSpaces()){this._bErrors=true;return}if(!this._helper.processTheme()){this._bErrors=true;return}if(!this._helper.processComments()){this._bErrors=true;return}if(!this._helper.processEcmaVer()){this._bErrors=true;return}if(!this._helper.processOptions()){this._bErrors=true;return}if(!this._helper.processTitle()){this._bErrors=true;return}if(!this._helper.processRetCode()){this._bErrors=true;return}if(!this._config.extends){this._cleanConfigPaths()}if(this._config.typescript&&(val=this._config.typescript.tsconfig)){if(!(this._tsCfgObj=this._loadTsConfig(val))){this._bErrors=true;return}}};Config.prototype.validateRetCode=function(val,cb){return this._helper.validateRetCode(val,cb)};Config.prototype._cleanConfigPaths=function(){var src,i,ftype,dir;var nd=this._nd;var base=this._config.base;function _resolve(fp){if(!nd.path.isAbsolute(fp)){fp=nd.path.normalize(fp);fp=nd.path.resolve(base,fp)}return fp};if(!this._config.extends){this._info("[Info]: Using config base '"+this._config.base+"'","I")}if(src=this._config.files){for(i=0;i<src.length;i++){if(!src[i].startsWith("http")){src[i]=_resolve(src[i])}}}if(src=this._config.exclude){for(i=0;i<src.length;i++){src[i]=_resolve(src[i])}}if(src=this._config.components){for(i=0;i<src.length;i++){src[i]=_resolve(src[i])}}src=this._config.outPath;if(src&&src!=="$noout"){this._config.outPath=_resolve(src)}src=this._config.rulePacks;if(src){for(i=0;i<src.length;i++){if(!nd.path.isAbsolute(src[i].path)){dir=nd.path.normalize(src[i].path);src[i].path=nd.path.resolve(this._config.base,dir)}if(src[i].path.endsWith(".zip")){continue}ftype=this._fsUtils.getFileType(src[i].path);if(ftype!=="d"){this._error("'rulePacks (entry "+(i+1)+"): path' is not a directory - \""+src[i].path+"\"");this._bErrors=true;return}}}if(this._config.typescript&&this._config.typescript.tsconfig)src=this._config.typescript.tsconfig;if(src&&typeof src==="string"){if(!nd.path.isAbsolute(src)){dir=nd.path.normalize(src);dir=nd.path.resolve(this._config.base,dir)}else{dir=src}if(!dir.endsWith(TSCONFIG)){dir=nd.path.join(dir,TSCONFIG)}this._config.typescript.tsconfig=dir}if(src=this._config.jetCorePack){this._config.jetCorePack=_resolve(src)}if(this._bErrors){return};};Config.prototype._cleanBase=function(){var p,ft;var nd=this._nd;p=this._config.base;p=nd.path.normalize(p);p=nd.path.resolve(this._dir,p);ft=this._fsUtils.getFileType(p);if(ft!=="d"){this._error(`Config file 'base' is not a directory - '${p}'`);this._bErrors=true;return false}p=nd.path.join(p,"/");this._config.base=p;this._info(`[Info]: Using Config base '${p}'`,"I");return true};Config.prototype._loadConfig=function(iniPath){var data,stats,bUseDefaults=false,msg;var nd=this._nd;try{stats=nd.fs.statSync(iniPath);if(!stats.isFile()){this._warn("\n[Warn]: Config file '"+iniPath+"' not found. Using defaults.\n");bUseDefaults=true}else{data=nd.fs.readFileSync(iniPath,"utf8");data=nd.decomment(data);data=this.processIncludes(data,iniPath);data=this.processTokens(data);if(this._bErrors){return}if(this._isDebug){if(!data){console.log("NO CONFIG DATA")}else{var a=data.split("\n");console.log("------------- Config Raw Text...");for(var i=0;i<a.length;i++){console.log(i+1+"] "+a[i])}console.log("-".repeat(40))}}if(data){this._config=JSON.parse(nd.decomment(data))}else{this._bErrors=true}}}catch(e){this._bErrors=true;if(e.code){if(e.message.startsWith("ENOENT:")){this._warn("\nConfig file \""+iniPath+"\" not found - using defaults.\n");this._bErrors=false;bUseDefaults=true}}else if(e.toString().startsWith("SyntaxError")){msg=_convertMsgToRowCol(e.message,data,this._utils)}else{msg=e.message}if(msg){msg=msg.replace(/\r/g,"");msg=msg.replace(/ +(?= )/g,"");this._error("Config parse error");this._error("Config file '"+iniPath+"' - "+msg)}}if(this._bErrors){return}if(bUseDefaults){this._config={exclude:["./**/*-min.js","./**/*-min.css","./**/node_modules/**/*.*"],builtinJetRules:true,builtinCspRules:false,builtinJetWcRules:false,builtinJetWcOracleRules:false,builtinOjcMigrationRules:false,followLinks:true,severity:this._severity.ALL,format:"prose",ecmaVer:DEFAULTS.ECMAVER,options:{verbose:false,color:true}}}return bUseDefaults};Config.prototype._checkProperties=function(){return this._helper.checkPropNames()};Config.prototype._loadTsConfig=function(fp){return this._nd.jsonLoader.load(fp,this._nd,m=>{this._error(`Error loading tsconfig : ${m}.`);this._bErrors=true},false,this._utils)};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)+"row "+rc.row+", col "+rc.col};Config.prototype.processTokens=function(data){const TOKENS="\"tokens\"";var token,sub,start,end,json,toks,count,subst,rc,x,n;if(this._isDebug){this._debug("Performing config 'tokens' substitution...")}x=data.indexOf(TOKENS);if(x<0)return data;x+=TOKENS.length;n=this._expect(data,x,":",true);if(n<0){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: expected ':' after property "+TOKENS+" on line "+rc.row+" position "+rc.col+".");this._bErrors=true;return}n=this._expect(data,n,"{");if(n<0){rc=this._utils.getRowColFromIndex(data,n);this._error("Config: expected '{' after property "+TOKENS+" on line "+rc.row+".");this._bErrors=true;return}start=n;end=data.indexOf("}",start);if(end<0){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: "+TOKENS+" property syntax error (on/after line "+rc.row+").");this._bErrors=true;return}json=data.substring(start,end+1);try{toks=JSON.parse(json)}catch(e){rc=this._utils.getRowColFromIndex(data,x);this._error("Config: syntax error "+TOKENS+" property (on/after line "+rc.row+").");this._bErrors=true;return}subst=0;count=0;for(token in toks){if(token.charAt(0)!=="@"){this._error("Config: token '"+token+"' : must be prefixed with '@'");this._bErrors=true;return}sub=toks[token];token=token.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");token=new RegExp(token,"g");if(this._isVerbose||this._isDebug){n=data.match(token).length;subst+=n>1?--n:0}data=data.replace(token,sub);count++}if(count){try{start=data.indexOf(TOKENS);start=this._expect(data,start+TOKENS.length,":",true);start=this._expect(data,start,"{");end=data.indexOf("}",start+1);data=data.substring(0,start)+json+data.substring(end+1);if(this._isVerbose||this._isDebug){this._info("[Info]: "+subst+" config token substitution"+(subst!==1?"s":"")+" performed with "+count+" token"+(count!==1?"s":"")+".")}}catch(e){this._error("Config: \"tokens\" substitution failed - review \"tokens\" property value");this._bErrors=true}}return data};Config.prototype._expect=function(data,x,s,bump){var ret=-1;x=this._utils.eatWhitespace(data,x);if(x>=0&&data.substr(x,s.length)===s){ret=x+(bump?s.length:0)}return ret};Config.prototype.processIncludes=function(data,filepath,chain){var a,i,line,x,path,comma;var inserts,insert,incPath;var nd=this._nd;if(this._isDebug){this._debug("Checking for "+(chain?"sub ":"")+"@include. . .")}if((i=data.indexOf(AT_INCLUDE))<0||data.charAt(i-1)==="_"){if(this._isDebug){this._debug("No "+(chain?"sub ":"")+"@include found")}return data}inserts=[];a=data.split("\n");for(i=0;i<a.length;i++){line=a[i];x=line.indexOf(AT_INCLUDE);if(x<0){continue}path=_extractStringFromLine(line,x+AT_INCLUDE.length,this._utils);if(!path){this._error("Config - @include syntax error"+(chain?" in '"+filepath+"'":"!"));return null}incPath=nd.path.normalize(path);incPath=nd.path.resolve(this._dir,incPath);comma=_isTrailingComma(line,x+AT_INCLUDE.length,this._utils);try{if(this._isDebug){this._debug("Reading @include -> "+incPath)}insert=nd.fs.readFileSync(incPath,"utf8")}catch(e){this._error("Config @include - "+e);return null}if(!insert){this._error("Config - @include '"+incPath+"' not found!");return null}insert=this.processIncludes(insert,incPath,true);if(insert){inserts.push(i);inserts.push(insert+(comma?",":""))}else if(insert===null){return null}}if(inserts&&inserts.length){for(i=0;i<inserts.length;i++){a[inserts[i]]=inserts[++i]}}return a.join("\n")};function _extractStringFromLine(data,start,utils){var c,xEnd,wantQuote,antiQuote;start=utils.eatWhitespace(data,start);if(start<0){return null}c=data.charAt(start);wantQuote=c===QUOTE||c==="'"?c:null;if(wantQuote){antiQuote=c===QUOTE?"'":QUOTE;start++}for(xEnd=start;xEnd<data.length;xEnd++){c=data.charAt(xEnd);if(c===")"||wantQuote&&c===wantQuote){break}else if(c==="\n"||wantQuote&&c===antiQuote||!wantQuote&&(c===QUOTE||c==="'")){xEnd=-1;break}}if(xEnd<0||xEnd>=data.length||wantQuote&&data.charAt(xEnd)!==wantQuote){return null}data=data.substring(start,xEnd).trim();return data?data:null};function _isTrailingComma(s,x,utils){var n,ret=false;n=s.indexOf(")",x);if(n<0){return false}n=utils.eatWhitespace(s,n+1);if(n>=0){ret=s.charAt(n)===","}return ret};function _cloneConfig(o){return JSON.parse(JSON.stringify(o))};module.exports=Config;
|
package/lib/ConfigLib.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const GROUPS=require("./groups");const DEFAULTS=require("./defaults");const SemVer=require("semver");const COMPOSITES="jet-composites";const TYPE_STRING="string";const TYPE_BOOLEAN="boolean";const AUTO="auto";const ERRORS="errors";const UNDEF="undefined";const NUMBER="number";const TOP_PROPS=["rulePacks","ruleMods","builtinJetRules","builtinCspRules","builtinSpocRules","builtinJetWcRules","builtinJetWcOracleRules","builtinOjcMigrationRules","builtinWebDriverTestRules","severity","groups","defGroups","ruleNames","base","files","exclude","typescript","jetPagesOnly","format","proseFormat","lineFormat","outPath","tabs","messages","addFileList","title","jetVer","components","componentUrls","componentOptions","jetCorePack","markdownOptions","stylesets","ecmaVer","ruleDescriptions","rulesFired","userDefs","options","comments","extends","extendOptions","nameSpaces","followLinks","tempDir","tokens","common","$JetCore","sevMap","theme","ojet","appendFileList"];const NOT_AMD=["addFileList","base","builtinJetWcRules","builtinJetWcOracleRules","builtinOjcMigrationRules","builtinWebDriverTestRules","components","componentOptions","componentUrls","extendOptions","files","exclude","followLinks","outPath","rulePacks","tempDir","tokens","typescript"];const OPTIONS_PROPS=["debug","verbose","color","msgid","ruleName","retCode","rc","ojetUpdate","$unittest"];const THEMES=["redwood","alta","stable","none"];const DEF_COMMENTS=false;const DEF_RULE_DESCRIPT="none";const DEF_GROUPS=["all"];const DEF_RETCODE="auto";const ISSUE_TAG="issueTag";const ECMA_VER=[5,6,7,8,9,10,11,12,13];const ECMA_YEAR=[-1,2015,2016,2017,2018,2019,2020,2021,2022];function CfgLib(oConfig,nodeDeps,sevLib,utils,fsUtils,msgCtx,modeCtx){this._oConfig=oConfig;this._config=null;this._dir=null;this._sevLib=sevLib;this._utils=utils;this._fsUtils=fsUtils;this._nd=nodeDeps;this._msgCtx=msgCtx;this._modeCtx=modeCtx;this._isVerbose=msgCtx.isVerbose;this._isCLI=modeCtx.isCLI||modeCtx.isOJETCLI;this._error=msgCtx.error;this._warn=msgCtx.warn;this._info=msgCtx.info};CfgLib.prototype.setDebugStatus=function(verbose,debug){this._isVerbose=this._msgCtx.isVerbose=verbose};CfgLib.prototype.processWebComponents=function(){var dir,o,t,i;var config=this._config;if(config.componentUrlBase){if(!typeof config.componentUrlBase===TYPE_STRING){this._error("Config entry 'componentUrlBase' must be a string!");return false}}if(config.componentUrls){if(typeof config.componentUrls===TYPE_STRING){config.componentUrls=[config.componentUrls]}else if(!Array.isArray(config.componentUrls)){this._error("Config entry 'componentUrls' must be a string or an aray of strings!");return false}for(i=0;i<this._config.componentUrls.length;i++){config.componentUrls[i]=config.componentUrls[i].trim();if(config.componentUrls[i].length===0){config.componentUrls.splice(i,1);i--}}}if(!config.components){if(this._isCLI&&!this._isOJET&&this._experimentalSet){dir=this._findCompositesDir(config.base);if(dir){config.components=[];config.components.push(this._nd.path.join(dir,COMPOSITES))}}}if(config.components){if(typeof config.components===TYPE_STRING){config.components=[config.components]}else if(!Array.isArray(config.components)){this._error("Config entry 'components' must be a string or an array of strings!");return false}for(i=0;i<config.components.length;i++){config.components[i]=config.components[i].trim();if(config.components[i].length===0){config.components.splice(i,1);i--}}}if(config.components&&config.components.length||config.componentUrls&&config.componentUrls.length){o=config.componentOptions;if(o){if(!this._utils.isObject(o)){this._error("Config 'components' sub-property 'componentOptions' must be an Object!");return false}t=typeof o.applySchema;if(t==="undefined"){o.applySchema=true}else if(t!=="boolean"){this._error("Config 'components' sub-property 'componentOptions' must be an Object!");return false}}}return true};CfgLib.prototype.processJetCorePack=function(){var config=this._config;var ret=true;if(!config.hasOwnProperty("jetCorePack")){return ret}let t=typeof config.jetCorePack;if(t===TYPE_BOOLEAN){if(config.jetCorePack){this._error("Config 'jetCorePack' property value cannot be boolean true!");ret=false}return ret}if(SemVer.lt(config.jetVer,"13.0.0")){this._error("Config 'jetCorePack' is valid for 'jetVer' values >= 13.0.0 only");ret=false}if(t!==TYPE_STRING){this._error("Config 'jetCorePack' property is not a string or a boolean!");ret=false}return ret};CfgLib.prototype.processTypeScript=function(){var ts,ret=true;if(this._config.hasOwnProperty("typescript")){ts=this._config.typescript;if(!this._utils.isObject(ts)){this._error("Config 'typescript' property is not an object!");ret=false}if(ts.hasOwnProperty("compile")){if(typeof ts.compile!=="boolean"){this._error("Config 'typescript' sub-property 'compile' is not a boolean!");ret=false}}if(ts.hasOwnProperty("tsconfig")){if(typeof ts.tsconfig!=="string"){this._error("Config 'typescript' sub-property 'tsconfig' must be a directory string!");ret=false}}}return ret};CfgLib.prototype.processRulePacks=function(){var packs,pack,i;var config=this._config;if(config.rulePacks){packs=this._config.rulePacks;if(!Array.isArray(packs)){this._error("Config entry 'rulePacks' is not an array!");return false}for(i=0;i<packs.length;i++){pack=packs[i];if(typeof pack!==TYPE_BOOLEAN){pack.enabled=true}if(!pack.path){this._error(`Config entry 'rulePacks' (entry ${i+1}) does not have a 'path' entry!`);return false}else{pack.path=pack.path.trim()}if(pack.status&&!Array.isArray(pack)){this._error(`Config entry 'rulePacks' (entry ${i+1}) 'status' property is not an array!`);return false}}}else{config.rulePacks=[]}return true};CfgLib.prototype.processRuleMods=function(cfg,fp){var mods,mod,val,rule;var config=cfg?cfg:this._config;const MSG="Config 'ruleMods' sub-property '${mod}' is not an array of rule names or group names";var self=this,b;if(!config.ruleMods){return true}function _emitRMError(s){s+=fp?` - in ${fp}`:"";self._error(s);b=true}mods=config.ruleMods;if(!this._utils.isObject(mods)){_emitRMError("Configuration property 'ruleMods' is not an object");return false}for(mod in mods){if(mod==="enabled"){_emitRMError("Config 'ruleMods' : invalid sub-property 'enabled' - did you mean 'enable'?")}else if(mod==="disabled"){_emitRMError("Config 'ruleMods' : invalid sub-property 'disabled' - did you mean 'disable'?")}if(b){return!b}val=mods[mod];if(mod==="enable"||mod==="disable"){if(!Array.isArray(val)){_emitRMError(this._utils.format(MSG,{mod:mod}))}if(!this._utils.isArrayContentsType(val,"string")){_emitRMError(this._utils.format(MSG,{mod:mod}))}}else{if(!this._utils.isObject(val)){_emitRMError(`Config 'ruleMods' sub-property '${mod}' is not an object!`)}else{for(rule in val){let o=val[rule];if(o.hasOwnProperty(ISSUE_TAG)){if(typeof o.issueTag!=="string"){_emitRMError(`Config 'ruleMods' for '${mod}' rule '${rule}' : '${ISSUE_TAG}' is not a string`)}}};}}}if(!b&&mods.enable&&mods.disable){mods.enable.forEach(function(r){if(mods.disable.includes(r)){_emitRMError(`Config 'ruleMods': 'enable' & 'disable' conflicting entry '${r}'`)}})}return!b};CfgLib.prototype.processFormat=function(){var config=this._config;if(config.format){if(config.format!=="json"&&config.format!=="prose"&&config.format!=="line"){this._error(`Config entry 'format' '${config.format}' not valid. Must be 'json', 'prose' or 'line'!`);return false}}return true};CfgLib.prototype.processProseFormat=function(){var config=this._config;if(config.proseFormat){if(typeof config.proseFormat==="string"){if(config.format!=="prose"){this._warn("Config entry 'proseFormat' ignored - not applicable if 'format is not 'prose'!")}}else{this._error(`Config entry 'proseFormat' '${config.proseFormat}' is not valid!`);return false}}return true};CfgLib.prototype.processLineFormat=function(){var config=this._config;if(config.lineFormat){if(typeof config.lineFormat==="string"){if(config.format!=="line"){this._warn("Config entry 'lineFormat' ignored - not applicable if 'format is not 'line'!")}}else{this._error(`Config entry 'lineFormat' '${config.lineFormat}' is not valid!`);return false}}return true};CfgLib.prototype.processRuleDescriptions=function(){var val,valType;var config=this._config;if(config.ruleDescriptions){val=config.ruleDescriptions;valType=typeof val;if(valType!=="string"||val!="all"&&val!=="short"&&val!=="long"&&val!=="none"){this._error(`Config entry 'ruleDescriptions' '${val}' is not valid!`);return false}}else{config.ruleDescriptions=DEF_RULE_DESCRIPT}return true};CfgLib.prototype.processRulesFired=function(){var config=this._config;if(config.rulesFired){if(!this._modeCtx.isAPI&&!this._modeCtx.isAMD&&(!config.format||config.format!=="json")){this._error(`Config entry 'rulesFired' - API/AMD mode required, or 'format' property set to 'json' for CLI mode!`);return false}}return true};CfgLib.prototype.processSevMap=function(){var config=this._config;var set,sev,msgs,inv,mapped,val,b,error;if(!config.sevMap){return true}set=config.sevMap.sevSet;if(set){b=error=false;for(val in set){if(!this._sevLib.isValidConfigSeverity(val)){this._error(`Config entry 'sevMap' sub-property 'sevSet' value '${val}' is not 'blocker/critical/major/minor/info'!`);error=true;continue}if(val==="all"){this._error("Config entry 'sevMap' sub-property 'sevSet' - pseudo severity 'all' cannot be remapped!");error=true;continue}if(typeof set[val]!=="string"){this._error(`Config entry 'sevMap' sub-property 'sevSet' value '${val}' is not a string!`);error=true;continue}b=true}if(error){return false}if(b){inv={};for(sev in set){mapped=set[sev];if(inv[mapped]){if(!Array.isArray(inv[mapped])){inv[mapped]=[inv[mapped]]}inv[mapped].push(sev)}else{inv[mapped]=sev}}this._sevLib.setSevMap(config.sevMap,inv)}else{config.sevMap.sevSet=null}}msgs=config.sevMap.sevMsg;if(msgs){if(!this._utils.isObject(msgs)){this._error("Config entry 'sevMap' sub-property 'sevMsg' is not an object!");return false}b=error=false;for(val in msgs){sev=msgs[val];if(typeof sev!=="string"){this._error(`Config entry 'sevMap' sub-property 'sevMsg' : '${val}' is not a string!`);error=true;continue}if(!this._sevLib.isSev(sev)){this._error(`Config entry 'sevMap' sub-property 'sevMsg' : '${sev}' is ${UNDEF}!`);error=true;continue}b=true}if(error){return false}if(b){this._sevLib.setSevMsg(msgs)}else{config.sevMap.sevMsg=null}}else{b=true;for(val in config.sevMap){if(val!=="sevSet"&&val!=="sevMsg"){this._error(`Config entry 'sevMap' unknown sub-property '${val}'!`);b=false}}if(!b){return false}}return true};CfgLib.prototype.processSeverity=function(cliSev){var config=this._config;var val,se,i;if(cliSev){config.severity=cliSev}if(config.severity){val=config.severity;if(typeof val==="string"){se=this._sevLib.getSevExpr(val);if(!this._sevLib.isValidConfigSeverity(val)){if(se.op&&se.sev==="all"){this._error(`Config entry 'severity' ('${val}') : 'all' cannot be used with a severity expression !`)}else if(cliSev){this._error(`command line --severity '${val}' is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`)}else{this._error(`Config entry 'severity' ('${val}') is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`)}return false}this._sevLib.setSevExpr(se)}else if(Array.isArray(val)&&this._utils.isArrayContentsType(val,"string")){for(i=0;i<val.length;i++){if(!this._sevLib.isValidConfigSeverity(val[i])){this._error(`Config entry 'severity' ('${val[i]}') is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`);return false}}}else{this._error("Config entry 'severity' is invalid!");return false}}else{config.severity=this._sevLib.ALL;this._sevLib.setSevExpr(this._sevLib.getSevExpr(this._sevLib.ALL))}return true};CfgLib.prototype.processGroups=function(cliGroups){var group,i;var config=this._config;if(cliGroups){config.groups=cliGroups}if(!config.groups){config.groups=DEF_GROUPS;return true}if(!Array.isArray(config.groups)){config.groups=[config.groups]}if(config.groups.length===0){config.groups.push("all")}else{for(i=0;i<config.groups.length;i++){group=config.groups[i];if(!GROUPS.isGroup(group)){if(group.startsWith("jet-")||group.startsWith("htm")){this._error(`Config 'groups' entry '${group}' is not defined!`);return false}}}}return true};CfgLib.prototype.processDefGroups=function(){var config=this._config;if(config.defGroups){if(!this._utils.isObject(config.defGroups)){this._error("Config entry 'defGroups' is not an object!");return false}}else{config.defGroups=null}return true};CfgLib.prototype.processRuleNames=function(){var config=this._config;if(config.ruleNames){if(!Array.isArray(config.ruleNames)){this._error("Config entry 'ruleNames' is not an array!");return false}}return true};CfgLib.prototype.processTheme=function(){var t,config=this._config;t=config.theme;if(t){t=t.toLowerCase();if(typeof t==="string"){if(!THEMES.includes(t)){this._error(`Invalid config theme '${t}' : must be 'Redwood', 'Alta', 'Stable' or 'none'`);return false}}else{this._error("Config entry 'theme' is not a string!");return false}if(t==="stable"){t="redwood"};config.theme=t.charAt(0).toUpperCase()+t.substring(1)}else{config.theme=SemVer.gte(config.jetVer,"12.0.0")?"Redwood":DEFAULTS.THEME;if(this._isVerbose){this._info(`[Info]: Default theme '${config.theme}' applied for jetVer ${config.jetVer}`)}}return true};CfgLib.prototype.processComments=function(){var t,config=this._config;t=typeof config.comments;if(t===UNDEF){config.comments=DEF_COMMENTS}else if(t!=="boolean"){this._error("Invalid 'comments' property - expected a boolean");return false}return true};CfgLib.prototype.processMarkdownOpts=function(){var config=this._config;var val=config.markdownOptions;var t=typeof val;if(t===UNDEF){config.markdownOptions={linkify:true}}else if(Array.isArray(val)||t!=="object"){this._error("Invalid 'markdownOptions' property - expected an object");return false}else{t=typeof val.linkify;if(t==="undefined"){val.linkify=true}else if(typeof val.linkify!=="boolean"){this._error("Invalid 'markdownOptions.linkify' - expected a boolean");return false}let n=Object.keys(val);if(!val.hasOwnProperty("linkify")){if(n.length){this._error("Invalid 'markdownOptions.linkify' - expected a boolean");return false}else{val.linkify=true}}else if(n.length>1){this._error("Invalid 'markdownOptions' properties found");return false}}return true};CfgLib.prototype.processEcmaVer=function(){var val,config=this._config;if(config.ecmaVer){val=config.ecmaVer;if(typeof val==="string"){if(val.substring(0,2).toLowerCase()==="es"){val=val.substring(2)}val=parseInt(val);if(isNaN(val)){val=0}}if(typeof val===NUMBER){if(!(ECMA_VER.includes(val)||ECMA_YEAR.includes(val))){this._error(`Config 'ecmaVer: ${config.ecmaVer}' is not in the version range ${ECMA_VER[0]}-${ECMA_VER[ECMA_VER.length-1]} or the year range ${ECMA_YEAR[1]}-${ECMA_YEAR[ECMA_YEAR.length-1]}!`);return false}}if(val>=2015){val=ECMA_YEAR.indexOf(val);config.ecmaVer=ECMA_VER[val]}else{config.ecmaVer=val}}else{config.ecmaVer=DEFAULTS.ECMAVER}return true};CfgLib.prototype.processMessages=function(){var val,config=this._config;if(config.messages){val=config.messages;if(!this._utils.isObject(val)){this._error("Config entry 'messages' is not an object!");return false}if(val.accept&&val.reject){this._error("Config entry 'messages' - 'accept' and 'reject' are mutually exclusive!");return false}if(val.accept){if(!Array.isArray(val.accept)){this._error("Config entry 'messages.accept' is not an array!");return false}else if(!this._utils.isArrayContentsType(val.accept,"string")){this._error("Config entry 'messages.accept' property array does not contain all strings");return false}}if(val.reject){if(!Array.isArray(val.reject)){this._error("Config entry 'messages.reject' is not an array!");return false}else if(!this._utils.isArrayContentsType(val.reject,"string")){this._error("Config entry 'messages.reject' property array does not contain all strings");return false}}}return true};CfgLib.prototype.processAddFileList=function(){var config=this._config;if(config.appendFileList){this._appendFileList=true;this._warn("Configuration property 'appendFileList' : change to 'addFileList'")}else if(config.addFileList){this._addFileList=true}return true};CfgLib.prototype.processNameSpaces=function(){var config,nsp,ns,e;config=this._config;if(!config.nameSpaces){return true}if(!Array.isArray(config.nameSpaces)){config.nameSpaces=[config.nameSpaces]}nsp=config.nameSpaces;for(let i=0;i<nsp.length;i++){ns=nsp[i];if(!ns||typeof ns!=="string"){this._error(`Config 'nameSpaces' entry "${ns}" at index ${i} is not a valid namespace`);e=true}else if(ns.startsWith("oj-")||ns.startsWith("ns-")){this._error(`Config 'nameSpaces' entry '${ns}' must not use reserved JET prefix ${ns.substring(0,3)}`);e=true}}return e?false:true};CfgLib.prototype.processOptions=function(){var prop,opts,config=this._config,isCLI=this._modeCtx.isCLI||this._modeCtx.isOJETCLI;if(config.options){opts=config.options;for(prop in opts){if(!OPTIONS_PROPS.includes(prop)){this._error(`Config - unknown 'options' sub-property '${prop}'`);return false}else if((prop==="retCode"||prop==="rc")&&!isCLI){this._error(`Config - 'options' property '${prop}' is valid in CLI mode only`);return false}}}return true};CfgLib.prototype.processExtends=function(){var config=this._config;var ext;if(this._modeCtx.isAMD){if(ext=config.extends){if(typeof ext==="string"){this._error("Config use of non-profile 'extends' property is not supported in AMD mode.");return false}}if(config.extendOptions){this._error("Config use of 'extendOptions' property is not supported in AMD mode.");return false}}if(this._config.extendOptions){if(!this._utils.isObject(this._config.extendOptions)){this._error("Config 'extendOptions' is not an object.");return false}}var extLib=new this._nd.extends(this,this._oConfig,config,this._path,this._nd,this._msgCtx,this._utils,this._fsUtils,this._modeCtx.isAMD);var cfg=extLib.extend();return cfg};CfgLib.prototype.processTitle=function(){var t,config=this._config;if(config.title){t=this._utils.getType(config.title);if(t!=="string"&&t!=="array"){this._error(`Config entry 'title has incorrect type ('${t}')`);return false}}return true};CfgLib.prototype.processRetCode=function(){var rc,prop,ret,config=this._config;if(config.options){prop=typeof config.options.retCode!==UNDEF?"retCode":typeof config.options.rc!==UNDEF?"rc":null;if(prop){rc=config.options[prop];ret=this.validateRetCode(rc,sev=>{this._error(`Config entry 'options.${prop}' : unknown severity '${sev}'`)});if(ret||typeof ret==="number"){config.options[prop]=ret}else{config.options[prop]=AUTO;return false}}}if(!prop){if(!config.options){config.options={}}config.options.retCode=DEF_RETCODE}return true};CfgLib.prototype.validateFileList=function(aFiles){var i,j,f,msg,ret=true;;for(i=0;i<aFiles.length;i++){f=aFiles[i];if(typeof f==="string"){continue}if(!this._utils.isObject(f)){msg=" property entry "+(i+1)+" is not a string or an object";break}if(f.files){if(!(Array.isArray(f.files)&&this._utils.isArrayContentsType(f.files,"string"))){msg=" property entry "+(i+1)+" does not contain a 'files' property array, or not all elements are strings";break}}else{msg=" property entry "+(i+1)+", does not contain a 'files' property";break}if(!f.base){msg=" property entry "+(i+1)+" does not contain a 'base' property";break}for(j=0;j<f.files.length;j++){f.files[j]=this._nd.path.join(f.base,f.files[j])}}if(!msg){for(i=0;i<aFiles.length;i++){f=aFiles[i];if(this._utils.isObject(f)){aFiles.splice(i,1,...f.files)}}}if(msg){this._error(msg);ret=false}return ret};CfgLib.prototype.validateRetCode=function(val,cb){var t,i,b;t=typeof val;if(t==="number"||t==="string"&&val===DEF_RETCODE||val===ERRORS){return val}if(t==="string"){if(!this._sevLib.isSev(val)){cb(val);return false}else{return this._sevLib.unmap(val)}}if(Array.isArray(val)){b=true;for(i=0;i<val.length;i++){if(!this._sevLib.isSev(val[i])){cb(val[i]);b=false}else{val[i]=this._sevLib.unmap(val[i])}}if(b){for(i=0;i<val.length;i++){if(Array.isArray(val[i])){let ar=[];for(i=0;i<val.length;i++){ar=ar.concat(val[i])}val=ar;break}}return val}}return false};CfgLib.prototype.setMessages=function(msgid,state){var accept,reject,msgs,target,changed=false,i;var config=this._config;msgs=config.messages;state=!!state;if(!msgs){if(!state){config.messages={reject:[msgid]};changed=true}}else{reject=msgs.reject;accept=msgs.accept;target=accept||reject;i=target?target.indexOf(msgid):-1;if(state){if(!accept&&!reject){msgs.accept=accept=[]}if(reject){if(i>=0){reject.splice(i,1);changed=true;if(reject.length===0){delete msgs.reject}}}else if(accept){if(i<0){accept.push(msgid);changed=true}}}else{if(!accept&&!reject){msgs.reject=reject=[]}if(reject){if(i<0){reject.push(msgid);changed=true}}else if(accept){if(i>=0){accept.splice(i,1);if(accept.length===0){delete msgs.accept}changed=true}}}}return changed};CfgLib.prototype.getAddFileList=function(){return!!(this._addFileList||this._appendFileList)};CfgLib.prototype.checkPropNames=function(cfg,path){var prop,ret=true,config=cfg?cfg:this._config;path=path||this._path;for(prop in config){if(!TOP_PROPS.includes(prop)){if(prop.charAt(0)==="_"){delete config[prop];continue}this._error(`Config - unknown property '${prop}' ${path?"- "+path:""}`);ret=false}else if(this._modeCtx.isAMD&&NOT_AMD.includes(prop)){this._error(`Config - property '${prop}' is not available in AMD mode!`);ret=false}}return ret};CfgLib.prototype.setConfig=function(cfg,cfgPath,dir){this._config=cfg;this._path=cfgPath;this._dir=dir};CfgLib.prototype._findCompositesDir=function(base){return this._fsUtils.findFile(base,COMPOSITES)};module.exports=CfgLib;
|
|
6
|
+
const GROUPS=require("./groups");const DEFAULTS=require("./defaults");const SemVer=require("semver");const COMPOSITES="jet-composites";const TYPE_STRING="string";const TYPE_BOOLEAN="boolean";const AUTO="auto";const ERRORS="errors";const UNDEF="undefined";const NUMBER="number";const TOP_PROPS=["rulePacks","ruleMods","builtinJetRules","builtinCspRules","builtinSpocRules","builtinJetWcRules","builtinJetWcOracleRules","builtinOjcMigrationRules","builtinWebDriverTestRules","severity","groups","defGroups","ruleNames","base","files","exclude","typescript","jetPagesOnly","format","proseFormat","lineFormat","outPath","tabs","messages","addFileList","title","jetVer","components","componentUrls","componentOptions","jetCorePack","markdownOptions","stylesets","ecmaVer","ruleDescriptions","rulesFired","userDefs","options","comments","extends","extendOptions","nameSpaces","followLinks","tempDir","tokens","common","$JetCore","sevMap","theme","ojet","appendFileList"];const NOT_AMD=["addFileList","base","builtinJetWcRules","builtinJetWcOracleRules","builtinOjcMigrationRules","builtinWebDriverTestRules","components","componentOptions","componentUrls","extendOptions","files","exclude","followLinks","outPath","rulePacks","tempDir","tokens","typescript"];const OPTIONS_PROPS=["debug","verbose","color","msgid","ruleName","retCode","rc","ojetUpdate","experimental","$unittest"];const THEMES=["redwood","alta","stable","none"];const DEF_COMMENTS=false;const DEF_RULE_DESCRIPT="none";const DEF_GROUPS=["all"];const DEF_RETCODE="auto";const ISSUE_TAG="issueTag";const ECMA_VER=[5,6,7,8,9,10,11,12,13,14];const ECMA_YEAR=[-1,2015,2016,2017,2018,2019,2020,2021,2022,2023];function CfgLib(oConfig,nodeDeps,sevLib,utils,fsUtils,msgCtx,modeCtx){this._oConfig=oConfig;this._config=null;this._dir=null;this._sevLib=sevLib;this._utils=utils;this._fsUtils=fsUtils;this._nd=nodeDeps;this._msgCtx=msgCtx;this._modeCtx=modeCtx;this._isVerbose=msgCtx.isVerbose;this._isCLI=modeCtx.isCLI||modeCtx.isOJETCLI;this._error=msgCtx.error;this._warn=msgCtx.warn;this._info=msgCtx.info};CfgLib.prototype.setDebugStatus=function(verbose,debug){this._isVerbose=this._msgCtx.isVerbose=verbose};CfgLib.prototype.processWebComponents=function(){var dir,o,t,i;var config=this._config;if(config.componentUrlBase){if(!typeof config.componentUrlBase===TYPE_STRING){this._error("Config entry 'componentUrlBase' must be a string!");return false}}if(config.componentUrls){if(typeof config.componentUrls===TYPE_STRING){config.componentUrls=[config.componentUrls]}else if(!Array.isArray(config.componentUrls)){this._error("Config entry 'componentUrls' must be a string or an aray of strings!");return false}for(i=0;i<this._config.componentUrls.length;i++){config.componentUrls[i]=config.componentUrls[i].trim();if(config.componentUrls[i].length===0){config.componentUrls.splice(i,1);i--}}}if(!config.components){if(this._isCLI&&!this._isOJET&&this._experimentalSet){dir=this._findCompositesDir(config.base);if(dir){config.components=[];config.components.push(this._nd.path.join(dir,COMPOSITES))}}}if(config.components){if(typeof config.components===TYPE_STRING){config.components=[config.components]}else if(!Array.isArray(config.components)){this._error("Config entry 'components' must be a string or an array of strings!");return false}for(i=0;i<config.components.length;i++){config.components[i]=config.components[i].trim();if(config.components[i].length===0){config.components.splice(i,1);i--}}}if(config.components&&config.components.length||config.componentUrls&&config.componentUrls.length){o=config.componentOptions;if(o){if(!this._utils.isObject(o)){this._error("Config 'components' sub-property 'componentOptions' must be an Object!");return false}t=typeof o.applySchema;if(t==="undefined"){o.applySchema=true}else if(t!=="boolean"){this._error("Config 'components' sub-property 'componentOptions' must be an Object!");return false}}}return true};CfgLib.prototype.processJetCorePack=function(){var config=this._config;var ret=true;if(!config.hasOwnProperty("jetCorePack")){return ret}let t=typeof config.jetCorePack;if(t===TYPE_BOOLEAN){if(config.jetCorePack){this._error("Config 'jetCorePack' property value cannot be boolean true!");ret=false}return ret}if(SemVer.lt(config.jetVer,"13.0.0")){this._error("Config 'jetCorePack' is valid for 'jetVer' values >= 13.0.0 only");ret=false}if(t!==TYPE_STRING){this._error("Config 'jetCorePack' property is not a string or a boolean!");ret=false}return ret};CfgLib.prototype.processTypeScript=function(){var ts,ret=true;if(this._config.hasOwnProperty("typescript")){ts=this._config.typescript;if(!this._utils.isObject(ts)){this._error("Config 'typescript' property is not an object!");ret=false}if(ts.hasOwnProperty("compile")){if(typeof ts.compile!=="boolean"){this._error("Config 'typescript' sub-property 'compile' is not a boolean!");ret=false}}if(ts.hasOwnProperty("tsconfig")){if(typeof ts.tsconfig!=="string"){this._error("Config 'typescript' sub-property 'tsconfig' must be a directory string!");ret=false}}}return ret};CfgLib.prototype.processRulePacks=function(){var packs,pack,i;var config=this._config;if(config.rulePacks){packs=this._config.rulePacks;if(!Array.isArray(packs)){this._error("Config entry 'rulePacks' is not an array!");return false}for(i=0;i<packs.length;i++){pack=packs[i];if(typeof pack!==TYPE_BOOLEAN){pack.enabled=true}if(!pack.path){this._error(`Config entry 'rulePacks' (entry ${i+1}) does not have a 'path' entry!`);return false}else{pack.path=pack.path.trim()}if(pack.status&&!Array.isArray(pack)){this._error(`Config entry 'rulePacks' (entry ${i+1}) 'status' property is not an array!`);return false}}}else{config.rulePacks=[]}return true};CfgLib.prototype.processRuleMods=function(cfg,fp){var mods,mod,val,rule;var config=cfg?cfg:this._config;const MSG="Config 'ruleMods' sub-property '${mod}' is not an array of rule names or group names";var self=this,b;if(!config.ruleMods){return true}function _emitRMError(s){s+=fp?` - in ${fp}`:"";self._error(s);b=true}mods=config.ruleMods;if(!this._utils.isObject(mods)){_emitRMError("Configuration property 'ruleMods' is not an object");return false}for(mod in mods){if(mod==="enabled"){_emitRMError("Config 'ruleMods' : invalid sub-property 'enabled' - did you mean 'enable'?")}else if(mod==="disabled"){_emitRMError("Config 'ruleMods' : invalid sub-property 'disabled' - did you mean 'disable'?")}if(b){return!b}val=mods[mod];if(mod==="enable"||mod==="disable"){if(!Array.isArray(val)){_emitRMError(this._utils.format(MSG,{mod:mod}))}if(!this._utils.isArrayContentsType(val,"string")){_emitRMError(this._utils.format(MSG,{mod:mod}))}}else{if(!this._utils.isObject(val)){_emitRMError(`Config 'ruleMods' sub-property '${mod}' is not an object!`)}else{for(rule in val){let o=val[rule];if(o.hasOwnProperty(ISSUE_TAG)){if(typeof o.issueTag!=="string"){_emitRMError(`Config 'ruleMods' for '${mod}' rule '${rule}' : '${ISSUE_TAG}' is not a string`)}}};}}}if(!b&&mods.enable&&mods.disable){mods.enable.forEach(function(r){if(mods.disable.includes(r)){_emitRMError(`Config 'ruleMods': 'enable' & 'disable' conflicting entry '${r}'`)}})}return!b};CfgLib.prototype.processFormat=function(){var config=this._config;if(config.format){if(config.format!=="json"&&config.format!=="prose"&&config.format!=="line"){this._error(`Config entry 'format' '${config.format}' not valid. Must be 'json', 'prose' or 'line'!`);return false}}return true};CfgLib.prototype.processProseFormat=function(){var config=this._config;if(config.proseFormat){if(typeof config.proseFormat==="string"){if(config.format!=="prose"){this._warn("Config entry 'proseFormat' ignored - not applicable if 'format is not 'prose'!")}}else{this._error(`Config entry 'proseFormat' '${config.proseFormat}' is not valid!`);return false}}return true};CfgLib.prototype.processLineFormat=function(){var config=this._config;if(config.lineFormat){if(typeof config.lineFormat==="string"){if(config.format!=="line"){this._warn("Config entry 'lineFormat' ignored - not applicable if 'format is not 'line'!")}}else{this._error(`Config entry 'lineFormat' '${config.lineFormat}' is not valid!`);return false}}return true};CfgLib.prototype.processRuleDescriptions=function(){var val,valType;var config=this._config;if(config.ruleDescriptions){val=config.ruleDescriptions;valType=typeof val;if(valType!=="string"||val!="all"&&val!=="short"&&val!=="long"&&val!=="none"){this._error(`Config entry 'ruleDescriptions' '${val}' is not valid!`);return false}}else{config.ruleDescriptions=DEF_RULE_DESCRIPT}return true};CfgLib.prototype.processRulesFired=function(){var config=this._config;if(config.rulesFired){if(!this._modeCtx.isAPI&&!this._modeCtx.isAMD&&(!config.format||config.format!=="json")){this._error(`Config entry 'rulesFired' - API/AMD mode required, or 'format' property set to 'json' for CLI mode!`);return false}}return true};CfgLib.prototype.processSevMap=function(){var config=this._config;var set,sev,msgs,inv,mapped,val,b,error;if(!config.sevMap){return true}set=config.sevMap.sevSet;if(set){b=error=false;for(val in set){if(!this._sevLib.isValidConfigSeverity(val)){this._error(`Config entry 'sevMap' sub-property 'sevSet' value '${val}' is not 'blocker/critical/major/minor/info'!`);error=true;continue}if(val==="all"){this._error("Config entry 'sevMap' sub-property 'sevSet' - pseudo severity 'all' cannot be remapped!");error=true;continue}if(typeof set[val]!=="string"){this._error(`Config entry 'sevMap' sub-property 'sevSet' value '${val}' is not a string!`);error=true;continue}b=true}if(error){return false}if(b){inv={};for(sev in set){mapped=set[sev];if(inv[mapped]){if(!Array.isArray(inv[mapped])){inv[mapped]=[inv[mapped]]}inv[mapped].push(sev)}else{inv[mapped]=sev}}this._sevLib.setSevMap(config.sevMap,inv)}else{config.sevMap.sevSet=null}}msgs=config.sevMap.sevMsg;if(msgs){if(!this._utils.isObject(msgs)){this._error("Config entry 'sevMap' sub-property 'sevMsg' is not an object!");return false}b=error=false;for(val in msgs){sev=msgs[val];if(typeof sev!=="string"){this._error(`Config entry 'sevMap' sub-property 'sevMsg' : '${val}' is not a string!`);error=true;continue}if(!this._sevLib.isSev(sev)){this._error(`Config entry 'sevMap' sub-property 'sevMsg' : '${sev}' is ${UNDEF}!`);error=true;continue}b=true}if(error){return false}if(b){this._sevLib.setSevMsg(msgs)}else{config.sevMap.sevMsg=null}}else{b=true;for(val in config.sevMap){if(val!=="sevSet"&&val!=="sevMsg"){this._error(`Config entry 'sevMap' unknown sub-property '${val}'!`);b=false}}if(!b){return false}}return true};CfgLib.prototype.processSeverity=function(cliSev){var config=this._config;var val,se,i;if(cliSev){config.severity=cliSev}if(config.severity){val=config.severity;if(typeof val==="string"){se=this._sevLib.getSevExpr(val);if(!this._sevLib.isValidConfigSeverity(val)){if(se.op&&se.sev==="all"){this._error(`Config entry 'severity' ('${val}') : 'all' cannot be used with a severity expression !`)}else if(cliSev){this._error(`command line --severity '${val}' is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`)}else{this._error(`Config entry 'severity' ('${val}') is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`)}return false}this._sevLib.setSevExpr(se)}else if(Array.isArray(val)&&this._utils.isArrayContentsType(val,"string")){for(i=0;i<val.length;i++){if(!this._sevLib.isValidConfigSeverity(val[i])){this._error(`Config entry 'severity' ('${val[i]}') is not 'major/minor/blocker/critical/info', 'all', or a remapped severity!`);return false}}}else{this._error("Config entry 'severity' is invalid!");return false}}else{config.severity=this._sevLib.ALL;this._sevLib.setSevExpr(this._sevLib.getSevExpr(this._sevLib.ALL))}return true};CfgLib.prototype.processGroups=function(cliGroups){var group,i;var config=this._config;if(cliGroups){config.groups=cliGroups}if(!config.groups){config.groups=DEF_GROUPS;return true}if(!Array.isArray(config.groups)){config.groups=[config.groups]}if(config.groups.length===0){config.groups.push("all")}else{for(i=0;i<config.groups.length;i++){group=config.groups[i];if(!GROUPS.isGroup(group)){if(group.startsWith("jet-")||group.startsWith("htm")){this._error(`Config 'groups' entry '${group}' is not defined!`);return false}}}}return true};CfgLib.prototype.processDefGroups=function(){var config=this._config;if(config.defGroups){if(!this._utils.isObject(config.defGroups)){this._error("Config entry 'defGroups' is not an object!");return false}}else{config.defGroups=null}return true};CfgLib.prototype.processRuleNames=function(){var config=this._config;if(config.ruleNames){if(!Array.isArray(config.ruleNames)){this._error("Config entry 'ruleNames' is not an array!");return false}}return true};CfgLib.prototype.processTheme=function(){var t,config=this._config;t=config.theme;if(t){t=t.toLowerCase();if(typeof t==="string"){if(!THEMES.includes(t)){this._error(`Invalid config theme '${t}' : must be 'Redwood', 'Alta', 'Stable' or 'none'`);return false}}else{this._error("Config entry 'theme' is not a string!");return false}if(t==="stable"){t="redwood"};config.theme=t.charAt(0).toUpperCase()+t.substring(1)}else{config.theme=SemVer.gte(config.jetVer,"12.0.0")?"Redwood":DEFAULTS.THEME;if(this._isVerbose){this._info(`[Info]: Default theme '${config.theme}' applied for jetVer ${config.jetVer}`)}}return true};CfgLib.prototype.processComments=function(){var t,config=this._config;t=typeof config.comments;if(t===UNDEF){config.comments=DEF_COMMENTS}else if(t!=="boolean"){this._error("Invalid 'comments' property - expected a boolean");return false}return true};CfgLib.prototype.processMarkdownOpts=function(){var config=this._config;var val=config.markdownOptions;var t=typeof val;if(t===UNDEF){config.markdownOptions={linkify:true}}else if(Array.isArray(val)||t!=="object"){this._error("Invalid 'markdownOptions' property - expected an object");return false}else{t=typeof val.linkify;if(t==="undefined"){val.linkify=true}else if(typeof val.linkify!=="boolean"){this._error("Invalid 'markdownOptions.linkify' - expected a boolean");return false}let n=Object.keys(val);if(!val.hasOwnProperty("linkify")){if(n.length){this._error("Invalid 'markdownOptions.linkify' - expected a boolean");return false}else{val.linkify=true}}else if(n.length>1){this._error("Invalid 'markdownOptions' properties found");return false}}return true};CfgLib.prototype.processEcmaVer=function(){var val,config=this._config;if(config.ecmaVer){val=config.ecmaVer;if(typeof val==="string"){if(val.substring(0,2).toLowerCase()==="es"){val=val.substring(2)}val=parseInt(val);if(isNaN(val)){val=0}}if(typeof val===NUMBER){if(!(ECMA_VER.includes(val)||ECMA_YEAR.includes(val))){this._error(`Config 'ecmaVer: ${config.ecmaVer}' is not in the version range ${ECMA_VER[0]}-${ECMA_VER[ECMA_VER.length-1]} or the year range ${ECMA_YEAR[1]}-${ECMA_YEAR[ECMA_YEAR.length-1]}!`);return false}}if(val>=2015){val=ECMA_YEAR.indexOf(val);config.ecmaVer=ECMA_VER[val]}else{config.ecmaVer=val}}else{config.ecmaVer=DEFAULTS.ECMAVER}return true};CfgLib.prototype.processMessages=function(){var val,config=this._config;if(config.messages){val=config.messages;if(!this._utils.isObject(val)){this._error("Config entry 'messages' is not an object!");return false}if(val.accept&&val.reject){this._error("Config entry 'messages' - 'accept' and 'reject' are mutually exclusive!");return false}if(val.accept){if(!Array.isArray(val.accept)){this._error("Config entry 'messages.accept' is not an array!");return false}else if(!this._utils.isArrayContentsType(val.accept,"string")){this._error("Config entry 'messages.accept' property array does not contain all strings");return false}}if(val.reject){if(!Array.isArray(val.reject)){this._error("Config entry 'messages.reject' is not an array!");return false}else if(!this._utils.isArrayContentsType(val.reject,"string")){this._error("Config entry 'messages.reject' property array does not contain all strings");return false}}}return true};CfgLib.prototype.processAddFileList=function(){var config=this._config;if(config.appendFileList){this._appendFileList=true;this._warn("Configuration property 'appendFileList' : change to 'addFileList'")}else if(config.addFileList){this._addFileList=true}return true};CfgLib.prototype.processNameSpaces=function(){var config,nsp,ns,e;config=this._config;if(!config.nameSpaces){return true}if(!Array.isArray(config.nameSpaces)){config.nameSpaces=[config.nameSpaces]}nsp=config.nameSpaces;for(let i=0;i<nsp.length;i++){ns=nsp[i];if(!ns||typeof ns!=="string"){this._error(`Config 'nameSpaces' entry "${ns}" at index ${i} is not a valid namespace`);e=true}else if(ns.startsWith("oj-")||ns.startsWith("ns-")){this._error(`Config 'nameSpaces' entry '${ns}' must not use reserved JET prefix ${ns.substring(0,3)}`);e=true}}return e?false:true};CfgLib.prototype.processOptions=function(){var prop,opts,config=this._config,isCLI=this._modeCtx.isCLI||this._modeCtx.isOJETCLI;if(config.options){opts=config.options;for(prop in opts){if(!OPTIONS_PROPS.includes(prop)){this._error(`Config - unknown 'options' sub-property '${prop}'`);return false}else if((prop==="retCode"||prop==="rc")&&!isCLI){this._error(`Config - 'options' property '${prop}' is valid in CLI mode only`);return false}}}return true};CfgLib.prototype.processExtends=function(){var config=this._config;var ext;if(this._modeCtx.isAMD){if(ext=config.extends){if(typeof ext==="string"){this._error("Config use of non-profile 'extends' property is not supported in AMD mode.");return false}}if(config.extendOptions){this._error("Config use of 'extendOptions' property is not supported in AMD mode.");return false}}if(this._config.extendOptions){if(!this._utils.isObject(this._config.extendOptions)){this._error("Config 'extendOptions' is not an object.");return false}}var extLib=new this._nd.extends(this,this._oConfig,config,this._path,this._nd,this._msgCtx,this._utils,this._fsUtils,this._modeCtx.isAMD);var cfg=extLib.extend();return cfg};CfgLib.prototype.processTitle=function(){var t,config=this._config;if(config.title){t=this._utils.getType(config.title);if(t!=="string"&&t!=="array"){this._error(`Config entry 'title has incorrect type ('${t}')`);return false}}return true};CfgLib.prototype.processRetCode=function(){var rc,prop,ret,config=this._config;if(config.options){prop=typeof config.options.retCode!==UNDEF?"retCode":typeof config.options.rc!==UNDEF?"rc":null;if(prop){rc=config.options[prop];ret=this.validateRetCode(rc,sev=>{this._error(`Config entry 'options.${prop}' : unknown severity '${sev}'`)});if(ret||typeof ret==="number"){config.options[prop]=ret}else{config.options[prop]=AUTO;return false}}}if(!prop){if(!config.options){config.options={}}config.options.retCode=DEF_RETCODE}return true};CfgLib.prototype.validateFileList=function(aFiles){var i,j,f,msg,ret=true;;for(i=0;i<aFiles.length;i++){f=aFiles[i];if(typeof f==="string"){continue}if(!this._utils.isObject(f)){msg=" property entry "+(i+1)+" is not a string or an object";break}if(f.files){if(!(Array.isArray(f.files)&&this._utils.isArrayContentsType(f.files,"string"))){msg=" property entry "+(i+1)+" does not contain a 'files' property array, or not all elements are strings";break}}else{msg=" property entry "+(i+1)+", does not contain a 'files' property";break}if(!f.base){msg=" property entry "+(i+1)+" does not contain a 'base' property";break}for(j=0;j<f.files.length;j++){f.files[j]=this._nd.path.join(f.base,f.files[j])}}if(!msg){for(i=0;i<aFiles.length;i++){f=aFiles[i];if(this._utils.isObject(f)){aFiles.splice(i,1,...f.files)}}}if(msg){this._error(msg);ret=false}return ret};CfgLib.prototype.validateRetCode=function(val,cb){var t,i,b;t=typeof val;if(t==="number"||t==="string"&&val===DEF_RETCODE||val===ERRORS){return val}if(t==="string"){if(!this._sevLib.isSev(val)){cb(val);return false}else{return this._sevLib.unmap(val)}}if(Array.isArray(val)){b=true;for(i=0;i<val.length;i++){if(!this._sevLib.isSev(val[i])){cb(val[i]);b=false}else{val[i]=this._sevLib.unmap(val[i])}}if(b){for(i=0;i<val.length;i++){if(Array.isArray(val[i])){let ar=[];for(i=0;i<val.length;i++){ar=ar.concat(val[i])}val=ar;break}}return val}}return false};CfgLib.prototype.setMessages=function(msgid,state){var accept,reject,msgs,target,changed=false,i;var config=this._config;msgs=config.messages;state=!!state;if(!msgs){if(!state){config.messages={reject:[msgid]};changed=true}}else{reject=msgs.reject;accept=msgs.accept;target=accept||reject;i=target?target.indexOf(msgid):-1;if(state){if(!accept&&!reject){msgs.accept=accept=[]}if(reject){if(i>=0){reject.splice(i,1);changed=true;if(reject.length===0){delete msgs.reject}}}else if(accept){if(i<0){accept.push(msgid);changed=true}}}else{if(!accept&&!reject){msgs.reject=reject=[]}if(reject){if(i<0){reject.push(msgid);changed=true}}else if(accept){if(i>=0){accept.splice(i,1);if(accept.length===0){delete msgs.accept}changed=true}}}}return changed};CfgLib.prototype.getAddFileList=function(){return!!(this._addFileList||this._appendFileList)};CfgLib.prototype.checkPropNames=function(cfg,path){var prop,ret=true,config=cfg?cfg:this._config;path=path||this._path;for(prop in config){if(!TOP_PROPS.includes(prop)){if(prop.charAt(0)==="_"){delete config[prop];continue}this._error(`Config - unknown property '${prop}' ${path?"- "+path:""}`);ret=false}else if(this._modeCtx.isAMD&&NOT_AMD.includes(prop)){this._error(`Config - property '${prop}' is not available in AMD mode!`);ret=false}}return ret};CfgLib.prototype.setConfig=function(cfg,cfgPath,dir){this._config=cfg;this._path=cfgPath;this._dir=dir};CfgLib.prototype._findCompositesDir=function(base){return this._fsUtils.findFile(base,COMPOSITES)};module.exports=CfgLib;
|
package/lib/DomUtils.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 jsonParser=require('really-relaxed-json').createParser();const HtmlUtils=require('./HtmlUtils');const NodeType=require('./NodeTypes');const OJCOMPONENT='ojComponent';const COMPONENT='component';const DOT='.';const ON_DASH='on-';function DomUtils(nodeDeps,appContext,oTabs,fileIndex){this._tree=null;this._nodeDeps=nodeDeps;this._appContext=appContext;this._tabs=oTabs;this._utils=appContext.utils;this._fileIndex=fileIndex};DomUtils.prototype.getFirst=function(){return this._tree.length?this._tree[0]:null};DomUtils.prototype.getLast=function(){var node;node=this._tree.length?this._tree[this._tree.length-1]:null;while(node&&node.children&&node.children.length){node=node.children[node.children.length-1]}return node};DomUtils.prototype.getFirstElem=function(){var node=this.getFirst();while(node){if(node.type===NodeType.TAG){break};node=node.next}return node};DomUtils.prototype.getChildren=function(node){return node.children};DomUtils.prototype.getParent=function(node){return node.parent};DomUtils.prototype.getSiblings=function(node){var parent;if(parent=this.getParent(node)){return this.getChildren(parent)}else{return this._tree}};DomUtils.prototype.getNext=function(node){return node.next||null};DomUtils.prototype.getAttribs=function(node){return node.attribs||null};DomUtils.prototype.getAttribValue=function(node,name){return node.attribs?node.attribs[name]:undefined};DomUtils.prototype.getAttribRawValue=function(ruleCtx,name){var val,pos;if(ruleCtx.tagNode.attribs){if(typeof(val=ruleCtx.tagNode.attribs[name])==='string'){pos=this.getAttrPosition(ruleCtx.data,ruleCtx.tagNode,name);return _getAttrRawValue(ruleCtx.data,pos.start,name,val,ruleCtx.utils.utils)}}};DomUtils.prototype.hasAttrib=function(node,name){return!!node.attribs&&hasOwnProperty.call(node.attribs,name)};DomUtils.prototype.hasChildren=function(node){return!!node.children};DomUtils.prototype.hasNext=function(node){return!!node.next};DomUtils.prototype.getName=function(node){return node.name};DomUtils.prototype.getType=function(node){return node.type};DomUtils.prototype.getElemsByName=function(name){var a=[],i,names;if(!this._tree){return a}names=typeof name==='string'?[name]:name;for(i=0;i<names.length;i++){names[i]=names[i].toLowerCase()}for(i=0;i<this._tree.length;i++){_getElemsByName2(this._tree[i],a,names)}return a};function _getElemsByName2(node,a,names){var children,i;if((node.type===NodeType.TAG||node.type===NodeType.SCRIPT)&&names.indexOf(node.name.toLowerCase())>=0){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){_getElemsByName2(children[i],a,names)}}};DomUtils.prototype.getElemById=function(id,labelId){var node,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){node=this._tree[i];if(node.type===NodeType.TAG||_isHtmlScript(node)){node=this._getElemById2(node,id,labelId);if(node){return node}}}return null};DomUtils.prototype._getElemById2=function(node,id,labelId){var curNode,attrib,attr,attribLower,i;if((node.type===NodeType.TAG||_isHtmlScript(node))&&node.attribs){for(attrib in node.attribs){attribLower=attrib.toLowerCase();if(attribLower==='id'||labelId&&attribLower==='label-id'){if(node.attribs[attrib]===id){return node}}else if(attrib==='data-bind'){attr=this.extractAttribsFromDataBind(node.attribs[attrib]);if(attr&&attr['id']===id){return node}}}}if(node.children){for(i=0;i<node.children.length;i++){curNode=this._getElemById2(node.children[i],id,labelId);if(curNode){return curNode}}}return null};DomUtils.prototype.getElems=function(){var a=[],i;if(!this._tree){return a}for(i=0;i<this._tree.length;i++){_getElems2(this._tree[i],a)}return a};function _getElems2(node,a){var children,i;if(node.type===NodeType.TAG||node.type===NodeType.SCRIPT){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){_getElems2(children[i],a)}}};DomUtils.prototype.getScripts=function(){var head,ch,a=[];if(head=this.getHead()){if(ch=head.children){ch.forEach(elem=>{if(elem.type===NodeType.TAG&&elem.name==='script'){a.push(elem)}})}}return a};DomUtils.prototype.getLinks=function(){var head,ch,a=[];if(head=this.getHead()){if(ch=head.children){ch.forEach(elem=>{if(elem.type===NodeType.TAG&&elem.name==='link'){a.push(elem)}})}}return a};DomUtils.prototype.getHead=function(){var elem,ch,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){elem=this._tree[i];if(elem.type===NodeType.TAG&&elem.name==='html'){if(ch=elem.children){for(i=0;i<ch.length;i++){elem=ch[i];if(elem.type===NodeType.TAG&&elem.name==='head'){return elem}}}break}}return null};DomUtils.prototype.getBody=function(){var elem,ch,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){elem=this._tree[i];if(elem.type===NodeType.TAG&&elem.name==='html'){if(ch=elem.children){for(i=0;i<ch.length;i++){elem=ch[i];if(elem.type===NodeType.TAG&&elem.name==='body'){return elem}}}break}}return null};DomUtils.prototype.getComponentElems=function(){var a=[],i;if(!this._tree){return a}for(i=0;i<this._tree.length;i++){this._getComponentElems2(this._tree[i],a)}return a};DomUtils.prototype._getComponentElems2=function(node,a){var children,i;if(node.type===NodeType.TAG&&this._appContext.metaLib.isWCTag(node.name)){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){this._getComponentElems2(children[i],a)}}};DomUtils.prototype.isCommonAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===':'?attrName.substr(1):attrName;return HtmlUtils.isCommonAttr(attrName)};DomUtils.prototype.isCommonEventAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===':'?attrName.substr(1):attrName;if(attrName.startsWith('on-oj-')){return false}if(attrName.startsWith('on-')){attrName=attrName.substring(0,2)+attrName.substring(3)}return HtmlUtils.isCommonEventAttr(attrName)};DomUtils.prototype.isCommonElem=function(elem){return HtmlUtils.isCommonElem(elem)};DomUtils.prototype.isSvgElem=function(elem){return HtmlUtils.isSvgElem(elem)};DomUtils.prototype.isHtml5ObsoleteElem=function(tag){return HtmlUtils.isHtml5ObsoleteElem(tag)};DomUtils.prototype.isHtml5ObsoleteAttr=function(tagName,attrName){return HtmlUtils.isHtml5ObsoleteAttr(tagName,attrName)};DomUtils.prototype.isSelfClosingTag=function(tag){return HtmlUtils.isSelfClosingTag(tag)};DomUtils.prototype.isNamespaceTag=function(tagName){if(this._appContext.metaLib.isJetTag(tagName)){return true}return HtmlUtils.isNamespaceTag(tagName)};DomUtils.prototype.isNamespacePrefix=function(tagPrefix){return!!HtmlUtils.isNamespacePrefix(tagPrefix)};DomUtils.prototype.isChildOfElem=function(elemName,node){return!!this.isChildOfElemNode(elemName,node)};DomUtils.prototype.isChildOfElemNode=function(elemName,node){var ret=null;while(node.parent){if(node.parent.name===elemName){ret=node.parent;break}node=node.parent}return ret};DomUtils.prototype.getDataBindComponent=function(context){var node,val,attrVal,ret=null;node=context.tagNode;if(this.getAttribs(node)){attrVal=this.getAttribValue(node,'data-bind');if(attrVal){val=this.extractComponentFromDataBind(attrVal);if(val){ret='oj.'+val}}}return ret};DomUtils.prototype.getDataBindAttr=function(context){return this.getDataBindAttrsFromNode(context,context.node)};DomUtils.prototype.getDataBindAttrs=function(context){return this.getDataBindAttrsFromNode(context,context.node)};DomUtils.prototype.getDataBindAttrsFromNode=function(context,node){var attrVal,ret=null;if(this.getAttribs(node)){attrVal=this.getAttribValue(node,'data-bind');if(attrVal){ret=this.extractAttribsFromDataBind(attrVal)}}return ret};DomUtils.prototype.extractComponentFromDataBind=function(attrValue){var dataBind,componentName,x;x=attrValue.indexOf(OJCOMPONENT);if(x<0){return}componentName=null;if(attrValue.length>OJCOMPONENT.length){dataBind=attrValue.substring(x+OJCOMPONENT.length);x=dataBind.indexOf(COMPONENT);if(x>=0){dataBind=dataBind.substring(x+COMPONENT.length).trim();if(dataBind.charAt(0)===':'){x=dataBind.indexOf('oj');if(x>=0){dataBind=dataBind.substring(x);componentName=_extractComponentName(dataBind,this._utils)}}}}return componentName};function _extractComponentName(s,utils){var componentName,i,c;for(i=0;i<s.length;i++){c=s.charAt(i);if(c==='\''||c==='"'||utils.isWhitespace(c)){componentName=s.substring(0,i);break}}return componentName};DomUtils.prototype.extractAttribsFromDataBind=function(attrValue){var s,a,nextAttr,val,i,j,x,ret=null;if(attrValue.indexOf(':')<0){return ret}a=attrValue.split('attr');if(a.length<2){return ret}for(i=0;i<a.length;i++){a[i]=s=a[i].trim();if(s.charAt(0)===':'){s=s.substr(1).trim();if(s.charAt(0)==='{'){try{ret=jsonParser.stringToJson(s);ret=JSON.parse(ret)}catch(e){s=s.substring(1).trim();a=s.split(':');for(j=0;j<a.length;j++){if(nextAttr){if(!ret){ret={}}ret[nextAttr]=val=a[j].replace(/['\"]/g,'').trim();x=val.lastIndexOf('}');if(x>=0){ret[nextAttr]=val.substring(0,x).trim();break}nextAttr=null}if(j+1===a.length){break}a[j]=s=a[j].trim();s=s.replace(/['\"]/g,'').trim();if(s.length===0)continue;if(!ret){ret={}}ret[s]=val=a[++j].trim();x=val.indexOf(',');if(x>=0){ret[s]=val.substring(0,x).replace(/['\"]/g,'').trim();nextAttr=val.substring(x+1).trim();nextAttr=nextAttr.replace(/['\"]/g,'').trim();val=val.substring(0,x).replace(/['\"]/g,'').trim()}else{ret[s]=val.replace(/['\"]/g,'').trim()}x=val.lastIndexOf('}');if(x>=0){ret[s]=val.substring(0,x).trim();break}}}}break}}return ret};DomUtils.prototype.getAttribPosition=function(data,node,attrName){var startIndex=this.getAttrIndex(data,node,attrName);var endIndex=startIndex+attrName.length-1;var pos=this._utils.getRowColFromIndex(data,startIndex,'html');pos.start=startIndex;pos.end=endIndex;return pos};DomUtils.prototype.getAttrPosition=function(data,node,attrName){return this.getAttribPosition(data,node,attrName)};DomUtils.prototype.getAttribValuePosition=function(data,node,attrName){var attrPos,pos,endPos,ws,ret,good;var isDouble,isSingle,isUnquoted;attrPos=this.getAttrPosition(data,node,attrName);if(!attrPos||attrPos.start===node.startIndex){return}if((pos=this._utils.eatWhitespace(data,attrPos.end+1))>=0){if(data.charAt(pos++)==='='){if((endPos=this._utils.eatWhitespace(data,pos))>=0){isDouble=data.charAt(endPos)==='"';isSingle=data.charAt(endPos)==='\'';isUnquoted=!(isSingle||isDouble);if(isDouble){if((endPos=data.indexOf('"',pos+1))>=0){good=true}}else if(isSingle){if((endPos=data.indexOf('\'',pos+1))>=0){good=true}}else if(isUnquoted){ws=this._utils.getIndexToWhitespace(data,pos);endPos=data.indexOf('>',pos);if(ws>=0&&endPos>=0){endPos=(endPos<ws?endPos:ws)-1;good=true}}if(good){attrPos=this.getLineCol(data,pos);ret={row:attrPos.row,col:attrPos.col,start:pos,end:endPos}}}}}return ret};DomUtils.prototype.getAttrValuePosition=function(data,node,attrName){return this.getAttribValuePosition(data,node,attrName)};DomUtils.prototype.getLineCol=function(data,index){return this._fileIndex.getRowCol(data,{start:index},'html')};DomUtils.prototype.getAttribIndex=function(data,node,attrName){var attribs,index,temp,c,i,isQuote=attrName==='"'||attrName==='\'';if(!(attribs=node.attribs)){this._appContext.assert('no attrs in tag '+node.name+'(expected attr \''+attrName+')');return node.startIndex}if(!attribs.hasOwnProperty(attrName)&&!attribs.hasOwnProperty(':'+attrName)){this._appContext.assert('expected attr \''+attrName+'\' in tag '+node.name);return node.startIndex}index=data.indexOf(attrName,node.startIndex);while(true){index=data.indexOf(attrName,index);if(index>=0){temp=data.substring(index+attrName.length,index+100);i=this._utils.eatWhitespace(temp);if(i<0){return node.startIndex}c=temp.charAt(i);if(c==='='||c==='>'||!isQuote&&this._utils.isWhitespace(temp.charAt(0))){return index}index+=i+1;continue}this._appContext.assert('expected attr \''+attrName+'\' in tag '+node.name);return node.startIndex}};DomUtils.prototype.getAttrIndex=function(data,node,attrName){return this.getAttribIndex(data,node,attrName)};DomUtils.prototype.isNonFragmentJetPage=function(context){return this.hasBody(context)&&this.isJetPage(context)};DomUtils.prototype.hasBody=function(context){var i,siblings,ret=false;siblings=this.getSiblings(context.node);for(i=0;i<siblings.length;i++){if(this._hasBody2(siblings[i])){ret=true;break}}return ret};DomUtils.prototype._hasBody2=function(node){var i,children,ret=false;if(node.type===NodeType.TAG&&node.name.toLowerCase()==='body'){return true}if(node.children){children=node.children;for(i=0;i<children.length;i++){if(this._hasBody2(children[i])){ret=true;break}}}return ret};DomUtils.prototype.isJetPage=function(context){var i,siblings,ret=false;siblings=this.getSiblings(context.node);for(i=0;i<siblings.length;i++){if(this._isJetPage2(siblings[i])){ret=true;break}}return ret};DomUtils.prototype._isJetPage2=function(node){var i,children,ret=false;if(node.type===NodeType.TAG&&node.name.toLowerCase().startsWith('oj-')){return true}if(node.children){children=node.children;for(i=0;i<children.length;i++){if(this._isJetPage2(children[i])){ret=true;break}}}return ret};DomUtils.prototype.isValidJson=function(value,data){var data,ret;if(value.charAt(0)!=='{'){return true}try{data=JSON.parse(this._nodeDeps.decomment(value));ret=!!data}catch(e){if(typeof data==='string'&&e.toString().startsWith('SyntaxError')){var obj=_convertMsgToRowCol(e.message,data,this._utils);ret.msg=obj.msg;ret.line=obj.row;ret.col=obj.col;ret.position=obj.position}else{ret=e.message}}return ret};DomUtils.prototype.isAttrExprConstant=function(expr){return HtmlUtils.isAttrExprConstant(expr)};const RE_EXPRESSION=/^(?:\[{2})(.*)(?:\]{2})$|^(?:\{{2})(.*)(?:\}{2})$/;DomUtils.prototype.isExpression=function(s){var ret=false;if(s){ret=RE_EXPRESSION.test(s.trim())}return ret};DomUtils.prototype.getExpression=function(s){var ret=null;if(this.isExpression(s)){ret=s.substring(2,s.length-2).trim()}return ret};DomUtils.prototype.isSvgPath=function(s){return HtmlUtils.isSvgPath(s)};DomUtils.prototype.camelCase=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)};DomUtils.prototype.kebabCase=function(str){return str.replace(/([a-zA-Z])(?=[A-Z])/g,'$1-').toLowerCase()};DomUtils.prototype.kekabCaseEvent=function(str){return ON_DASH+this.kebabCase(str)};function _isHtmlScript(node){var attribs=node.attribs;return node.type&&node.type===NodeType.SCRIPT&&attribs&&attribs.type&&attribs.type.indexOf('html')>=0};function _convertMsgToRowCol(msg,data,utils){var x,n,obj;x=msg.indexOf('position');if(x<0){return null}n=parseInt(msg.substr(x+8).trim());obj=utils.getRowColFromIndex(data,n);obj.msg=msg.substr(0,x)+'line '+obj.row+', col '+obj.col+' (position '+n+')';obj.position=n;return obj};function _getAttrRawValue(data,index,attrName,attrValue,utils){var ret=null,delim,i;i=index+attrName.length;if(data.charAt(i)==='='){i=utils.eatWhitespace(data,i+1);delim=data.substr(i,1);delim=delim==='\''||delim==='"'?delim:'"';ret=delim+attrValue+data.charAt(i+attrValue.length+1)}else{ret=attrValue}return ret};DomUtils.prototype.setDom=function(oDom){this._tree=oDom};module.exports=DomUtils;
|
|
6
|
+
const jsonParser=require("really-relaxed-json").createParser();const HtmlUtils=require("./HtmlUtils");const NodeType=require("./NodeTypes");const OJCOMPONENT="ojComponent";const COMPONENT="component";const DOT=".";const ON_DASH="on-";function DomUtils(nodeDeps,appContext,oTabs,fileIndex){this._tree=null;this._nodeDeps=nodeDeps;this._appContext=appContext;this._tabs=oTabs;this._utils=appContext.utils;this._fileIndex=fileIndex};DomUtils.prototype.getFirst=function(){return this._tree.length?this._tree[0]:null};DomUtils.prototype.getLast=function(){var node;node=this._tree.length?this._tree[this._tree.length-1]:null;while(node&&node.children&&node.children.length){node=node.children[node.children.length-1]}return node};DomUtils.prototype.getFirstElem=function(){var node=this.getFirst();while(node){if(node.type===NodeType.TAG){break};node=node.next}return node};DomUtils.prototype.getChildren=function(node){return node.children};DomUtils.prototype.getParent=function(node){return node.parent};DomUtils.prototype.getSiblings=function(node){var parent;if(parent=this.getParent(node)){return this.getChildren(parent)}else{return this._tree}};DomUtils.prototype.getNext=function(node){return node.next||null};DomUtils.prototype.getAttribs=function(node){return node.attribs||null};DomUtils.prototype.getAttribValue=function(node,name){return node.attribs?node.attribs[name]:undefined};DomUtils.prototype.getAttribRawValue=function(ruleCtx,name){var val,pos;if(ruleCtx.tagNode.attribs){if(typeof(val=ruleCtx.tagNode.attribs[name])==="string"){pos=this.getAttrPosition(ruleCtx.data,ruleCtx.tagNode,name);return _getAttrRawValue(ruleCtx.data,pos.start,name,val,ruleCtx.utils.utils)}}};DomUtils.prototype.hasAttrib=function(node,name){return!!node.attribs&&hasOwnProperty.call(node.attribs,name)};DomUtils.prototype.hasChildren=function(node){return!!node.children?.length};DomUtils.prototype.hasNext=function(node){return!!node.next};DomUtils.prototype.getName=function(node){return node.name};DomUtils.prototype.getType=function(node){return node.type};DomUtils.prototype.getElemsByName=function(name){var a=[],i,names;if(!this._tree){return a}names=typeof name==="string"?[name]:name;for(i=0;i<names.length;i++){names[i]=names[i].toLowerCase()}for(i=0;i<this._tree.length;i++){_getElemsByName2(this._tree[i],a,names)}return a};function _getElemsByName2(node,a,names){var children,i;if((node.type===NodeType.TAG||node.type===NodeType.SCRIPT)&&names.indexOf(node.name.toLowerCase())>=0){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){_getElemsByName2(children[i],a,names)}}};DomUtils.prototype.getElemById=function(id,labelId){var node,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){node=this._tree[i];if(node.type===NodeType.TAG||_isHtmlScript(node)){node=this._getElemById2(node,id,labelId);if(node){return node}}}return null};DomUtils.prototype._getElemById2=function(node,id,labelId){var curNode,attrib,attr,attribLower,i;if((node.type===NodeType.TAG||_isHtmlScript(node))&&node.attribs){for(attrib in node.attribs){attribLower=attrib.toLowerCase();if(attribLower==="id"||labelId&&attribLower==="label-id"){if(node.attribs[attrib]===id){return node}}else if(attrib==="data-bind"){attr=this.extractAttribsFromDataBind(node.attribs[attrib]);if(attr&&attr["id"]===id){return node}}}}if(node.children){for(i=0;i<node.children.length;i++){curNode=this._getElemById2(node.children[i],id,labelId);if(curNode){return curNode}}}return null};DomUtils.prototype.getElems=function(){var a=[],i;if(!this._tree){return a}for(i=0;i<this._tree.length;i++){_getElems2(this._tree[i],a)}return a};function _getElems2(node,a){var children,i;if(node.type===NodeType.TAG||node.type===NodeType.SCRIPT){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){_getElems2(children[i],a)}}};DomUtils.prototype.getScripts=function(){var head,ch,a=[];if(head=this.getHead()){if(ch=head.children){ch.forEach(elem=>{if(elem.type===NodeType.TAG&&elem.name==="script"){a.push(elem)}})}}return a};DomUtils.prototype.getLinks=function(){var head,ch,a=[];if(head=this.getHead()){if(ch=head.children){ch.forEach(elem=>{if(elem.type===NodeType.TAG&&elem.name==="link"){a.push(elem)}})}}return a};DomUtils.prototype.getHead=function(){var elem,ch,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){elem=this._tree[i];if(elem.type===NodeType.TAG&&elem.name==="html"){if(ch=elem.children){for(i=0;i<ch.length;i++){elem=ch[i];if(elem.type===NodeType.TAG&&elem.name==="head"){return elem}}}break}}return null};DomUtils.prototype.getBody=function(){var elem,ch,i;if(!this._tree){return null}for(i=0;i<this._tree.length;i++){elem=this._tree[i];if(elem.type===NodeType.TAG&&elem.name==="html"){if(ch=elem.children){for(i=0;i<ch.length;i++){elem=ch[i];if(elem.type===NodeType.TAG&&elem.name==="body"){return elem}}}break}}return null};DomUtils.prototype.getComponentElems=function(){var a=[],i;if(!this._tree){return a}for(i=0;i<this._tree.length;i++){this._getComponentElems2(this._tree[i],a)}return a};DomUtils.prototype._getComponentElems2=function(node,a){var children,i;if(node.type===NodeType.TAG&&this._appContext.metaLib.isWCTag(node.name)){a.push(node)}if(node.children){children=node.children;for(i=0;i<children.length;i++){this._getComponentElems2(children[i],a)}}};DomUtils.prototype.isCommonAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===":"?attrName.substring(1):attrName;return HtmlUtils.isCommonAttr(attrName)};DomUtils.prototype.isCommonEventAttr=function(attrName){attrName=attrName.toLowerCase();attrName=attrName.charAt(0)===":"?attrName.substr(1):attrName;if(attrName.startsWith("on-oj-")){return false}if(attrName.startsWith("on-")){attrName=attrName.substring(0,2)+attrName.substring(3)}return HtmlUtils.isCommonEventAttr(attrName)};DomUtils.prototype.isCommonElem=function(elem){return HtmlUtils.isCommonElem(elem)};DomUtils.prototype.isSvgElem=function(elem){return HtmlUtils.isSvgElem(elem)};DomUtils.prototype.isHtml5ObsoleteElem=function(tag){return HtmlUtils.isHtml5ObsoleteElem(tag)};DomUtils.prototype.isHtml5ObsoleteAttr=function(tagName,attrName){return HtmlUtils.isHtml5ObsoleteAttr(tagName,attrName)};DomUtils.prototype.isSelfClosingTag=function(tag){return HtmlUtils.isSelfClosingTag(tag)};DomUtils.prototype.isNamespaceTag=function(tagName){if(this._appContext.metaLib.isJetTag(tagName)){return true}return HtmlUtils.isNamespaceTag(tagName)};DomUtils.prototype.isNamespacePrefix=function(tagPrefix){return!!HtmlUtils.isNamespacePrefix(tagPrefix)};DomUtils.prototype.isChildOfElem=function(elemName,node){return!!this.isChildOfElemNode(elemName,node)};DomUtils.prototype.isChildOfElemNode=function(elemName,node){var ret=null;while(node.parent){if(node.parent.name===elemName){ret=node.parent;break}node=node.parent}return ret};DomUtils.prototype.getDataBindComponent=function(context){var node,val,attrVal,ret=null;node=context.tagNode;if(this.getAttribs(node)){attrVal=this.getAttribValue(node,"data-bind");if(attrVal){val=this.extractComponentFromDataBind(attrVal);if(val){ret="oj."+val}}}return ret};DomUtils.prototype.getDataBindAttr=function(context){return this.getDataBindAttrsFromNode(context,context.node)};DomUtils.prototype.getDataBindAttrs=function(context){return this.getDataBindAttrsFromNode(context,context.node)};DomUtils.prototype.getDataBindAttrsFromNode=function(context,node){var attrVal,ret=null;if(this.getAttribs(node)){attrVal=this.getAttribValue(node,"data-bind");if(attrVal){ret=this.extractAttribsFromDataBind(attrVal)}}return ret};DomUtils.prototype.extractComponentFromDataBind=function(attrValue){var dataBind,componentName,x;x=attrValue.indexOf(OJCOMPONENT);if(x<0){return}componentName=null;if(attrValue.length>OJCOMPONENT.length){dataBind=attrValue.substring(x+OJCOMPONENT.length);x=dataBind.indexOf(COMPONENT);if(x>=0){dataBind=dataBind.substring(x+COMPONENT.length).trim();if(dataBind.charAt(0)===":"){x=dataBind.indexOf("oj");if(x>=0){dataBind=dataBind.substring(x);componentName=_extractComponentName(dataBind,this._utils)}}}}return componentName};function _extractComponentName(s,utils){var componentName,i,c;for(i=0;i<s.length;i++){c=s.charAt(i);if(c==="'"||c==="\""||utils.isWhitespace(c)){componentName=s.substring(0,i);break}}return componentName};DomUtils.prototype.extractAttribsFromDataBind=function(attrValue){var s,a,nextAttr,val,i,j,x,ret=null;if(attrValue.indexOf(":")<0){return ret}a=attrValue.split("attr");if(a.length<2){return ret}for(i=0;i<a.length;i++){a[i]=s=a[i].trim();if(s.charAt(0)===":"){s=s.substr(1).trim();if(s.charAt(0)==="{"){try{ret=jsonParser.stringToJson(s);ret=JSON.parse(ret)}catch(e){s=s.substring(1).trim();a=s.split(":");for(j=0;j<a.length;j++){if(nextAttr){if(!ret){ret={}}ret[nextAttr]=val=a[j].replace(/['\"]/g,"").trim();x=val.lastIndexOf("}");if(x>=0){ret[nextAttr]=val.substring(0,x).trim();break}nextAttr=null}if(j+1===a.length){break}a[j]=s=a[j].trim();s=s.replace(/['\"]/g,"").trim();if(s.length===0)continue;if(!ret){ret={}}ret[s]=val=a[++j].trim();x=val.indexOf(",");if(x>=0){ret[s]=val.substring(0,x).replace(/['\"]/g,"").trim();nextAttr=val.substring(x+1).trim();nextAttr=nextAttr.replace(/['\"]/g,"").trim();val=val.substring(0,x).replace(/['\"]/g,"").trim()}else{ret[s]=val.replace(/['\"]/g,"").trim()}x=val.lastIndexOf("}");if(x>=0){ret[s]=val.substring(0,x).trim();break}}}}break}}return ret};DomUtils.prototype.getAttribPosition=function(data,node,attrName){var startIndex=this.getAttrIndex(data,node,attrName);var endIndex=startIndex+attrName.length-1;var pos=this._utils.getRowColFromIndex(data,startIndex,"html");pos.start=startIndex;pos.end=endIndex;return pos};DomUtils.prototype.getAttrPosition=function(data,node,attrName){return this.getAttribPosition(data,node,attrName)};DomUtils.prototype.getAttribValuePosition=function(data,node,attrName){var attrPos,pos,endPos,ws,ret,good;var isDouble,isSingle,isUnquoted;attrPos=this.getAttrPosition(data,node,attrName);if(!attrPos||attrPos.start===node.startIndex){return}if((pos=this._utils.eatWhitespace(data,attrPos.end+1))>=0){if(data.charAt(pos++)==="="){if((endPos=this._utils.eatWhitespace(data,pos))>=0){isDouble=data.charAt(endPos)==="\"";isSingle=data.charAt(endPos)==="'";isUnquoted=!(isSingle||isDouble);if(isDouble){if((endPos=data.indexOf("\"",pos+1))>=0){good=true}}else if(isSingle){if((endPos=data.indexOf("'",pos+1))>=0){good=true}}else if(isUnquoted){ws=this._utils.getIndexToWhitespace(data,pos);endPos=data.indexOf(">",pos);if(ws>=0&&endPos>=0){endPos=(endPos<ws?endPos:ws)-1;good=true}}if(good){attrPos=this.getLineCol(data,pos);ret={row:attrPos.row,col:attrPos.col,start:pos,end:endPos}}}}}return ret};DomUtils.prototype.getAttrValuePosition=function(data,node,attrName){return this.getAttribValuePosition(data,node,attrName)};DomUtils.prototype.getLineCol=function(data,index){return this._fileIndex.getRowCol(data,{start:index},"html")};DomUtils.prototype.getAttribIndex=function(data,node,attrName){var attribs,index,temp,c,i,isQuote=attrName==="\""||attrName==="'";if(!(attribs=node.attribs)){this._appContext.assert("no attrs in tag "+node.name+"(expected attr '"+attrName+")");return node.startIndex}if(!attribs.hasOwnProperty(attrName)&&!attribs.hasOwnProperty(":"+attrName)){this._appContext.assert("expected attr '"+attrName+"' in tag "+node.name);return node.startIndex}index=data.indexOf(attrName,node.startIndex);while(true){index=data.indexOf(attrName,index);if(index>=0){temp=data.substring(index+attrName.length,index+100);i=this._utils.eatWhitespace(temp);if(i<0){return node.startIndex}c=temp.charAt(i);if(c==="="||c===">"||!isQuote&&this._utils.isWhitespace(temp.charAt(0))){return index}index+=i+1;continue}this._appContext.assert("expected attr '"+attrName+"' in tag "+node.name);return node.startIndex}};DomUtils.prototype.getAttrIndex=function(data,node,attrName){return this.getAttribIndex(data,node,attrName)};DomUtils.prototype.isNonFragmentJetPage=function(context){return this.hasBody(context)&&this.isJetPage(context)};DomUtils.prototype.hasBody=function(context){var i,siblings,ret=false;siblings=this.getSiblings(context.node);for(i=0;i<siblings.length;i++){if(this._hasBody2(siblings[i])){ret=true;break}}return ret};DomUtils.prototype._hasBody2=function(node){var i,children,ret=false;if(node.type===NodeType.TAG&&node.name.toLowerCase()==="body"){return true}if(node.children){children=node.children;for(i=0;i<children.length;i++){if(this._hasBody2(children[i])){ret=true;break}}}return ret};DomUtils.prototype.isJetPage=function(context){var i,siblings,ret=false;siblings=this.getSiblings(context.node);for(i=0;i<siblings.length;i++){if(this._isJetPage2(siblings[i])){ret=true;break}}return ret};DomUtils.prototype._isJetPage2=function(node){var i,children,ret=false;if(node.type===NodeType.TAG&&node.name.toLowerCase().startsWith("oj-")){return true}if(node.children){children=node.children;for(i=0;i<children.length;i++){if(this._isJetPage2(children[i])){ret=true;break}}}return ret};DomUtils.prototype.isValidJson=function(value,data){var data,ret;if(value.charAt(0)!=="{"){return true}try{data=JSON.parse(this._nodeDeps.decomment(value));ret=!!data}catch(e){if(typeof data==="string"&&e.toString().startsWith("SyntaxError")){var obj=_convertMsgToRowCol(e.message,data,this._utils);ret.msg=obj.msg;ret.line=obj.row;ret.col=obj.col;ret.position=obj.position}else{ret=e.message}}return ret};DomUtils.prototype.isAttrExprConstant=function(expr){return HtmlUtils.isAttrExprConstant(expr)};DomUtils.prototype.isExpression=function(s){var sq,ret=false;if(s&&(s=s.trim())){if((sq=s.startsWith("[["))||s.startsWith("{{")){ret=sq?s.endsWith("]]"):s.endsWith("}}")}}return ret};DomUtils.prototype.getExpression=function(s){var ret=null;if(this.isExpression(s)){ret=s.trim().substring(2,s.length-2).trim()}return ret};DomUtils.prototype.isSvgPath=function(s){return HtmlUtils.isSvgPath(s)};DomUtils.prototype.camelCase=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)};DomUtils.prototype.kebabCase=function(str){return str.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase()};DomUtils.prototype.kekabCaseEvent=function(str){return ON_DASH+this.kebabCase(str)};function _isHtmlScript(node){var attribs=node.attribs;return node.type&&node.type===NodeType.SCRIPT&&attribs&&attribs.type&&attribs.type.indexOf("html")>=0};function _convertMsgToRowCol(msg,data,utils){var x,n,obj;x=msg.indexOf("position");if(x<0){return null}n=parseInt(msg.substr(x+8).trim());obj=utils.getRowColFromIndex(data,n);obj.msg=msg.substr(0,x)+"line "+obj.row+", col "+obj.col+" (position "+n+")";obj.position=n;return obj};function _getAttrRawValue(data,index,attrName,attrValue,utils){var ret=null,delim,i;i=index+attrName.length;if(data.charAt(i)==="="){i=utils.eatWhitespace(data,i+1);delim=data.substr(i,1);delim=delim==="'"||delim==="\""?delim:"\"";ret=delim+attrValue+data.charAt(i+attrValue.length+1)}else{ret=attrValue}return ret};DomUtils.prototype.setDom=function(oDom){this._tree=oDom};module.exports=DomUtils;
|
package/lib/FileIndex.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 FileIndex=function(utils){this._displacements=[];this._lastDisp=null;this._utils=utils};FileIndex.prototype.getRowCol=function(data,index,fileType){var start,end,datalen,disp,lastDisp,c,inStart=false,latest,temp,initIndex,i;if(index.line){return{row:index.line,col:index.col}}if(!data){return{row:0,col:0}}start=index.start;end=index.end;datalen=data.length;lastDisp=null;latest=0;for(i=0;i<this._displacements.length;i++){disp=this._displacements[i];if(start>=disp.index&&disp.index>latest){lastDisp=disp;latest=disp.index}}if(lastDisp){if(start===lastDisp.index){return{row:lastDisp.line,col:lastDisp.col}}temp={index:lastDisp.index,line:lastDisp.line,col:lastDisp.col};lastDisp=temp}else{lastDisp={index:0,line:1,col:1}}initIndex=lastDisp.index;for(i=initIndex;i<datalen;i++){c=data.charAt(i);if(i===start){inStart=true;lastDisp.index=start;break}if(c===
|
|
6
|
+
var FileIndex=function(utils){this._displacements=[];this._lastDisp=null;this._utils=utils};FileIndex.prototype.getRowCol=function(data,index,fileType){var start,end,datalen,disp,lastDisp,c,inStart=false,latest,temp,initIndex,i;if(index.line){return{row:index.line,col:index.col}}if(!data){return{row:0,col:0}}start=index.start;end=index.end;datalen=data.length;lastDisp=null;latest=0;for(i=0;i<this._displacements.length;i++){disp=this._displacements[i];if(start>=disp.index&&disp.index>latest){lastDisp=disp;latest=disp.index}}if(lastDisp){if(start===lastDisp.index){return{row:lastDisp.line,col:lastDisp.col}}temp={index:lastDisp.index,line:lastDisp.line,col:lastDisp.col};lastDisp=temp}else{lastDisp={index:0,line:1,col:1}}initIndex=lastDisp.index;for(i=initIndex;i<datalen;i++){c=data.charAt(i);if(i===start){inStart=true;lastDisp.index=start;break}if(c==="\n"){lastDisp.line++;lastDisp.col=1;continue}if(c==="\r"){continue}if(!inStart){if(c!=="\t"){lastDisp.col++}else{lastDisp.col=this._tabs.getTabCol(lastDisp.col,fileType)}continue}}this._displacements.push(lastDisp);return{row:lastDisp.line,col:lastDisp.col}};FileIndex.prototype.clear=function(){this._displacements.length=0};FileIndex.prototype.setTabHandler=function(oTabs){this._tabs=oTabs};module.exports=FileIndex;
|
package/lib/FileSet.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
|
-
function FileSet(nd,fsUtils){this._contentStack=null;this._contentStackIndex=-1;this._srcStack=null;this._srcStackIndex=-1;this._globOpts=null;this._fileErrorCount=0;this._info=null;this._nd=nd;this._fsUtils=fsUtils};FileSet.prototype.setFiles=function(files,excludes,msgCtx){this._srcStack=files;this._globOpts=addGlobIgnoreOpts(this._globOpts,excludes);this._contentStack=null;this._contentStackIndex=-1;this._srcStackIndex=-1;this._fileErrorCount=0;if(msgCtx){this._info=msgCtx.info}};FileSet.prototype.getFiles=function(){if(this._srcStack){return{files:this._srcStack,exclude:this._globOpts.ignore}}};FileSet.prototype.getFileErrorCount=function(){return this._fileErrorCount};FileSet.prototype.getNextFile=function(){var path,ft,files,i;if(this._contentStack){for(i=this._contentStackIndex+1;i<this._contentStack.length;i++){path=this._contentStack[i];if(!path){continue}this._contentStackIndex=i;ft=this._fsUtils.getFileType(path);if(ft===
|
|
6
|
+
function FileSet(nd,fsUtils){this._contentStack=null;this._contentStackIndex=-1;this._srcStack=null;this._srcStackIndex=-1;this._globOpts=null;this._fileErrorCount=0;this._info=null;this._nd=nd;this._fsUtils=fsUtils};FileSet.prototype.setFiles=function(files,excludes,msgCtx){this._srcStack=files;this._globOpts=addGlobIgnoreOpts(this._globOpts,excludes);this._contentStack=null;this._contentStackIndex=-1;this._srcStackIndex=-1;this._fileErrorCount=0;if(msgCtx){this._info=msgCtx.info}};FileSet.prototype.getFiles=function(){if(this._srcStack){return{files:this._srcStack,exclude:this._globOpts.ignore}}};FileSet.prototype.getFileErrorCount=function(){return this._fileErrorCount};FileSet.prototype.getNextFile=function(){var path,ft,files,i;if(this._contentStack){for(i=this._contentStackIndex+1;i<this._contentStack.length;i++){path=this._contentStack[i];if(!path){continue}this._contentStackIndex=i;ft=this._fsUtils.getFileType(path);if(ft==="f"){if(i+1>=this._contentStack.length){this._contentStack=null;this._contentStackIndex=-1}return path}else if(ft==="?"){this._info("** File '"+path+"' : ignored");this._fileErrorCount++}}}for(i=this._srcStackIndex+1;i<this._srcStack.length;i++){path=this._srcStack[i];this._srcStackIndex++;if(typeof path==="object"){return path}if(!path.startsWith("http")){if(this._globOpts){files=this._nd.glob.sync(path,this._globOpts)}else{files=this._nd.glob.sync(path)}if(this._removeDirs(files)){this._contentStack=files;this._contentStackIndex=-1;return this.getNextFile()}}else{return path}}return null};function addGlobIgnoreOpts(opts,excludes){if(!excludes||excludes.length===0){return opts}if(!opts){opts={}}opts.ignore=excludes;return opts};FileSet.prototype._removeDirs=function(ar){var i,ft,count=0;for(i=0;i<ar.length;i++){ft=this._fsUtils.getFileTypeWithMsg(ar[i]);if(ft==="d"){ar[i]=null;continue}count++}return count};module.exports=FileSet;
|
package/lib/FsUtils.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 tmpFile=require(
|
|
6
|
+
const tmpFile=require("tmp");function FSU(nd,utils){this._nd=nd;this._utils=utils};FSU.prototype.getFileType=function(path){var stats,ret;try{stats=this._nd.fs.statSync(path);if(stats.isFile()){ret="f"}else if(stats.isDirectory()){ret="d"}}catch(e){ret=e}return ret};FSU.prototype.getFileTypeSync=function(path){return this.getFileType(path)};FSU.prototype.getFileTypeWithMsg=function(path){var ret;ret=this.getFileType(path);if(ret!=="f"&&ret!=="d"){if(ret.message.startsWith("ENOENT:")){console.log("\n** File \""+path+"\" not found")}else{console("\n** File \""+path+"\" error.\n"+" "+ret.message+".\n")}ret="?"}return ret};FSU.prototype.getFileTypeWithMsgSync=function(path){return this.getFileTypeWithMsg(path)};FSU.prototype.getFileExt=function(path){var s;try{if(!this.isSymLink(path)){s=this._nd.path.extname(path)}else{let p=this._nd.fs.readlinkSync(path);if(p){s=this._nd.path.extname(p)}}if(s&&s.charAt(0)==="."){s=s.substring(1)}return s}catch(e){}return""};FSU.prototype.getFileExtSync=function(path){return this.getFileExt(path)};FSU.prototype.isSymLink=function(path){var stats;try{stats=this._nd.fs.lstatSync(path);return stats.isSymbolicLink()}catch(e){}return false};FSU.prototype.fileExists=function(filepath,dir){var stats,ret=false;try{stats=this._nd.fs.lstatSync(filepath);ret=dir?stats.isDirectory():stats.isFile()}catch(e){}return ret};FSU.prototype.fileExistsSync=function(filepath,dir){return this.fileExists(filepath,dir)};FSU.prototype.pathExistsSync=function(filepath){try{return this._nd.fs.existsSync(filepath)}catch(e){}return false};FSU.prototype.readDir=function(path){var ret=[];try{this._readDir(path,ret)}catch(e){ret=null}return ret};FSU.prototype.readDirSync=function(path){return this.readDir(path)};FSU.prototype._readDir=function(dir,ar){var files,file,filePath,stat,arDir,i;files=this._nd.fs.readdirSync(dir);for(i=0;i<files.length;i++){file=files[i];if(file[0]==="."){continue}filePath=this._nd.path.join(dir,file);stat=this._nd.fs.statSync(filePath);if(stat.isFile()){ar.push({name:file,isFile:true})}else if(stat.isDirectory()){arDir=[];ar.push({name:file,isFile:false,files:arDir});this._readDir(filePath,arDir)}}};FSU.prototype.createFolder=function(dirPath,orig){var rc;dirPath=this._nd.path.resolve(dirPath);if(!orig){orig=dirPath}try{if(!this._nd.fs.statSync(dirPath).isDirectory()){return new Error(dirPath+" exists but is not a directory")}}catch(err){if(err.code==="ENOENT"){var np=this._nd.path.dirname(dirPath);if(np===dirPath){return new Error(orig+" cannot be created")}rc=this.createFolder(np,orig);if(typeof rc!=="boolean"){return rc}this._nd.fs.mkdirSync(dirPath);if(dirPath===orig){return true}}else{return err}}return true};FSU.prototype.createFolderSync=function(dirPath){return this.createFolder(dirPath)};FSU.prototype.deleteFolder=function(filepath,deleteTarget){if(this._nd.fs.existsSync(filepath)){this._nd.fs.readdirSync(filepath).forEach(function(file){var curPath=this._nd.path.join(filepath,file);if(this._nd.fs.lstatSync(curPath).isDirectory()){this.deleteFolder(curPath,true)}else{this._nd.fs.unlinkSync(curPath)}},this);if(deleteTarget){this._nd.fs.rmdirSync(filepath)}}};FSU.prototype.deleteFolderSync=function(filepath,deleteTarget){return this.deleteFolder(filepath,deleteTarget)};FSU.prototype.getUniqueFileNameSync=function(template,targetFolder){const opts={template:template};if(targetFolder){opts.dir=targetFolder}return tmpFile.tmpNameSync(opts)};FSU.prototype.getUniqueFileName=function(template,targetFolder){return this.getUniqueFileNameSync(template,targetFolder)};FSU.prototype.findFile=function(dir,name,fncb){var ret;try{ret=this._findFile(dir,name,fncb)}catch(e){}return ret};FSU.prototype._findFile=function(dir,name,fncb){var files,file,filePath,stat,ret,i;files=this._nd.fs.readdirSync(dir);for(i=0;i<files.length;i++){file=files[i];if(!fncb||fncb(dir,file)){if(file===name){return dir}}if(file[0]==="."){continue}filePath=this._nd.path.join(dir,file);stat=this._nd.fs.statSync(filePath);if(stat.isDirectory()){ret=this._findFile(filePath,name,fncb);if(ret){return ret}}}return null};FSU.prototype.findFileSync=function(dir,name,fncb){return this.findFile(dir,name,fncb)};FSU.prototype.readFileSync=function(filePath,error){return this._readFileSync(filePath,false,error)};FSU.prototype.readFileBufSync=function(filePath,error){return this._readFileSync(filePath,true,error)};FSU.prototype._readFileSync=function(filePath,wantBuffer,error){var haveFn,doThrow,noThrow,t;t=typeof error;doThrow=t==="boolean"&&error;noThrow=t==="boolean"&&!error;haveFn=t==="function";try{return wantBuffer?this._nd.fs.readFileSync(filePath):this._nd.fs.readFileSync(filePath,"utf8")}catch(e){function _prepErr(){var s=e.message;if(s.startsWith("ENOENT")){s=`ENOENT: file not found - '${filePath}'`}return s}if(haveFn){error(_prepErr())}else if(doThrow){throw new Error(e)}else if(noThrow){return _prepErr()}}return null};FSU.prototype.readJsonSync=function(filepath,comments,error){var e,haveFn,doThrow,noThrow,t;t=typeof error;doThrow=t==="boolean"&&error;noThrow=t==="boolean"&&!error;haveFn=t==="function";var _fn=function(err){err="SYNTAX: "+err;e=err;if(haveFn){error(err)}};filepath=this.makeAbsolutePath(filepath);var o=this._nd.jsonLoader.load(filepath,this._nd,_fn,comments,this._utils);if(e){if(doThrow){throw new Error(e)}else if(noThrow){return e}return null}if(o){return o}let msg="NOFILE: "+filepath;if(doThrow){throw new Error(msg)}if(noThrow){return msg}if(haveFn){error(msg)}return null};FSU.prototype.writeJsonSync=function(obj,filepath,opts,error){var repl,ind,err;var doThrow,noThrow,haveFn,t;t=typeof error;doThrow=t==="boolean"&&error;noThrow=t==="boolean"&&!error;haveFn=t==="function";if(opts){repl=opts.replacer?opts.replacer:null;ind=opts.spaces}filepath=this.makeAbsolutePath(filepath);try{let s=JSON.stringify(obj,repl,ind);this._nd.fs.writeFileSync(filepath,s);return true}catch(e){if(doThrow){throw e}err=e}if(err){if(haveFn){error(err.message);return false}if(noThrow){return err.message}}return false};FSU.prototype.walkDirSync=function(dirPath,cb,forceFwdSlash){if(typeof cb!=="function"||!this.fileExistsSync(dirPath,true)){return}let path=this._nd.path;let fs=this._nd.fs;let _getFileType=this.getFileType.bind(this);function _walkDirSync(dirPath,cb,forceFwdSlash){var i,ftype,fpath,files,file,ret;if(files=fs.readdirSync(dirPath)){for(i=0;i<files.length;i++){file=files[i];fpath=path.join(dirPath,file);fpath=forceFwdSlash?fpath.replace(/\\/g,"/"):fpath;ftype=_getFileType(fpath);if(ftype==="f"||ftype==="d"||ftype==="l"){ret=cb(fpath,ftype);if(ret==="exit"){return false}else if(ret==="direxit"){break}if(ftype==="d"){if(!_walkDirSync(fpath,cb,forceFwdSlash)){return false}}}}}return true};_walkDirSync(dirPath,cb,forceFwdSlash)};FSU.prototype.makeAbsolutePath=function(filepath){if(!this._nd.path.isAbsolute(filepath)){filepath=this._nd.path.resolve(process.cwd(),filepath)}return filepath};module.exports=FSU;
|