@oracle/oraclejet-audit 15.1.8 → 16.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/corePackMigrator.js +2 -2
- package/corePackMigrator/metadata/actionCardMetadata.json +8 -0
- package/corePackMigrator/metadata/avatarMetadata.json +0 -12
- package/corePackMigrator/metadata/drawerPopupMetadata.json +16 -0
- package/corePackMigrator/metadata/formLayoutMetadata.json +34 -0
- package/corePackMigrator/metadata/highlightTextMetadata.json +8 -0
- package/corePackMigrator/metadata/inputNumberMetadata.json +26 -2
- package/corePackMigrator/metadata/inputPasswordMetadata.json +32 -2
- package/corePackMigrator/metadata/inputTextMetadata.json +26 -2
- package/corePackMigrator/metadata/legendItemMetadata.json +1 -5
- package/corePackMigrator/metadata/legendMetadata.json +42 -0
- package/corePackMigrator/metadata/legendSectionMetadata.json +6 -4
- package/corePackMigrator/metadata/listviewMetadata.json +61 -2
- package/corePackMigrator/metadata/messageBannerMetadata.json +8 -0
- package/corePackMigrator/metadata/messagesMetadata.json +17 -5
- package/corePackMigrator/metadata/radiosetMetadata.json +86 -0
- package/corePackMigrator/metadata/ratingGaugeMetadata.json +29 -17
- package/corePackMigrator/metadata/selectManyMetadata.json +9 -3
- package/corePackMigrator/metadata/selectSingleMetadata.json +16 -5
- package/corePackMigrator/metadata/selectorMetadata.json +37 -0
- package/corePackMigrator/metadata/statusMeterGaugeMetadata.json +21 -9
- package/corePackMigrator/metadata/tagCloudMetadata.json +8 -0
- package/corePackMigrator/metadata/textAreaMetadata.json +8 -2
- package/corePackMigrator/resource/astUtils.js +1 -1
- package/corePackMigrator/resource/componentMigrator.js +1 -1
- package/corePackMigrator/resource/fileScanner.js +1 -1
- package/corePackMigrator/resource/htmlUtils.js +1 -1
- package/corePackMigrator/resource/manifest.json +25 -10
- package/corePackMigrator/resource/migrationConfig.json +3 -0
- package/corePackMigrator/templates/componentMetaData.json +18 -4
- package/corePackMigrator/templates/migrationConfig.json +15 -3
- package/corePackMigrator/utilities/logging.js +1 -1
- package/jaf-amd.js +1 -1
- package/jaf.js +1 -1
- package/jafapi.js +1 -1
- package/lib/AST_Ts.js +1 -1
- package/lib/AstNodeTypes.js +1 -1
- package/lib/Components.js +1 -1
- package/lib/DomUtils.js +1 -1
- package/lib/FsUtils.js +1 -1
- package/lib/HtmlUtils.js +1 -1
- package/lib/JafLib.js +1 -1
- package/lib/MetaLib.js +1 -1
- package/lib/OjCPack.js +1 -1
- package/lib/Registry.js +1 -1
- package/lib/RulePack.js +1 -1
- package/lib/RuleSet.js +1 -1
- package/lib/Rules.js +1 -1
- package/lib/Stats.js +1 -1
- package/lib/Ts.js +1 -1
- package/lib/TsUtils.js +6 -0
- package/lib/TsxUtils.js +1 -1
- package/lib/TsxUtils2.js +1 -1
- package/lib/Utils.js +1 -1
- package/lib/checkage.js +1 -1
- package/lib/defaults.js +1 -1
- package/lib/jsx.js +1 -1
- package/lib/migrator.js +1 -1
- package/lib/scaffold.js +1 -1
- package/lib/sublib/precomp/ComponentFinder.js +6 -0
- package/lib/sublib/precomp/Precompiler.js +6 -0
- package/lib/sublib/precomp/TsxUtils.js +6 -0
- package/lib/sublib/precomp/Utils.js +6 -0
- package/meta/15.0.0/jetauditmeta.js +1 -1
- package/meta/15.1.0/jetauditmeta.js +1 -1
- package/meta/16.0.0/jetauditmeta.js +9 -0
- package/meta/metaverlist.json +1 -1
- package/package.json +10 -7
- package/profiles/best-practice.json +1 -0
- package/rulepacks/csp/csp-json-unsafe-expr.js +1 -1
- package/rulepacks/jetwc/jetwc-bootstrap.js +1 -1
- package/rulepacks/jetwc/jetwc-require-paths.js +1 -1
- package/rulepacks/jetwc/jetwc-schema.js +1 -1
- package/rulepacks/jetwc/jetwc-well-formed-description.js +6 -0
- package/rulepacks/jetwc/msgid.json +1 -1
- package/rulepacks/jetwc/rules.json +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-tsxUtils.js +1 -1
- package/rulepacks/jetwco/jetwco-bootstrap.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-methodParamTypes.js +1 -1
- package/rulepacks/jetwco/jetwco-cacc-methodReturnType.js +1 -1
- package/rulepacks/jetwco/jetwco-description-standards.js +1 -1
- package/rulepacks/jetwco/jetwco-license-info.js +1 -1
- package/rulepacks/jetwco/jetwco-validate-applied-audits.js +6 -0
- package/rulepacks/jetwco/msgid.json +1 -1
- package/rulepacks/jetwco/rules.json +1 -1
- package/rulepacks/ojc/msgid.json +1 -1
- package/rulepacks/ojc/ojc-html-button-defslot.js +6 -0
- package/rulepacks/ojc/ojc-tsx-button-defslot.js +6 -0
- package/rulepacks/ojc/rules.json +1 -1
- package/rules/jaf/jaf-css-diagnose.js +1 -1
- package/rules/jaf/jaf-js-diagnose.js +1 -1
- package/rules/jaf/jaf-sys-dup-component.js +6 -0
- package/rules/jaf/jaf-sys-rule-opt.js +6 -0
- package/rules/jaf/jaf-ts-precompile.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/msgid.json +1 -1
- package/rules/jet/oj-cca-compjson-bp-jetver.js +1 -1
- package/rules/jet/oj-html-alta-deprecated.js +1 -1
- package/rules/jet/oj-html-attr-expr-writeback.js +6 -0
- package/rules/jet/oj-html-binding-as-slot-child.js +6 -0
- package/rules/jet/oj-html-event-focus-blur.js +6 -0
- package/rules/jet/oj-html-form-bindif.js +1 -1
- package/rules/jet/oj-html-ojattr-deprecated.js +1 -1
- package/rules/jet/oj-html-ojattr-enum-deprecated.js +1 -1
- package/rules/jet/oj-html-ojattr.js +1 -1
- package/rules/jet/oj-html-ojtag-deprecated.js +1 -1
- package/rules/jet/oj-html-ojtag-nonglobattr-prefix.js +1 -1
- package/rules/jet/oj-html-prop-anti-pattern.js +6 -0
- package/rules/jet/oj-html-slot-default.js +6 -0
- package/rules/jet/oj-html-slot-deprecated.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-deprecated.js +1 -1
- package/rules/jet/oj-html-treeview-actionable-content.js +6 -0
- package/rules/jet/oj-html-wctag-anti-pattern.js +6 -0
- package/rules/jet/oj-html-wctag-maintenance.js +1 -1
- package/rules/jet/oj-html-wctag-supersedes.js +1 -1
- package/rules/jet/oj-js-ojcomp-exist.js +1 -1
- package/rules/jet/oj-ts-ojcomp-exist.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-event.js +6 -0
- package/rules/jet/oj-tsx-ojattr-deprecated.js +1 -1
- package/rules/jet/oj-tsx-ojattr-enum-deprecated.js +1 -1
- 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-pageopts-type.js +1 -1
- package/rules/jet/oj-tsx-picker-attrs.js +1 -1
- package/rules/jet/oj-tsx-popup-sibling.js +6 -0
- package/rules/jet/oj-tsx-prop-anti-pattern.js +6 -0
- package/rules/jet/oj-tsx-rating-gauge-size.js +1 -1
- package/rules/jet/oj-tsx-rating-gauge-track-resize.js +1 -1
- package/rules/jet/oj-tsx-slot-deprecated.js +1 -1
- package/rules/jet/oj-tsx-slot-pref-content.js +1 -1
- package/rules/jet/oj-tsx-treeview-actionable-content.js +6 -0
- package/rules/jet/oj-tsx-unsup-theme.js +1 -1
- package/rules/jet/oj-tsx-wctag-anti-pattern.js +6 -0
- package/rules/jet/oj-tsx-wctag-maintenance.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 +1 -0
- package/rulepacks/jetwc-lib/jetwcutils-preCompiler.js +0 -6
- package/rules/jet/oj-html-combo-converter.js +0 -6
- package/rules/jet/oj-tsx-combo-converter.js +0 -6
package/lib/Stats.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 Stats=function(){this.errors=0;this.warnings=0;this.asserts=0;this.totalFilesSelected=0;this.totalFilesAudited=0;this.totalIssues=0;this.totalIssueFiles=0;this.errorFiles=0;this.parseErrors=0;this.totalUrlsAudited=0;this.sevStats={
|
|
6
|
+
var Stats=function(){this.errors=0;this.warnings=0;this.asserts=0;this.totalFilesSelected=0;this.totalFilesAudited=0;this.totalIssues=0;this.totalIssueFiles=0;this.errorFiles=0;this.parseErrors=0;this.totalUrlsAudited=0;this.sevStats={blocker:0,critical:0,major:0,minor:0,info:0};this.totalSevStats={blocker:0,critical:0,major:0,minor:0,info:0};this.rulesFired=0;this.hooksFired=0;this.packRulesFired};Stats.prototype.clearAll=function(){this.clearErrWarnAsserts();this.clearFileStats();this.clearSevStats();this.clearTotalSevStats();this.clearRulesFired();this.clearPackRulesFired()};Stats.prototype.clearErrWarnAsserts=function(){this.errors=this.warnings=this.asserts=0};Stats.prototype.clearSevStats=function(){this.sevStats.critical=this.sevStats.blocker=this.sevStats.major=this.sevStats.minor=this.sevStats.info=0};Stats.prototype.clearTotalSevStats=function(){this.totalSevStats.critical=this.totalSevStats.blocker=this.totalSevStats.major=this.totalSevStats.minor=this.totalSevStats.info=0};Stats.prototype.clearFileStats=function(){this.totalIssues=this.totalIssueFiles=this.errorFiles=this.parseErrors=this.totalFilesSelected=this.totalFilesAudited=this.totalUrlsAudited=0};Stats.prototype.clearRulesFired=function(){this.rulesFired=this.hooksFired=0};Stats.prototype.clearPackRulesFired=function(){if(this.packRulesFired){for(let i=0;i<this.packRulesFired.length;i++){let pack=this.packRulesFired[i];if(Object.keys(pack.rules).length){pack.rules={}}}}};Stats.prototype.addSevStatsToTotals=function(clear){this.totalSevStats.critical+=this.sevStats.critical;this.totalSevStats.blocker+=this.sevStats.blocker;this.totalSevStats.major+=this.sevStats.major;this.totalSevStats.minor+=this.sevStats.minor;this.totalSevStats.info+=this.sevStats.info;if(clear){this.clearSevStats()}};module.exports=Stats;
|
package/lib/Ts.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const AST=require("../lib/AST_Ts");const Comments=require("../lib/Comments");const JSX=require("../lib/jsx");const VAR_DECL="VariableDeclarator";const CALL_EXPR="CallExpression";const RETURN_STMT="ReturnStatement";const ASSIGN_EXPR="AssignmentExpression";function Ts(parser,nd,rules,fileIndex,appCtx,msgCtx){this._parser=parser;this._rules=rules;this._Issue=appCtx.Issue;this._reporter=appCtx.reporter;this._fileIndex=fileIndex;this._utils=appCtx.utils;this._msgCtx=msgCtx;this._nd=nd;this._Ast=null;this._jsx=new JSX(appCtx.metaLib,msgCtx);this._tsxUtils=appCtx.tsxUtils;this._debugMode=msgCtx.debugMode;this._debug=msgCtx.debug;this._error=msgCtx.error;this._info=msgCtx.info;this._verboseMode=msgCtx.isVerbose;this._config=appCtx.config;this._ecmaVer=appCtx.config.getEcmaVer();this._isComments=appCtx.config.getComments();this._reportJafIssue=appCtx.reportJafIssue;this._flushIssues=appCtx.flushIssues;this._runMode=appCtx.runMode};Ts.prototype.parse=function(data,file,fileType){var self=this;this._parseIt(data,file,fileType,function(treenode){let rc=self._parser.fireHookFileRules(treenode,null,false)});this._parser.fireHookFileRules(null,null)};Ts.prototype.hasParser=function(){return!!this._nd.tsparse};Ts.prototype.reportNoParser=function(){let issue=new this._Issue(`.ts/.tsx support not loaded - run mode '${this._runMode}'`);this._reportJafIssue(issue,this._parser.RULE_TS_NO_PARSER,0,0,0,0)};Ts.prototype.getAst=function(){return this._Ast.getAst()};Ts.prototype.getAstUtils=function(){return this._Ast?this._Ast.getUtils():null};Ts.prototype._parseIt=function(data,file,fileType,cb){var ret=false,rowNow,colNow,issue,opts,arRawComs,startPos;try{this._debug(`Parsing ${fileType.toUpperCase()}...`);this._Ast=new AST(data,file,fileType,this._nd,this._ecmaVer,this._isComments,this._msgCtx,this._config);ret=!!this._Ast.getAst()}catch(e){startPos=this._parser.startJsPosition;opts=this._rules.getRuleOptions(this._parser.RULE_TS_DIAGNOSE,this._parser.JAF_RSI);if(opts&&opts.enabled){rowNow=e.lineNumber+(startPos.row===0?0:startPos.row-2);colNow=e.column+(startPos.col===0?0:startPos.col-1);e.message=e.message.replace("}","{");issue=new this._Issue("TypeScript syntax - "+e.message);this._reportJafIssue(issue,this._parser.RULE_TS_DIAGNOSE,rowNow,colNow,e.index+startPos.startIndex,e.index+startPos.startIndex+1)}else{rowNow=e.lineNumber+(startPos.row===0?0:startPos.row-2);colNow=e.column+(startPos.col===0?0:startPos.col-1);console.log(`\nTS-DIAGNOSE : [${rowNow}, ${colNow}] ${e.message}\n File -> ${this._curFile}`)}this._parser.parseErrors++;if(this._debugMode||this._verboseMode){this._info(`[TS PARSE ERROR(4) #${this._parser.parseErrors} : '${e.message}' File -> ${this._parser.curFile?this._parser.curFile:"n/a"}`)}}if(!ret){return ret}if(cb)cb(this._Ast.getProgram());ret=false;try{this._debug("Walking TS...");if(this._isComments){arRawComs=this._Ast.getRawComments();if(arRawComs&&arRawComs.length){if(!this._comments){this._comments=new Comments(this._nd,this._rules,this._msgCtx,this._utils,true)}this._comments.reset(this._Ast)}}this._fileType=fileType;this._Ast.walk(this._AstNodeHandler.bind(this));ret=true}catch(e){this._error(`TypeScript walk failure - ${e} in ${this._parser.curFile}`)}return ret};Ts.prototype._AstNodeHandler=function(node){var coms;if(this._rules.isTypeRegistered(node.type)){if(this._comments){coms=this._comments.isDisabled(node);if(coms&&(!coms.rules||coms.rules.length===0)){return}this._rules.setJSCommentCallback(coms?function(ruleName){var b=coms.rules.includes(ruleName);return!coms.invert?b:!b}:null)}this._rules.fireRules({type:node.type,node:node,position:{offset:this._parser.startJsPosition.startIndex,start:node.range[0],end:node.range[1]},data:this._Ast.getData(),utils:{AstUtils:this._Ast.getUtils(),tsxUtils:this._tsxUtils}},node,this._parser.curFile,this._parser.curFileType,null)}if(this._fileType==="tsx"){if(this._rules.isAnyTsxTypeRegistered()){this._fireTsxRules(node)}}};Ts.prototype._fireTsxRules=function(node){var _self=this;if(node.type===VAR_DECL||node.type===CALL_EXPR||node.type===RETURN_STMT||node.type===ASSIGN_EXPR){let result;if(result=this._jsx.genTsxRenderComponent(node,this._Ast.getData())){let syn=this._rules.getTsxRuleSynopsis();if(syn.isTsxRC){if(!Array.isArray(result)){_fireTsxRules(result)}else{result.forEach(tsxRC=>{_fireTsxRules(tsxRC)})}}if(syn.isTsxWC||syn.isTsxNamedComp||syn.isTsxComp||syn.isTsxElem||syn.isTsxJetWC||syn.isTsxProp){result.components.forEach(tsxComp=>{function _fireTsx(tsxComp){let props;if(syn.isTsxWC&&tsxComp.isWCTag){tsxComp.type="TsxWebComponent";_fireTsxRules(tsxComp)}if(syn.isTsxJetWC){tsxComp.type="TsxJetComponent";_fireTsxRules(tsxComp)}if(syn.isTsxComp){_fireTsxRules(tsxComp)}if(syn.isTsxElem&&!tsxComp.isPreactComp&&!tsxComp.isWCTag&&!tsxComp.NaT){tsxComp.type="TsxElem";_fireTsxRules(tsxComp)}if(syn.isTsxNamedComp){let t="Tsx<"+tsxComp.name+">";if(_self._rules.isTypeRegistered(t)){tsxComp.type=t;_fireTsxRules(tsxComp)}}if(syn.isAnyTsxCompAttr){if(props=tsxComp.properties){props.forEach(prop=>{let t=`Tsx<${tsxComp.name}|${prop.name}>`;if(_self._rules.isTypeRegistered(t)){prop.type=t;_fireTsxRules(prop)}})}}if(syn.isAnyTsxAttr){if(props=tsxComp.properties){props.forEach(prop=>{let t=`Tsx<${prop.name}=>`;if(_self._rules.isTypeRegistered(t)){prop.type=t;_fireTsxRules(prop)}})}}if(syn.isTsxProp){if(props=tsxComp.properties){props.forEach(prop=>{_fireTsxRules(prop)})}}if(tsxComp.children){tsxComp.children.forEach(child=>{_fireTsx(child)})}}_fireTsx(tsxComp)})}}}function _fireTsxRules(tsxObj){_self._rules.fireRules({type:tsxObj.type,node:tsxObj,position:{offset:_self._parser.startJsPosition.startIndex,start:tsxObj.range[0],end:tsxObj.range[1]},data:_self._Ast.getData(),utils:{AstUtils:_self._Ast.getUtils(),tsxUtils:_self._tsxUtils}},tsxObj,_self._parser.curFile,_self._parser.curFileType,
|
|
6
|
+
const AST=require("../lib/AST_Ts");const Comments=require("../lib/Comments");const JSX=require("../lib/jsx");const VAR_DECL="VariableDeclarator";const CALL_EXPR="CallExpression";const RETURN_STMT="ReturnStatement";const ASSIGN_EXPR="AssignmentExpression";const STYLE="style";function Ts(parser,nd,rules,fileIndex,appCtx,msgCtx){this._parser=parser;this._rules=rules;this._Issue=appCtx.Issue;this._reporter=appCtx.reporter;this._fileIndex=fileIndex;this._utils=appCtx.utils;this._msgCtx=msgCtx;this._nd=nd;this._Ast=null;this._jsx=new JSX(appCtx.metaLib,msgCtx);this._tsxUtils=appCtx.tsxUtils;this._debugMode=msgCtx.debugMode;this._debug=msgCtx.debug;this._error=msgCtx.error;this._info=msgCtx.info;this._verboseMode=msgCtx.isVerbose;this._config=appCtx.config;this._ecmaVer=appCtx.config.getEcmaVer();this._isComments=appCtx.config.getComments();this._reportJafIssue=appCtx.reportJafIssue;this._flushIssues=appCtx.flushIssues;this._runMode=appCtx.runMode};Ts.prototype.parse=function(data,file,fileType){var self=this;this._parseIt(data,file,fileType,function(treenode){let rc=self._parser.fireHookFileRules(treenode,null,false)});this._parser.fireHookFileRules(null,null)};Ts.prototype.hasParser=function(){return!!this._nd.tsparse};Ts.prototype.reportNoParser=function(){let issue=new this._Issue(`.ts/.tsx support not loaded - run mode '${this._runMode}'`);this._reportJafIssue(issue,this._parser.RULE_TS_NO_PARSER,0,0,0,0)};Ts.prototype.getAst=function(){return this._Ast.getAst()};Ts.prototype.getAstUtils=function(){return this._Ast?this._Ast.getUtils():null};Ts.prototype._parseIt=function(data,file,fileType,cb){var ret=false,rowNow,colNow,issue,opts,arRawComs,startPos;try{this._debug(`Parsing ${fileType.toUpperCase()}...`);this._Ast=new AST(data,file,fileType,this._nd,this._ecmaVer,this._isComments,this._msgCtx,this._config);ret=!!this._Ast.getAst()}catch(e){startPos=this._parser.startJsPosition;opts=this._rules.getRuleOptions(this._parser.RULE_TS_DIAGNOSE,this._parser.JAF_RSI);if(opts&&opts.enabled){rowNow=e.lineNumber+(startPos.row===0?0:startPos.row-2);colNow=e.column+(startPos.col===0?0:startPos.col-1);e.message=e.message.replace("}","{");issue=new this._Issue("TypeScript syntax - "+e.message);this._reportJafIssue(issue,this._parser.RULE_TS_DIAGNOSE,rowNow,colNow,e.index+startPos.startIndex,e.index+startPos.startIndex+1)}else{rowNow=e.lineNumber+(startPos.row===0?0:startPos.row-2);colNow=e.column+(startPos.col===0?0:startPos.col-1);console.log(`\nTS-DIAGNOSE : [${rowNow}, ${colNow}] ${e.message}\n File -> ${this._curFile}`)}this._parser.parseErrors++;if(this._debugMode||this._verboseMode){this._info(`[TS PARSE ERROR(4) #${this._parser.parseErrors} : '${e.message}' File -> ${this._parser.curFile?this._parser.curFile:"n/a"}`)}}if(!ret){return ret}if(cb)cb(this._Ast.getProgram());ret=false;try{this._debug("Walking TS...");if(this._isComments){arRawComs=this._Ast.getRawComments();if(arRawComs&&arRawComs.length){if(!this._comments){this._comments=new Comments(this._nd,this._rules,this._msgCtx,this._utils,true)}this._comments.reset(this._Ast)}}this._fileType=fileType;if(fileType==="tsx"){if(this._rules.isTypeRegistered("TsxFunction")){let namedFuncs,tsxComps;if(namedFuncs=this._Ast.extractNamedFuncs()){namedFuncs.forEach(tsxFunc=>{tsxFunc.returns.forEach(ret=>{if(tsxComps=this._jsx.genTsxRenderComponent(ret.node,this._Ast.getData())){if(tsxComps.components){tsxComps.components.forEach(tsxComp=>{ret.tsxComponent=tsxComp})}}});this._fireTsxRules(tsxFunc)})}}}this._Ast.walk(this._AstNodeHandler.bind(this));ret=true}catch(e){this._error(`TypeScript walk failure - ${e} in ${this._parser.curFile}`)}return ret};Ts.prototype._AstNodeHandler=function(node){var coms;if(this._rules.isTypeRegistered(node.type)){if(this._comments){coms=this._comments.isDisabled(node);if(coms&&(!coms.rules||coms.rules.length===0)){return}this._rules.setJSCommentCallback(coms?function(ruleName){var b=coms.rules.includes(ruleName);return!coms.invert?b:!b}:null)}this._rules.fireRules({type:node.type,node:node,position:{offset:this._parser.startJsPosition.startIndex,start:node.range[0],end:node.range[1]},data:this._Ast.getData(),utils:{AstUtils:this._Ast.getUtils(),tsxUtils:this._tsxUtils}},node,this._parser.curFile,this._parser.curFileType,null)}if(this._fileType==="tsx"){if(this._rules.isAnyTsxTypeRegistered()){this._fireTsxRules(node)}}};Ts.prototype._fireTsxRules=function(node){var _self=this;if(node.type===VAR_DECL||node.type===CALL_EXPR||node.type===RETURN_STMT||node.type===ASSIGN_EXPR){let result;if(result=this._jsx.genTsxRenderComponent(node,this._Ast.getData())){let syn=this._rules.getTsxRuleSynopsis();if(syn.isTsxRC){if(!Array.isArray(result)){_fireTsxRules(result)}else{result.forEach(tsxRC=>{_fireTsxRules(tsxRC)})}}if(syn.isTsxWC||syn.isTsxNamedComp||syn.isTsxComp||syn.isTsxElem||syn.isTsxJetWC||syn.isTsxProp||syn.isTsxEvent||syn.isTsxStyle){result.components.forEach(tsxComp=>{function _fireTsx(tsxComp){let props;if(syn.isTsxWC&&tsxComp.isWCTag){tsxComp.type="TsxWebComponent";_fireTsxRules(tsxComp)}if(syn.isTsxJetWC){tsxComp.type="TsxJetComponent";_fireTsxRules(tsxComp)}if(syn.isTsxComp){_fireTsxRules(tsxComp)}if(syn.isTsxElem&&!tsxComp.isPreactComp&&!tsxComp.isWCTag&&!tsxComp.NaT){tsxComp.type="TsxElem";_fireTsxRules(tsxComp)}if(syn.isTsxNamedComp){let t="Tsx<"+tsxComp.name+">";if(_self._rules.isTypeRegistered(t)){tsxComp.type=t;_fireTsxRules(tsxComp)}}if(syn.isAnyTsxCompAttr){if(props=tsxComp.properties){props.forEach(prop=>{let t=`Tsx<${tsxComp.name}|${prop.name}>`;if(_self._rules.isTypeRegistered(t)){prop.type=t;_fireTsxRules(prop)}})}}if(syn.isAnyTsxAttr){if(props=tsxComp.properties){props.forEach(prop=>{let t=`Tsx<${prop.name}=>`;if(_self._rules.isTypeRegistered(t)){prop.type=t;_fireTsxRules(prop)}})}}if(syn.isTsxProp){if(props=tsxComp.properties){props.forEach(prop=>{_fireTsxRules(prop)})}}if(syn.isTsxEvent){if(props=tsxComp.properties){props.forEach(prop=>{if(prop.name.startsWith("on")){prop.type="TsxEvent";_fireTsxRules(prop)}})}}if(syn.isTsxStyle){if(props=tsxComp.properties){props.forEach(prop=>{if(prop.name===STYLE){prop.type="TsxStyle";_fireTsxRules(prop)}})}}if(tsxComp.children){tsxComp.children.forEach(child=>{_fireTsx(child)})}}_fireTsx(tsxComp)})}}}else if(node.type==="TsxFunction"){_fireTsxRules(node)}function _fireTsxRules(tsxObj){var arg2=null;if(tsxObj.type!=="TsxRendercomponent"&&tsxObj.type!=="TsxProperty"){arg2=tsxObj.name}_self._rules.fireRules({type:tsxObj.type,node:tsxObj,position:{offset:_self._parser.startJsPosition.startIndex,start:tsxObj.range[0],end:tsxObj.range[1]},data:_self._Ast.getData(),utils:{AstUtils:_self._Ast.getUtils(),tsxUtils:_self._tsxUtils}},tsxObj,_self._parser.curFile,_self._parser.curFileType,arg2)}};Ts.prototype.getAst=function(){return this._Ast};Ts.prototype.clear=function(){};module.exports=Ts;
|
package/lib/TsUtils.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2024, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const PRE_COMPILER=require("./sublib/precomp/Precompiler");const UTILS=require("./sublib/precomp/Utils");const TsUtils=function(jafUtils,fsUtils,msgCtx,semVer,nd){this._jafUtils=jafUtils;this._fsUtils=fsUtils;this._utils=null;this._msgCtx=msgCtx;this._semVer=semVer;this._nd=nd;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._ojetCfg=null;this._preComp=null};TsUtils.prototype.getUtils=function(){if(!this._utils){this._utils=new UTILS(this._ojetCfg,this._jafUtils,this._fsUtils,this._msgCtx,this._nd)}return this._utils};TsUtils.prototype.getPreCompiler=function(){if(!this._preComp){if(this._isDebug){this.msgCtx.debug("Loading precompiler lib...")}this._preComp=new PRE_COMPILER(this.getUtils(),this._jafUtils,this._fsUtils,this._msgCtx,this._semVer,this._nd)}return this._preComp};TsUtils.prototype.setOjetConfig=function(cfg){this._ojetCfg=cfg};module.exports=TsUtils;
|
package/lib/TsxUtils.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const TSX2_UTILS=require("./TsxUtils2");const HTML_UTILS=require("./HtmlUtils");const CB_END="end";const CB_NEXT_COMP="next-comp";const TSX_COMPONENT="TsxComponent";const TSX_PROPERTY="TsxProperty";const TEMPLATE="template";const OJ_DEFER="oj-defer";const OJ_BIND="oj-bind";const BODY="body";var TsxUtils=function(assert){this._fnAssert=assert};TsxUtils.prototype.extractTsxProperties=function(ruleCtx,tsxRC,cb){this._onTsxRC(ruleCtx,tsxRC,cb)};TsxUtils.prototype.getProperty=function(tsxObj,propName){return this._extractProp(tsxObj,propName)};TsxUtils.prototype._extractProp=function(tsxObj,propName){var ret,ot;if(tsxObj&&(ot=tsxObj.type)){if(ot===TSX_PROPERTY){return tsxObj}if(ot===TSX_COMPONENT&&propName){let props,prop,i;if(props=tsxObj.properties){for(i=0;i<props.length;i++){prop=props[i];if(prop.name===propName){ret=prop;break}}}}}return ret};TsxUtils.prototype.getPropertyRawValue=function(tsxComp,name,stripDelims){var prop,ret;if(prop=this.getProperty(tsxComp,name)){ret=prop.valueRaw;if(stripDelims&&ret.charAt(0)==="\""){ret=ret.charAt(1)==="\""?ret="":ret.substring(1,ret.length-1)}}return typeof ret==="string"?ret:null};TsxUtils.prototype.getPropertyValue=function(tsxComp,propName){var tsxProp,ret,obj,i;var a=propName.split(".");var major=a[0];if(tsxProp=this.getProperty(tsxComp,major)){if(a.length===1){return tsxProp.value}if(!this.isPropertyPreactExpr(tsxProp)){return undefined}obj=tsxProp.
|
|
6
|
+
const TSX2_UTILS=require("./TsxUtils2");const HTML_UTILS=require("./HtmlUtils");const CB_END="end";const CB_NEXT_COMP="next-comp";const TSX_COMPONENT="TsxComponent";const TSX_PROPERTY="TsxProperty";const TEMPLATE="template";const OJ_DEFER="oj-defer";const OJ_BIND="oj-bind";const BODY="body";var TsxUtils=function(assert){this._fnAssert=assert;this._metaLib=null};TsxUtils.prototype.extractTsxProperties=function(ruleCtx,tsxRC,cb){this._onTsxRC(ruleCtx,tsxRC,cb)};TsxUtils.prototype.getProperty=function(tsxObj,propName){return this._extractProp(tsxObj,propName)};TsxUtils.prototype._extractProp=function(tsxObj,propName){var ret,ot;if(tsxObj&&(ot=tsxObj.type)){if(ot===TSX_PROPERTY){return tsxObj}if(ot===TSX_COMPONENT&&propName){let props,prop,i;if(props=tsxObj.properties){for(i=0;i<props.length;i++){prop=props[i];if(prop.name===propName){ret=prop;break}}}}}return ret};TsxUtils.prototype.getPropertyRawValue=function(tsxComp,name,stripDelims){var prop,ret;if(prop=this.getProperty(tsxComp,name)){ret=prop.valueRaw;if(stripDelims&&ret.charAt(0)==="\""){ret=ret.charAt(1)==="\""?ret="":ret.substring(1,ret.length-1)}}return typeof ret==="string"?ret:null};TsxUtils.prototype.getPropertyValue=function(tsxComp,propName){var tsxProp,ret,obj,i;var a=propName.split(".");var major=a[0];if(tsxProp=this.getProperty(tsxComp,major)){if(a.length===1){return tsxProp.node.value}if(!this.isPropertyPreactExpr(tsxProp)){return undefined}obj=tsxProp.node.value;for(i=1;i<a.length;i++){major=a.shift();if(!_isObject(obj)){break}if((obj=obj[major])&&_isObject(obj)){continue}break}}return ret};TsxUtils.prototype.getPropertyStringValue=function(tsxObj,propName){var tsxProp,value,ret;if(tsxProp=this._extractProp(tsxObj,propName)){value=tsxProp.node.value;if(value!==null){ret=value.type==="Literal"&&typeof value.value==="string"?value.value:null}}else{ret=null}return ret};TsxUtils.prototype.isPropertyPreactExpr=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){ret=tsxProp.node.value.type==="JSXExpressionContainer"}return ret};TsxUtils.prototype.isPropertyObjectExpr=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){if(tsxProp.node.value.type==="JSXExpressionContainer"){let expr=tsxProp.node.value.expression;ret=expr&&expr.type==="ObjectExpression"}}return ret};TsxUtils.prototype.isPropertyString=function(tsxObj,propName){var tsxProp,ret=false;if(tsxProp=this._extractProp(tsxObj,propName)){ret=tsxProp.node.value.type==="Literal"&&typeof tsxProp.node.value.value==="string"}return ret};TsxUtils.prototype.getAncestor=function(tsxComp,name){var o,ret;name=name||tsxComp.name;while(o=tsxComp.parent){if(o.name===name){ret=o;break}tsxComp=o}return ret||null};TsxUtils.prototype.getChildren=function(tsxComp){return tsxComp.children};TsxUtils.prototype.getDescendant=function(tsxComp,name){var childs,child,ret,i;while(childs=tsxComp.children){for(i=0;i<childs.length;i++){child=childs[i];if(child.name===name){ret=child;break}if(ret=this.getDescendant(child,name)){break}}break}return ret||null};TsxUtils.prototype.getDirectDescendant=function(tsxComp,name){var childs,child,ret,i;if(childs=tsxComp.children){for(i=0;i<childs.length;i++){child=childs[i];if(child.name===name){ret=child;break}}}return ret||null};TsxUtils.prototype.isExpressionObject=function(tsxObj,propName){var tsxProp,ret;if(tsxProp=this._extractProp(tsxObj,propName)){if(tsxProp.node.value.type==="JSXExpressionContainer"){let expr=tsxProp.node.value.expression;ret=expr.type==="ObjectExpression"}}return!!ret};TsxUtils.prototype.getExpressionObject=function(tsxObj,propName){var tsxProp,obj;if(tsxProp=this._extractProp(tsxObj,propName)){if(!tsxProp.node.value){return null}if(tsxProp.node.value.type!=="JSXExpressionContainer"){return null}let expr=tsxProp.node.value.expression;if(expr.type==="ObjectExpression"){let props,stack;props=expr.properties;obj={};stack=[];props.forEach(prop=>{_doProp(prop,obj,stack,this._fnAssert)})}}return obj||null};TsxUtils.prototype.toCamelCase=function(str){return TSX2_UTILS.toCamelCase(str)};TsxUtils.prototype.toKebabCase=function(str){return TSX2_UTILS.toKebabCase(str)};function _doProp(prop,obj,stack,fnAssert){let key,elems,propx;if(prop.type==="Property"&&(prop.key.type==="Identifier"||prop.key.type==="Literal")){if(prop.key.type==="Identifier"){key=prop.key.name}else{key=prop.key.value}if(prop.value.type==="Literal"){obj[key]=prop.value.value}else if(prop.value.type==="Identifier"){obj[key]=prop.value.name}else if(prop.value.type==="ArrayExpression"){obj[key]=[];elems=prop.value.elements;elems.forEach(elem=>{if(elem.type==="Literal"){obj[key].push(elem.value)}else if(elem.type==="ObjectExpression"){elem.properties.forEach(prop=>{stack.push(obj);obj={};propx=_doProp(prop,obj,stack,fnAssert);obj=stack.pop();obj[key].push(propx)})}})}else if(prop.value.type==="FunctionExpression"){obj[key]=prop.value.body.body}else if(prop.value.type==="ObjectExpression"){let o,p,i,objProps=prop.value.properties;stack.push(obj);obj[key]=o={};obj=o;for(i=0;i<objProps.length;i++){p=objProps[i];if(p.key.type==="Identifier"){if(p.value.type==="Literal"){o[p.key.name]=p.value.value}else if(p.value.type==="ObjectExpression"){_doProp(p,obj,stack,fnAssert);obj=stack.pop()}else if(p.value.type==="Identifier"){o[p.key.name]=p.value.name}else if(p.value.type==="ArrowFunctionExpression"){o[p.key.name]=p.value}else{fnAssert(`TsxUtils._doProp file line=${prop?.loc.start.line} ${p.value.type}`)}}}}else if(prop.value.type==="MemberExpression"){obj[key]=prop.value}else if(prop.value.type==="TemplateLiteral"){obj[key]=null}else if(prop.value.type==="LogicalExpression"){obj[key]=prop.value}else if(prop.value.type==="AssignmentPattern"){fnAssert(`TsxUtils._doProp2 file line=${prop?.loc.start.line} key=${key} prop value type=${prop.value.type}`);obj[key]="?"}else{fnAssert(`TsxUtils._doProp2 file line=${prop?.loc.start.line} key=${key} prop value type=${prop.value.type}`);obj[key]="?"}}return obj};TsxUtils.prototype.setIssuePosition=function(issue,obj){if(obj.type===TSX_COMPONENT||obj.type===TSX_PROPERTY){let loc=obj.loc;issue.setPosition(loc.start.line,loc.start.column,obj.range[0],obj.range[1])}else{issue.setPosition(0,0,0,0)}};TsxUtils.prototype.setIssuePropValuePosition=function(issue,tsxProp){if(tsxProp.type==="TsxProperty"){let loc=tsxProp.node.value.loc;issue.setPosition(loc.start.line,loc.start.column,tsxProp.node.value.range[0],tsxProp.node.value.range[1])}else{issue.setPosition(0,0,0,0)}};TsxUtils.prototype.getRawtext=function(ruleCtx,tsxRC){return ruleCtx&&tsxRC&&tsxRC.range?ruleCtx.data.substring(tsxRC.range[0],tsxRC.range[1]):""};TsxUtils.prototype._onTsxRC=function(ruleCtx,tsxRC,cb){var comps,tsxComp,ret,i;if(!(comps=tsxRC.components)){return}for(i=0;i<comps.length;i++){tsxComp=comps[i];ret=this._checkComp(ruleCtx,tsxComp,cb);if(ret===CB_END){break}};cb(ruleCtx,null)};TsxUtils.prototype._checkComp=function(ruleCtx,tsxComp,cb){var props;if(props=tsxComp.properties){let prop,ret,i;for(i=0;i<props.length;i++){prop=props[i];ret=cb(ruleCtx,prop);if(ret===CB_END||ret===CB_NEXT_COMP){return ret}};}if(tsxComp.children){tsxComp.children.forEach(child=>{this._checkComp(ruleCtx,child,cb)})}};TsxUtils.prototype.getSlotParent=function(ruleCtx,tsxProp,slotName){var parent,isOjDefer=false,ret=null;parent=tsxProp.parent;if(!(parent=parent.parent)){return}isOjDefer=parent.name==="oj-defer";if(parent&&parent.name){if(parent.name!==BODY){if(ruleCtx.utils.metaLib.isTagSlotName(parent.name,slotName)){ret=parent}if(!ret){if(isOjDefer&&parent.name===TEMPLATE||parent.name==="oj-switcher"){ret=parent}else if(parent.name===TEMPLATE||parent.name.startsWith(OJ_BIND)||parent.name===OJ_DEFER){ret=_continueUpwards(ruleCtx,parent,slotName)}}}}return ret};TsxUtils.prototype.isChildOfElem=function(elemName,tsxComp){var ret=null;while(tsxComp.parent){if(tsxComp.parent.name===elemName){ret=tsxComp.parent;break}tsxComp=tsxComp.parent}return ret};function _continueUpwards(ruleCtx,tsxComp,slotName){var ret=null,parent,tagName;while(parent=tsxComp.parent){tagName=parent.name;if(tagName===TEMPLATE||tagName.startsWith(OJ_BIND)||tagName===OJ_DEFER){parent=parent.parent;continue}if(parent.name!==BODY){if(ruleCtx.utils.metaLib.isTagSlotName(tagName,slotName)){ret=parent}}break}return ret};function _isObject(value){return typeof value==="object"&&!Array.isArray(value)};TsxUtils.prototype.setMetaLib=function(metaLib){this._metaLib=metaLib};TsxUtils.prototype.isCommonElem=function(elem){return HTML_UTILS.isCommonElem(elem)};TsxUtils.prototype.isCommonAttr=function(attrName){return TSX2_UTILS.isCommonProp(attrName)||this.isAriaAttr(attrName)};TsxUtils.prototype.isCommonEventAttr=function(attrName){return TSX2_UTILS.isCommonEventProp(attrName)};TsxUtils.prototype.isHtml5ObsoleteElem=function(tag){return HTML_UTILS.isHtml5ObsoleteElem(tag)};TsxUtils.prototype.isAriaAttr=function(attr){return HTML_UTILS.isAriaAttr(attr)};TsxUtils.prototype.isSelfClosingTag=function(tag){return HTML_UTILS.isSelfClosingTag(tag)};TsxUtils.prototype.isSvgElem=function(elem){return HTML_UTILS.isSvgElem(elem)};module.exports=TsxUtils;
|
package/lib/TsxUtils2.js
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 DOT=".";const COMMON_PROPS={"accessKey":true,"class":true,"className":true,"contentEditable":true,"contextMenu":true,"dir":true,"draggable":true,"dropZone":true,"forHtml":true,"hidden":true,"id":true,"lang":true,"role":true,"spellCheck":true,"style":true,"tabIndex":true,"title":true,"translate":true};var COMMON_EVENT_PROPS={"onAbort":true,"onAuxClick":true,"onBlur":true,"onCanPlay":true,"onCanPlayThrough":true,"onChange":true,"onClick":true,"onContextMenu":true,"onDblClick":true,"onDrag":true,"onDragEnd":true,"onDragEnter":true,"onDragLeave":true,"onDragOver":true,"onDragStart":true,"onDrop":true,"onDurationChange":true,"onEmptied":true,"onEnded":true,"onError":true,"onFocus":true,"onFormChange":true,"onFormInput":true,"onInput":true,"onInvalid":true,"onKeyDown":true,"onKeyPress":true,"onKeyUp":true,"onLoad":true,"onLoadedData":true,"onLoadedMetadata":true,"onLoadStart":true,"onMouseDown":true,"onMouseMove":true,"onMouseOut":true,"onMouseOver":true,"onMouseUp":true,"onMouseWheel":true,"onPause":true,"onPlay":true,"onPlaying":true,"onProgress":true,"onRateChange":true,"onReadyStateChange":true,"onScroll":true,"onSeeked":true,"onSeeking":true,"onSelect":true,"onShow":true,"onStalled":true,"onSubmit":true,"onSuspend":true,"onTimeUpdate":true,"onVolumeChange":true,"onWaiting":true};module.exports.isCommonProp=function(propName){return COMMON_PROPS[propName]};module.exports.isCommonEventProp=function(propName){return COMMON_EVENT_PROPS[propName]};module.exports.toCamelCase=function(str){var parts,i;function _camelCase(str){return str.replace(/(?:^\w|[A-Z]|\b\w)/g,function(word,index){return index==0?word.toLowerCase():word.toUpperCase()}).replace(/-|\s+/g,"")};parts=str.split(DOT);for(i=0;i<parts.length;i++){parts[i]=_camelCase(parts[i])}return parts.join(DOT)};module.exports.toKebabCase=function(str){return str.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase()};
|
|
6
|
+
const DOT=".";const COMMON_PROPS={"accessKey":true,"class":true,"className":true,"contentEditable":true,"contextMenu":true,"dir":true,"draggable":true,"dropZone":true,"forHtml":true,"hidden":true,"id":true,"lang":true,"role":true,"spellCheck":true,"style":true,"tabIndex":true,"title":true,"translate":true};var COMMON_EVENT_PROPS={"onAbort":true,"onAuxClick":true,"onBlur":true,"onCanPlay":true,"onCanPlayThrough":true,"onChange":true,"onClick":true,"onContextMenu":true,"onDblClick":true,"onDrag":true,"onDragEnd":true,"onDragEnter":true,"onDragLeave":true,"onDragOver":true,"onDragStart":true,"onDrop":true,"onDurationChange":true,"onEmptied":true,"onEnded":true,"onError":true,"onFocus":true,"onFocusIn":true,"onFocusOut":true,"onFormChange":true,"onFormInput":true,"onInput":true,"onInvalid":true,"onKeyDown":true,"onKeyPress":true,"onKeyUp":true,"onLoad":true,"onLoadedData":true,"onLoadedMetadata":true,"onLoadStart":true,"onMouseDown":true,"onMouseEnter":true,"onMouseLeave":true,"onMouseMove":true,"onMouseOut":true,"onMouseOver":true,"onMouseUp":true,"onMouseWheel":true,"onPause":true,"onPlay":true,"onPlaying":true,"onProgress":true,"onRateChange":true,"onReadyStateChange":true,"onReset":true,"onScroll":true,"onSeeked":true,"onSeeking":true,"onSelect":true,"onShow":true,"onStalled":true,"onSubmit":true,"onSuspend":true,"onTimeUpdate":true,"onVolumeChange":true,"onWaiting":true,"onWheel":true};const COMMON_PREACT_EVENTS={"onBlurCapture":true,"onClickCapture":true,"onContextMenuCapture":true,"onDblClickCapture":true,"onDragCapture":true,"onDragEndCapture":true,"onDragEnterCapture":true,"onDragExit":true,"onDragExitCapture":true,"onDragLeaveCapture":true,"onDragOverCapture":true,"onDragStartCapture":true,"onDropCapture":true,"onFocusCapture":true,"onKeyDownCapture":true,"onKeyPressCapture":true,"onKeyUpCapture":true,"onMouseDownCapture":true,"onMouseEnterCapture":true,"onMouseLeaveCapture":true,"onMouseMoveCapture":true,"onmouseoutcapture":true,"onMouseOverCapture":true,"onMouseUpCapture":true,"onPointerCancel":true,"onPointerCancelCapture":true,"onPointerDown":true,"onPointerDownCapture":true,"onPointerEnter":true,"onPointerEnterCapture":true,"onPointerleave":true,"onPointerLeaveCapture":true,"onPointerMove":true,"onPointerMovecapture":true,"onPointerOut":true,"onPointerOutCapture":true,"onPointerOver":true,"onPointerOverCapture":true,"onPointerUp":true,"onPointerUpCapture":true,"onTouchCancel":true,"onTouchCancelCapture":true,"onTouchEnd":true,"onTouchEndCapture":true,"onTouchMove":true,"onToucMmoveCapture":true,"onTouchStart":true,"onToucStartCapture":true,"onWheelCapture":true};module.exports.isCommonProp=function(propName){return COMMON_PROPS[propName]};module.exports.isCommonEventProp=function(propName){return COMMON_EVENT_PROPS[propName]||COMMON_PREACT_EVENTS[propName]};module.exports.toCamelCase=function(str){var parts,i;function _camelCase(str){return str.replace(/(?:^\w|[A-Z]|\b\w)/g,function(word,index){return index==0?word.toLowerCase():word.toUpperCase()}).replace(/-|\s+/g,"")};parts=str.split(DOT);for(i=0;i<parts.length;i++){parts[i]=_camelCase(parts[i])}return parts.join(DOT)};module.exports.toKebabCase=function(str){return str.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase()};
|
package/lib/Utils.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const daysOfWeek=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];const WHITESPACE=" \t\n\r\x0B";const NL="\n";const CR="\r";const DOT=".";const SP=" ";function Utils(nd){this._nd=nd;this._tabHandler=null};Utils.prototype.isObject=function(value){return typeof value==="object"&&!Array.isArray(value)};Utils.prototype.isArrayContentsType=function(ar,type){var i,elemType,ret=true;var isAr=Array.isArray(type);for(i=0;i<ar.length;i++){elemType=this.getType(ar[i]);if(isAr&&!type.includes(elemType)||!isAr&&elemType!==type){ret=false;break}}return ret};Utils.prototype.extend=function(from,internal,to){var prop,what;to=to||{};for(prop in from){if(!internal&&(prop.startsWith("_")||prop==="$builtin")){continue}what=from[prop];if(Array.isArray(what)){to[prop]=what.slice()}else{to[prop]=what}}return to};Utils.prototype.hasAnyProps=function(obj){var ret=false;if(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}}return ret};Utils.prototype.isProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length};Utils.prototype.getProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length?obj:undefined};Utils.prototype.splitString=function(s,sep){var a=s.split(sep);a.forEach(function(val,index){a[index]=a[index].trim()});return a};Utils.prototype.getType=function(val){var t=typeof val;if(val===undefined){t="undefined"}else if(val===null){t="null"}else if(t==="object"){if(Array.isArray(val)){t="array"}else if(this.isObject(val)){t="object"}else{console.log("[ASSERT] unknown object type' "+t+"'");t="?"}}return t};Utils.prototype.format=function(msg,vars){var v,k,k2,i;for(v in vars){k="${"+v+"}";k2=new RegExp("\\$\\{"+v+"\\}","g");i=msg.indexOf(k);if(i>=0){msg=msg.replace(k2,vars[v])}}return msg};Utils.prototype.removeMarkup=function(m){var s;if(!m){return m}s=m.replace(/<[^>]+>/g,"");s=s.replace(/\s\s+/g," ");return s};Utils.prototype.getRowColFromIndex=function(data,disp,fileType,tabs){var row=1,col=1,i,c,len=data.length;var oTabs=tabs?tabs:this._tabHandler;for(i=0;i<len;i++){if(i===disp)break;c=data.charAt(i);if(c==="\n"){row++;col=1}else if(c==="\t"){if(oTabs){col=oTabs.getTabCol(col,fileType)}else{col++}}else if(c!=="\r"){col++}}return{row:row,col:col}};Utils.prototype.decommentJson=function(text){return this._nd.decomment(text)};Utils.prototype.parseJson=function(data,comments){var obj,ret;comments=typeof comments!=="undefined"?!!comments:true;if(comments){data=this._nd.decomment(data)}let x=this.eatWhitespace(data);if(x>=0){let c=data.charAt(x);if(c!=="{"&&c!=="["){return this._convertJsonPosToRowCol(`Invalid JSON - unexpected start character '${c}' at position ${x}`,data)}}try{obj=JSON.parse(data);ret={obj:obj,msg:null,startIndex:undefined,endIndex:undefined}}catch(e){if(e.toString().startsWith("SyntaxError")){ret=this._convertJsonPosToRowCol(e.message,data)}else{ret.msg=e.message}ret.obj=null}return ret};Utils.prototype._convertJsonPosToRowCol=function(msg,data){var x,n,rc;x=msg.indexOf("position");if(x<0){if(msg.startsWith("Unexpected end of JSON")){msg+=` at position ${data.length-1}`;x=msg.indexOf("position")}else{n=data.length-1;return{msg:msg,line:0,row:0,col:0,startIndex:0,endIndex:0}}}n=parseInt(msg.substring(x+8).trim());rc=this.getRowColFromIndex(data,n);x=msg.indexOf("at");if(x>=0){msg=msg.substring(0,x).trimRight()}x=msg.indexOf("token");if(x>=0){x+=6;let c=msg.charAt(x);let q=c==="'"?"\"":"'";msg=msg.substring(0,x)+q+c+q+msg.substring(x+1)}return{msg:msg,line:rc.row,col:rc.col,startIndex:n,endIndex:n}};Utils.prototype.eatLine=function(str,index){var ret,i,c;index=index||0;if(index>str.length){ret=""}for(i=index;i<str.length;i++){c=str.charAt(i);if(c=="\n"){ret=str.substring(i+1);break}}return ret};Utils.prototype.getLineStart=function(data,index){var c;if(data.length&&index>0&&index<data.length){while(--index){c=data.charAt(index);if(c===NL||c===CR){return index+1}}}return 0};Utils.prototype.getIndexToWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(this.isWhitespace(str.charAt(i))){ret=i;break}}return ret};Utils.prototype.eatWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(WHITESPACE.indexOf(str[i])<0){ret=i;break}}return ret};Utils.prototype.isWhitespace=function(c){return WHITESPACE.indexOf(c)>=0};Utils.prototype.isAlpha=function(c){return c>="a"&&c<="z"||c>="A"&&c<="Z"};Utils.prototype.isDigit=function(c){return c>="0"&&c<="9"};Utils.prototype.isAlphaNum=function(c){return this.isAlpha(c)||this.isDigit(c)};Utils.prototype.getCurrentDate=function(dateObj){var date,dayOfweek,tmp;date=dateObj?dateObj:new Date;dayOfweek=daysOfWeek[date.getDay()];date=date.toString();tmp=date.split(" ");tmp[0]=dayOfweek;return dayOfweek+" "+tmp[1]+" "+tmp[2]+", "+tmp[3]};Utils.prototype.getCurrentTime=function(dateObj){var time,hours,mins,zone;var ampm="am";time=dateObj?dateObj:new Date;hours=time.getHours();mins=time.getMinutes();if(hours>12){hours-=12;ampm="pm"}zone=time.toLocaleTimeString("en-us",{timeZoneName:"short"}).split(" ")[2];return hours+":"+(mins<=9?"0":"")+mins+ampm+" "+zone};Utils.prototype.lineWrap=function(text,width=95,clean=true){if(Array.isArray(text)){let i;for(i=0;i<text.length;i++){let s=text[i];let c=s[s.length-1];if(c!==NL&&c!==SP){text[i]=s+SP}}text=text.join("")}if(clean){text=text.replace(/\<p\>/g,NL);text=text.replace(/\<br\>/g,NL);text=text.replace(/\<b\>/g,"");text=text.replace(/\<i\>/g,"");text=text.replace(/\<\/b\>/g,"");text=text.replace(/\<\/i\>/g,"");text=text.replace(/</g,"<");text=text.replace(/>/g,">")}return this.breakLines(text,width)};Utils.prototype.breakLines=function(s,width){var lines=[];var line,start,end,c,x,y;var len=s.length;s=s.trimRight();len=s.length;if(len<width||len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}if(len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}start=0;while(start<len){x=this.eatWhitespace(s,start);if(x>0){start=x}end=start+width;line=s.substring(start,end+1);if(end>=len){if((x=line.indexOf(NL))>=0){lines.push(line.substring(0,x));start+=x+1;continue}lines.push(line);return lines}if(this.isWhitespace(line.charAt(line.length-1))){for(x=line.length-1;this.isWhitespace(s.charAt(x));x--){}x+=start}else{x=end;c=s.charAt(end+1);if(this.isAlphaNum(c)){for(;x>=start;x--){if(this.isWhitespace(s.charAt(x))){break}}}}x++;if(start<x){line=s.substring(start,x).trimRight()}else{line=s.substring(start,end).trimRight();x=end++}if((y=line.indexOf(NL))>=0){line=line.substring(0,y);x=start+y}lines.push(line);start=x}return lines};Utils.prototype.setTabHandler=function(oTabs){this._tabHandler=oTabs};Utils.prototype.removeLink=function(s){if(s){s=s.replace(/<a\b[^>]*>/i,"");s=s.replace(/<\/a>/i,"")}return s};module.exports=Utils;
|
|
6
|
+
const daysOfWeek=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];const WHITESPACE=" \t\n\r\x0B";const NL="\n";const CR="\r";const DOT=".";const SP=" ";function Utils(nd){this._nd=nd;this._tabHandler=null;this._isWindows=nd.os.platform().startsWith("win")};Utils.prototype.isWindows=function(){return this._isWindows};Utils.prototype.isObject=function(value){return typeof value==="object"&&!Array.isArray(value)};Utils.prototype.isArrayContentsType=function(ar,type){var i,elemType,ret=true;var isAr=Array.isArray(type);for(i=0;i<ar.length;i++){elemType=this.getType(ar[i]);if(isAr&&!type.includes(elemType)||!isAr&&elemType!==type){ret=false;break}}return ret};Utils.prototype.extend=function(from,internal,to){var prop,what;to=to||{};for(prop in from){if(!internal&&(prop.startsWith("_")||prop==="$builtin")){continue}what=from[prop];if(Array.isArray(what)){to[prop]=what.slice()}else{to[prop]=what}}return to};Utils.prototype.hasAnyProps=function(obj){var ret=false;if(obj){for(var prop in obj){if(obj.hasOwnProperty(prop)){ret=true;break}}}return ret};Utils.prototype.isProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length};Utils.prototype.getProperty=function(obj,propName){var a,i;a=this.splitString(propName,DOT);for(i=0;i<a.length;i++){if(this.getType(obj)!=="object"||!obj.hasOwnProperty(a[i])){break}obj=obj[a[i]]}return i>=a.length?obj:undefined};Utils.prototype.splitString=function(s,sep){var a=s.split(sep);a.forEach(function(val,index){a[index]=a[index].trim()});return a};Utils.prototype.getType=function(val){var t=typeof val;if(val===undefined){t="undefined"}else if(val===null){t="null"}else if(t==="object"){if(Array.isArray(val)){t="array"}else if(this.isObject(val)){t="object"}else{console.log("[ASSERT] unknown object type' "+t+"'");t="?"}}return t};Utils.prototype.format=function(msg,vars){var v,k,k2,i;for(v in vars){k="${"+v+"}";k2=new RegExp("\\$\\{"+v+"\\}","g");i=msg.indexOf(k);if(i>=0){msg=msg.replace(k2,vars[v])}}return msg};Utils.prototype.removeMarkup=function(m){var s;if(!m){return m}s=m.replace(/<[^>]+>/g,"");s=s.replace(/\s\s+/g," ");return s};Utils.prototype.getRowColFromIndex=function(data,disp,fileType,tabs){var row=1,col=1,i,c,len=data.length;var oTabs=tabs?tabs:this._tabHandler;for(i=0;i<len;i++){if(i===disp)break;c=data.charAt(i);if(c==="\n"){row++;col=1}else if(c==="\t"){if(oTabs){col=oTabs.getTabCol(col,fileType)}else{col++}}else if(c!=="\r"){col++}}return{row:row,col:col}};Utils.prototype.decommentJson=function(text){return this._nd.decomment(text)};Utils.prototype.parseJson=function(data,comments){var obj,ret;comments=typeof comments!=="undefined"?!!comments:true;if(comments){data=this._nd.decomment(data)}let x=this.eatWhitespace(data);if(x>=0){let c=data.charAt(x);if(c!=="{"&&c!=="["){return this._convertJsonPosToRowCol(`Invalid JSON - unexpected start character '${c}' at position ${x}`,data)}}try{obj=JSON.parse(data);ret={obj:obj,msg:null,startIndex:undefined,endIndex:undefined}}catch(e){if(e.toString().startsWith("SyntaxError")){ret=this._convertJsonPosToRowCol(e.message,data)}else{ret.msg=e.message}ret.obj=null}return ret};Utils.prototype._convertJsonPosToRowCol=function(msg,data){var x,n,rc;x=msg.indexOf("position");if(x<0){if(msg.startsWith("Unexpected end of JSON")){msg+=` at position ${data.length-1}`;x=msg.indexOf("position")}else{n=data.length-1;return{msg:msg,line:0,row:0,col:0,startIndex:0,endIndex:0}}}n=parseInt(msg.substring(x+8).trim());rc=this.getRowColFromIndex(data,n);x=msg.indexOf("at");if(x>=0){msg=msg.substring(0,x).trimRight()}x=msg.indexOf("token");if(x>=0){x+=6;let c=msg.charAt(x);let q=c==="'"?"\"":"'";msg=msg.substring(0,x)+q+c+q+msg.substring(x+1)}return{msg:msg,line:rc.row,col:rc.col,startIndex:n,endIndex:n}};Utils.prototype.eatLine=function(str,index){var ret,i,c;index=index||0;if(index>str.length){ret=""}for(i=index;i<str.length;i++){c=str.charAt(i);if(c=="\n"){ret=str.substring(i+1);break}}return ret};Utils.prototype.getLineStart=function(data,index){var c;if(data.length&&index>0&&index<data.length){while(--index){c=data.charAt(index);if(c===NL||c===CR){return index+1}}}return 0};Utils.prototype.getIndexToWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(this.isWhitespace(str.charAt(i))){ret=i;break}}return ret};Utils.prototype.eatWhitespace=function(str,startIndex){var i,len,ret=-1;startIndex=startIndex>=0?startIndex:0;len=str?str.length:0;for(i=startIndex;i<len;i++){if(WHITESPACE.indexOf(str[i])<0){ret=i;break}}return ret};Utils.prototype.isWhitespace=function(c){return WHITESPACE.indexOf(c)>=0};Utils.prototype.isAlpha=function(c){return c>="a"&&c<="z"||c>="A"&&c<="Z"};Utils.prototype.isDigit=function(c){return c>="0"&&c<="9"};Utils.prototype.isAlphaNum=function(c){return this.isAlpha(c)||this.isDigit(c)};Utils.prototype.getCurrentDate=function(dateObj){var date,dayOfweek,tmp;date=dateObj?dateObj:new Date;dayOfweek=daysOfWeek[date.getDay()];date=date.toString();tmp=date.split(" ");tmp[0]=dayOfweek;return dayOfweek+" "+tmp[1]+" "+tmp[2]+", "+tmp[3]};Utils.prototype.getCurrentTime=function(dateObj){var time,hours,mins,zone;var ampm="am";time=dateObj?dateObj:new Date;hours=time.getHours();mins=time.getMinutes();if(hours>12){hours-=12;ampm="pm"}zone=time.toLocaleTimeString("en-us",{timeZoneName:"short"}).split(" ")[2];return hours+":"+(mins<=9?"0":"")+mins+ampm+" "+zone};Utils.prototype.lineWrap=function(text,width=95,clean=true){if(Array.isArray(text)){let i;for(i=0;i<text.length;i++){let s=text[i];let c=s[s.length-1];if(c!==NL&&c!==SP){text[i]=s+SP}}text=text.join("")}if(clean){text=text.replace(/\<p\>/g,NL);text=text.replace(/\<br\>/g,NL);text=text.replace(/\<b\>/g,"");text=text.replace(/\<i\>/g,"");text=text.replace(/\<\/b\>/g,"");text=text.replace(/\<\/i\>/g,"");text=text.replace(/</g,"<");text=text.replace(/>/g,">")}return this.breakLines(text,width)};Utils.prototype.breakLines=function(s,width){var lines=[];var line,start,end,c,x,y;var len=s.length;s=s.trimRight();len=s.length;if(len<width||len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}if(len+1===width&&s.charAt(s.length-1)===DOT){lines.push(s);return lines}start=0;while(start<len){x=this.eatWhitespace(s,start);if(x>0){start=x}end=start+width;line=s.substring(start,end+1);if(end>=len){if((x=line.indexOf(NL))>=0){lines.push(line.substring(0,x));start+=x+1;continue}lines.push(line);return lines}if(this.isWhitespace(line.charAt(line.length-1))){for(x=line.length-1;this.isWhitespace(s.charAt(x));x--){}x+=start}else{x=end;c=s.charAt(end+1);if(this.isAlphaNum(c)){for(;x>=start;x--){if(this.isWhitespace(s.charAt(x))){break}}}}x++;if(start<x){line=s.substring(start,x).trimRight()}else{line=s.substring(start,end).trimRight();x=end++}if((y=line.indexOf(NL))>=0){line=line.substring(0,y);x=start+y}lines.push(line);start=x}return lines};Utils.prototype.setTabHandler=function(oTabs){this._tabHandler=oTabs};Utils.prototype.removeLink=function(s){if(s){s=s.replace(/<a\b[^>]*>/i,"");s=s.replace(/<\/a>/i,"")}return s};module.exports=Utils;
|
package/lib/checkage.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const BUILT="2024-02-
|
|
6
|
+
const BUILT="2024-02-10T16:43:43.237Z";const MAJOR_RELS=2;function CheckAge(burnedInJetVer,msgCtx){this._jetRels=-1;this._msgCtx=msgCtx;this._burnedInMajor=parseInt(burnedInJetVer.split(".")[0])};CheckAge.prototype.checkAge=function(){var curDate;var buildDate;var buildMonth;var monthsToNow;curDate=new Date;buildDate=BUILT==="@BUILT@"?curDate:new Date(BUILT);buildMonth=buildDate.getMonth()+1;monthsToNow=_getElapsedMonths(buildDate,curDate);if(!monthsToNow){this._jetRels=0}else{this._jetRels=_getReleases(buildMonth,monthsToNow);if(this._jetRels>MAJOR_RELS){this._emitMsg(monthsToNow)}}return this._jetRels};CheckAge.prototype.getJafReleaseCount=function(){return this._jetRels};CheckAge.prototype.getMajorReleaseCount=function(major){if(typeof major==="string"){let a=major.split(".");major=parseInt(a[0])}if(isNaN(major)){return this._jetRels}let estimatedMajor=this._burnedInMajor+this._jetRels;return estimatedMajor-major};CheckAge.prototype._emitMsg=function(old){var INDENT=" ".repeat(12);var s,h,p;if(this._jetRels){s=""+this._jetRels;if(this._jetRels===1){h="has";p=""}else{h="have";p="s"}}else{s="at least one";h="has";p=""}var s=`\nThis version of JAF is ${old} month${old===1?"":"s"} old, and there ${h} been ${s} scheduled public\n`+`${INDENT}major JET release${p}, together with JAF updates and fixes. It is strongly\n`+INDENT+"recommended that you install the latest version of JAF. [JAF-9100]\n";this._msgCtx.warn(s,"JAF-9100",true)};function _getElapsedMonths(start,end){return end.getMonth()-start.getMonth()+12*(end.getFullYear()-start.getFullYear())};function _getReleases(buildMonth,months){var toNextRel,releases=0;if(buildMonth===1){toNextRel=0}else if(buildMonth>1&&buildMonth<7){toNextRel=7-buildMonth}else if(buildMonth===7){toNextRel=0}else{toNextRel=13-buildMonth}if((releases=months-toNextRel)>=0){releases=1+Math.floor(releases/6)}else{releases=0}return releases};module.exports=CheckAge;
|
package/lib/defaults.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const defaults={JETVER:"
|
|
6
|
+
const defaults={JETVER:"16.0.0".replace(/(\d*\.\d*)(\.\d*)+$/g,"$1")+".0",THEME:"Alta",ECMAVER:14};module.exports=defaults;
|
package/lib/jsx.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 HtmlUtils=require("./HtmlUtils");const JSXELEMENT="JSXElement";var Jsx=function(metaLib,msgCtx){this._elemStack=[];this._parentStack=[];this._metaLib=metaLib;this._msgCtx=msgCtx};Jsx.prototype.genTsxRenderComponent=function(node,data){var tsxRC;this._data=data;try{switch(node.type){case"VariableDeclarator":tsxRC=this._onDecl(node);break;case"CallExpression":tsxRC=this._onCallExpr(node);break;case"ReturnStatement":tsxRC=this._onReturn(node);break;case"AssignmentExpression":tsxRC=this._onAssignExpr(node);break}}catch(e){this._msgCtx.error(`JAF TSXRC gen internal, file line=${node?.loc.start.line} : ${e}`)}return tsxRC};Jsx.prototype._toTsxRC=function(node,container){var first,tsxComp,curContainer,opelem,oName,props,childs;var isPreact,isJetTag,isWCTag;if(!container&&!first){container={type:"TsxRenderComponent",components:[],range:node.range,loc:node.loc};first=true;this._parentStack.length=this._elemStack.length=0}if(opelem=node.openingElement||node.openingFragment){if(oName=opelem.name){let compName;if(oName.type==="JSXIdentifier"){compName=oName.name}else if(oName.type==="JSXMemberExpression"){compName=oName.object.name+"."+oName.property.name}isPreact=!compName.includes("-")&&!HtmlUtils.isCommonElem(compName)&&compName.charAt(0).toUpperCase()===compName.charAt(0)||compName.includes(".");isJetTag=!isPreact&&this._metaLib.isJetTag(compName);isWCTag=!isPreact&&this._metaLib.isWCTag(compName);tsxComp={type:"TsxComponent",name:compName,elemStack:this._cloneElemStack(),ojNS:this._metaLib.isNamespaceTag(compName),isJetTag:isJetTag,isWCTag:isWCTag,isPreact:isPreact,loc:oName.loc,range:oName.range};this._elemStack.push(tsxComp);if(Array.isArray(container)){container.push(tsxComp)}else{container.components.push(tsxComp)}if((props=_propsToArray(opelem))&&props.length){let aProps,tsxProp;tsxComp.properties=aProps=[];props.forEach(prop=>{tsxProp={type:"TsxProperty"
|
|
6
|
+
const HtmlUtils=require("./HtmlUtils");const JSXELEMENT="JSXElement";const JSXATTRIBUTE="JSXAttribute";const JSXSPREADATTRIBUTE="JSXSpreadAttribute";const IDENTIFIER="Identifier";const MEMBEREXPRESSION="MemberExpression";var Jsx=function(metaLib,msgCtx){this._elemStack=[];this._parentStack=[];this._metaLib=metaLib;this._msgCtx=msgCtx};Jsx.prototype.genTsxRenderComponent=function(node,data){var tsxRC;this._data=data;try{switch(node.type){case"VariableDeclarator":tsxRC=this._onDecl(node);break;case"CallExpression":tsxRC=this._onCallExpr(node);break;case"ReturnStatement":tsxRC=this._onReturn(node);break;case"AssignmentExpression":tsxRC=this._onAssignExpr(node);break}}catch(e){this._msgCtx.error(`JAF TSXRC gen internal, file line=${node?.loc.start.line} : ${e}`)}return tsxRC};Jsx.prototype._toTsxRC=function(node,container){var first,tsxComp,curContainer,opelem,oName,props,childs;var isPreact,isJetTag,isWCTag;if(!container&&!first){container={type:"TsxRenderComponent",components:[],range:node.range,loc:node.loc};first=true;this._parentStack.length=this._elemStack.length=0}if(opelem=node.openingElement||node.openingFragment){if(oName=opelem.name){let compName;if(oName.type==="JSXIdentifier"){compName=oName.name}else if(oName.type==="JSXMemberExpression"){compName=oName.object.name+"."+oName.property.name}isPreact=!compName.includes("-")&&!HtmlUtils.isCommonElem(compName)&&compName.charAt(0).toUpperCase()===compName.charAt(0)||compName.includes(".");isJetTag=!isPreact&&this._metaLib.isJetTag(compName);isWCTag=!isPreact&&this._metaLib.isWCTag(compName);tsxComp={type:"TsxComponent",name:compName,elemStack:this._cloneElemStack(),ojNS:this._metaLib.isNamespaceTag(compName),isJetTag:isJetTag,isWCTag:isWCTag,isPreact:isPreact,loc:oName.loc,range:oName.range,node:node};this._elemStack.push(tsxComp);if(Array.isArray(container)){container.push(tsxComp)}else{container.components.push(tsxComp)}if((props=_propsToArray(opelem))&&props.length){let aProps,tsxProp;tsxComp.properties=aProps=[];props.forEach(prop=>{tsxProp={type:"TsxProperty"};if(prop.type===JSXATTRIBUTE){tsxProp.name=prop?.name?.name}else if(prop.type===JSXSPREADATTRIBUTE){if(prop.argument){if(prop.argument.type===IDENTIFIER){tsxProp.name=prop?.argument?.name}else if(prop.argument.type===MEMBEREXPRESSION){if(prop.argument?.object?.type===IDENTIFIER){tsxProp.name=prop.argument.object.name}else{tsxProp=null}}else{tsxProp=null}}}if(tsxProp){tsxProp.node=prop;tsxProp.loc=prop.loc;tsxProp.range=prop.range;aProps.push(tsxProp)}});this._genPropRawValues(aProps,tsxComp)}if(this._parentStack.length){tsxComp.parent=this._parentStack[this._parentStack.length-1]}this._parentStack.push(tsxComp);tsxComp.valueRaw=this._data.substring(node.range[0],node.range[1]);tsxComp.value=opelem}if(node.type!=="JSXFragment"){if(childs=node.children){childs.forEach(entry=>{if(entry.type===JSXELEMENT){if(!tsxComp.children){tsxComp.children=curContainer=[]}else{curContainer=tsxComp.children}this._toTsxRC(entry,curContainer)}})}this._elemStack.pop();this._parentStack.pop()}else{if(childs=node.children){childs.forEach(entry=>{if(entry.type===JSXELEMENT){this._toTsxRC(entry,container)}})}}}return first?container:tsxComp};Jsx.prototype._onDecl=function(node){var init,tsxRC;if(!((init=node.init)&&(node.init.openingElement||node.init.openingFragment))){return}tsxRC=this._toTsxRC(init);return tsxRC};Jsx.prototype._onCallExpr=function(node){var tsxRC,args,a;if(args=node.arguments){args.forEach(arg=>{if(arg.type===JSXELEMENT){if(tsxRC&&!a){a=[tsxRC]}tsxRC=this._toTsxRC(arg);if(a){a.push(tsxRC)}}})}return a?a:tsxRC;return tsxRC};Jsx.prototype._onReturn=function(node){var tsxRC,arg;if(arg=node.argument){if(arg.type===JSXELEMENT&&arg.openingElement||arg.type==="JSXFragment"){tsxRC=this._toTsxRC(arg)}}return tsxRC};Jsx.prototype._onAssignExpr=function(node){var tsxRC,right;if(right=node.right){if(right.type===JSXELEMENT&&right.openingElement){tsxRC=this._toTsxRC(right)}}return tsxRC};Jsx.prototype._cloneElemStack=function(){return[...this._elemStack]};Jsx.prototype._genPropRawValues=function(props,tsxComp){var node,val,self=this;props.forEach(prop=>{node=prop.node;if(val=node.value){prop.valueRaw=self._data.substring(val.range[0],val.range[1])}prop.parent=tsxComp})};function _propsToArray(node){var props,ret;if(props=node.attributes){ret=[];props.forEach(prop=>{ret.push(prop)})}return ret};module.exports=Jsx;
|
package/lib/migrator.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 run(cwd,rtf,appCtx,fnOpenWriter,JafVersion,fnShowVersion){var mig,isVerboseDebug=rtf.verboseMode||rtf.debugMode;var ctx;fnShowVersion();appCtx.debug("Loading migrator entry-point...");try{if(rtf.outPath){if(!fnOpenWriter(rtf.outPath)){return}}ctx=_makeContext(rtf,appCtx,JafVersion,cwd);mig=new(require("../corePackMigrator/cli"))(ctx)}catch(e){let s="[JAF-9100]: Error loading Migrator support.";if(isVerboseDebug){s+=`\n{e.message}`}appCtx.msg(appCtx.colors.RED(s))}if(!mig){return}appCtx.debug("Checking entry-points...");let isError;if(!mig.run){_missingEntry("run",appCtx);isError=true}if(rtf.unitTest&&!mig.test){_missingEntry("test",appCtx);isError=true}if(isError||rtf.help){return}_displayOptions(ctx,appCtx);appCtx.debug("Invoking migrator...");try{return mig.run()}catch(e){let s,x,i;s=e.stack;if((x=s.indexOf("migrator.js"))>=0){for(i=x;;i--){if(s.charAt(i)==="\n"){s=s.substring(0,i);break}}}appCtx.error(appCtx.colors.RED(`[JAF-9102]: Migrator run failure.\n${s}`))}return 0};function _makeContext(rtf,appCtx,JafVersion,cwd){return{jafVersion:JafVersion,jetVersion:rtf.jetverSet?rtf.jetverSet:appCtx.defaultJetVer,configPath:rtf.configPath||null,cwd:cwd,logPath:rtf.outPath,log:{error:appCtx.error,warn:appCtx.warn,info:appCtx.info,msg:appCtx.msg,console:appCtx.console,debug:appCtx.debug},options:{verboseMode:rtf.verboseMode,debugMode:rtf.debugMode,dryRunMode:rtf.dryRunSet,colorMode:appCtx.colors.isColor(),unitTest:!!rtf.unitTest},utils:{utils:appCtx.utils,fsUtils:appCtx.fsUtils,color:appCtx.colors}}};function _displayOptions(ctx,appCtx){if(ctx.options.debugMode){appCtx.debug("Migrator options:");appCtx.debug(` jafVersion: ${ctx.jafVersion}`);appCtx.debug(` jetVersion: ${ctx.jetVersion}`);appCtx.debug(` configPath: ${ctx.configPath}`);appCtx.debug(` debugMode: ${ctx.options.debugMode}`);appCtx.debug(` verboseMode: ${ctx.options.verboseMode}`);appCtx.debug(` dryRunMode: ${ctx.options.dryRunMode}`);appCtx.debug(` colorMode: ${ctx.options.colorMode}`);appCtx.debug(` logPath: ${ctx.logPath}`);appCtx.debug(` unitTest: ${ctx.options.unitTest}`)}else{appCtx.info(`Migrator log -> ${ctx.logPath}\n`)}};function _missingEntry(method,appCtx){appCtx.error(appCtx.colors.RED(`[JAF-9101]: Migrator linkage support - no ${method}() method exported.`))};module.exports={run};
|
|
6
|
+
function run(cwd,rtf,appCtx,fnOpenWriter,JafVersion,fnShowVersion){var mig,isVerboseDebug=rtf.verboseMode||rtf.debugMode;var ctx;fnShowVersion();appCtx.debug("Loading migrator entry-point...");try{if(rtf.outPath){if(!fnOpenWriter(rtf.outPath)){return}}ctx=_makeContext(rtf,appCtx,JafVersion,cwd);mig=new(require("../corePackMigrator/cli"))(ctx)}catch(e){let s="[JAF-9100]: Error loading Migrator support.";if(isVerboseDebug){s+=`\n{e.message}`}appCtx.msg(appCtx.colors.RED(s))}if(!mig){return}appCtx.debug("Checking entry-points...");let isError;if(!mig.run){_missingEntry("run",appCtx);isError=true}if(rtf.unitTest&&!mig.test){_missingEntry("test",appCtx);isError=true}if(isError||rtf.help){return}_displayOptions(ctx,appCtx);appCtx.debug("Invoking migrator...");try{return mig.run()}catch(e){let s,x,i;s=e.stack;if((x=s.indexOf("migrator.js"))>=0){for(i=x;;i--){if(s.charAt(i)==="\n"){s=s.substring(0,i);break}}}appCtx.error(appCtx.colors.RED(`[JAF-9102]: Migrator run failure.\n${s}`))}return 0};function _makeContext(rtf,appCtx,JafVersion,cwd){return{jafVersion:JafVersion,jetVersion:rtf.jetverSet?rtf.jetverSet:appCtx.defaultJetVer,configPath:rtf.configPath||null,cwd:cwd,logPath:rtf.outPath,log:{error:appCtx.error,warn:appCtx.warn,info:appCtx.info,msg:appCtx.msg,console:appCtx.console,debug:appCtx.debug},options:{verboseMode:rtf.verboseMode,debugMode:rtf.debugMode,dryRunMode:rtf.dryRunSet,colorMode:appCtx.colors.isColor(),unitTest:!!rtf.unitTest},runMode:appCtx.runMode,utils:{utils:appCtx.utils,fsUtils:appCtx.fsUtils,color:appCtx.colors}}};function _displayOptions(ctx,appCtx){if(ctx.options.debugMode){appCtx.debug("Migrator options:");appCtx.debug(` jafVersion: ${ctx.jafVersion}`);appCtx.debug(` jetVersion: ${ctx.jetVersion}`);appCtx.debug(` configPath: ${ctx.configPath}`);appCtx.debug(` debugMode: ${ctx.options.debugMode}`);appCtx.debug(` verboseMode: ${ctx.options.verboseMode}`);appCtx.debug(` dryRunMode: ${ctx.options.dryRunMode}`);appCtx.debug(` colorMode: ${ctx.options.colorMode}`);appCtx.debug(` logPath: ${ctx.logPath}`);appCtx.debug(` unitTest: ${ctx.options.unitTest}`)}else{appCtx.info(`Migrator log -> ${ctx.logPath}\n`)}};function _missingEntry(method,appCtx){appCtx.error(appCtx.colors.RED(`[JAF-9101]: Migrator linkage support - no ${method}() method exported.`))};module.exports={run};
|
package/lib/scaffold.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
4
|
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
5
|
*/
|
|
6
|
-
const DEFAULTS=require("./defaults");const OJET_CONFIG="oraclejetconfig.json";const OJAF_CONFIG="oraclejafconfig.json";const OJAF_DEFAULT_CONFIG="jafconfig.json";const DEPENDENCIES_VER_PROP="@oracle/oraclejet";const PACKAGE_JSON="package.json";const TSCONFIG="tsconfig.json";const SUFFIX_HTML="/**/*.html";const SUFFIX_JS="/**/*.js";const SUFFIX_TS="/**/*.ts";const SUFFIX_CSS="/**/*.css";const SUFFIX_COMPJSON="/**/component.json";const OJET_COMMENT="OJET Based Configuration";const NON_OJET_COMMENT="Default Configuration";const SLASHIFY=/\\\\|\\/g;const STABLE="Stable";var Scaffold=function(cwd,nd,appCtx){this._cwd=_fwdSlashify(cwd);this._nd=nd;this._appCtx=appCtx;this._fsUtils=appCtx.fsUtils;this._ojet=null;this._jetConfig=null;this._jafConfig=null;this._ojetLib=null;this._md5=null};Scaffold.prototype.init=function(){if(!this._initDone){this._ojet=this.isOJET();if(!this._ojet&&this._ojetJafConfigExists()){this._appCtx.warn(`JAF Configuration '${OJAF_CONFIG}' found, but OJET configuration '${OJET_CONFIG}' no longer exists.\n`)}this._initDone=true}return this._ojet};Scaffold.prototype.isOJET=function(){return this._initDone?!!this._jetConfig:this._fsUtils.fileExists(this._nd.path.join(this._cwd,OJET_CONFIG))};Scaffold.prototype.handleOjetConfig=function(isScaffold){var ojetPath,ojafPath,doUpdate=false,temp,hash,tsHash,tsc,tsConfig,jafConfig,defaultExists,error=false;ojetPath=this._nd.path.join(this._cwd,OJET_CONFIG);this._jetConfig=this._nd.jsonLoader.load(ojetPath,this._nd,errMsg=>{this._appCtx.error(errMsg);error=true},false,this._appCtx.utils);if(isScaffold){if(error){this._appCtx.error("Cannot continue with --init");return"error"}else if(this._jetConfig){this._appCtx.msg(`Scaffolding JAF configuration in ${this._getFolderName()} ...`)}else{this._appCtx.error("OJET CLI config not found - cannot continue with --init");return"error"}}if(tsConfig=this._readTsConfig(ojetPath)){try{tsConfig=JSON.stringify(tsConfig)}catch(e){tsConfig=null}}this._ojetLib=this._appCtx.ojetLib=new this._nd.ojetUtils(this._jetConfig,tsConfig,this._cwd);ojafPath=this._nd.path.join(this._cwd,OJAF_CONFIG);if(this._fsUtils.fileExists(ojafPath)){this._jafConfig=this._readJAFConfig(ojafPath);if(this._jafConfig==="error"){return"error"}}if(isScaffold){defaultExists=this._defaultConfigExists();if(this._jafConfig||defaultExists){this._appCtx.warn(`Pre-existing configuration found '${defaultExists?OJAF_DEFAULT_CONFIG:OJAF_CONFIG}' : ojaf will not delete it.`);return"error"}}hash=this._isOjetFileChange(ojetPath);if(this._jafConfig){jafConfig=this._jafConfig;if(hash){if(jafConfig.ojet&&jafConfig.ojet.update){if(this._appCtx.verboseMode||this._appCtx.debugMode){if(hash){this._appCtx.info(`${OJET_CONFIG} change detected - updating ${OJAF_CONFIG}`)}if(tsHash){if(typeof tsHash==="string"){this._appCtx.info(`${TSCONFIG} change detected - updating ${OJAF_CONFIG}`)}else{this._appCtx.info(`${TSCONFIG} no longer found - updating ${OJAF_CONFIG}`)}}}jafConfig.files=this._getFileSet();jafConfig.exclude=this._getExcludes();jafConfig.components=this._getComposites();if(tsc=this._getTsConfigPath()){if(jafConfig.typescript){jafConfig.typescript.tsconfig=tsc}else{jafConfig.typescript={tsconfig:tsc}}}else if(jafConfig.typescript&&jafConfig.typescript.tsconfig){delete jafConfig.typescript}if(jafConfig.tsconfig){delete jafConfig.tsconfig}temp=this._getJetVer();if(jafConfig.jetVer!==temp){jafConfig.jetVer=temp}if(temp=this._getTheme()){if(jafConfig.theme!==temp){jafConfig.theme=temp}}else if(jafConfig.theme){delete jafConfig.theme}if(!jafConfig.ojet){jafConfig.ojet={}}if(hash){jafConfig.ojet.md5=hash}if(typeof jafConfig.ojet.update!=="boolean"){jafConfig.ojet.update=true}if(typeof tsHash==="string"){jafConfig.ojet.tsmd5=tsHash}else if(tsHash&&jafConfig.ojet.tsmd5){delete jafConfig.ojet.tsmd5}doUpdate=true;this._backupJAFConfig(ojafPath)}else{const changeMsg=" changes detected, but oraclejafconfig updates are disabled";if(hash){this._appCtx.warn(OJET_CONFIG+changeMsg)}if(tsHash){this._appCtx.warn(TSCONFIG+changeMsg)}}}}else if(isScaffold){jafConfig={};jafConfig.title=["+---------------------------------------------------------------------+","| OJET Application Audit |","+---------------------------------------------------------------------+","JAF $jafver - Jet $jetver : ($jafdate, $jaftime)\n"];jafConfig.base="$jafcwd";jafConfig.files=this._getFileSet(),jafConfig.exclude=this._getExcludes(),jafConfig.components=this._getComposites(),jafConfig.builtinJetRules=true,jafConfig.jetVer=this._getJetVer(),jafConfig.ecmaVer=DEFAULTS.ECMAVER,jafConfig.format="prose",jafConfig.severity="all",jafConfig.groups=["all"];if(temp=this._getTheme()){jafConfig.theme=temp}if(tsc=this._getTsConfigPath()){jafConfig.typescript={tsconfig:tsc}}if(tsHash){jafConfig.ojet.tsmd5=tsHash}jafConfig.options={verbose:false,color:true};jafConfig.ojet={update:true,md5:hash};this._jafConfig=jafConfig;doUpdate=true}if(doUpdate&&!this._writeJAFConfig(OJAF_CONFIG,true)){this.appCtx.error("Failed to "+(isScaffold?"scaffold":"update")+" OJAF config '"+this._nd.path.join(this._cwd,OJAF_CONFIG)+"'");return"error"}if(isScaffold){this._scaffoldSuccessful(OJAF_CONFIG)}if(this._appCtx.debugMode){this._appCtx.debug("JAFConfig :\n"+JSON.stringify(jafConfig,null,3))}return jafConfig};Scaffold.prototype.getOjetConfig=function(){return this._jetConfig};Scaffold.prototype.getOjetLib=function(){return this._ojetLib?this._ojetLib:new this._nd.ojetUtils(null,null,null)};Scaffold.prototype._getFileSet=function(){var source,src,files=[];if(this._jetConfig&&this._jetConfig.paths){if(source=this._jetConfig.paths.source){if(src=source.common){files.push("./"+src+SUFFIX_HTML);if(source.javascript){files.push("./"+src+SUFFIX_JS)}if(source.typescript){files.push("./"+src+SUFFIX_TS)}files.push("./"+src+SUFFIX_COMPJSON)}if(source.styles){files.push("./"+src+"/"+source.styles+SUFFIX_CSS)}}}return _fwdSlashify(files)};Scaffold.prototype.createNonOjetConfig=function(){var oj;oj=this._ojetJafConfigExists();if(oj||this._defaultConfigExists()){this._appCtx.error("Default configuration '"+(oj?OJAF_CONFIG:OJAF_DEFAULT_CONFIG)+"' exists - terminating --init");return"'error"}this._jafConfig=this._createDefaultNonOjetConfig();this._setFileProps(this._jafConfig);if(!this._writeJAFConfig(OJAF_DEFAULT_CONFIG,false)){this._appCtx.error("Failed to scaffold OJAF config '"+OJAF_DEFAULT_CONFIG+"'");return"error"}this._scaffoldSuccessful(OJAF_DEFAULT_CONFIG)};Scaffold.prototype._getExcludes=function(){var files=[],source;if(this._jetConfig.paths&&this._jetConfig.paths.source){source=this._jetConfig.paths.source.common;files.push("./"+this._nd.path.join(source,"**"+"/"+"*-min.js"));files.push("./"+this._nd.path.join(source,"**"+"/"+"*-min.css"));files.push("./**/node_modules/**/*.*")}return _fwdSlashify(files)};Scaffold.prototype._getComposites=function(){var a=[],dir;if(this._jetConfig.paths&&this._jetConfig.paths.exchangeComponents){dir="./exchange_components/**/component.json"}else{dir="./jet_components/**/component.json"}a.push(dir);if(dir=_getOjCPackComponentJson()){a.push(dir)}return _fwdSlashify(a)};function _getOjCPackComponentJson(){};Scaffold.prototype._getTsConfigPath=function(){return this._tsConfigExists()?".":null};Scaffold.prototype._getJetVer=function(){var i,ojetPackage,ver,error;var _self=this;ojetPackage=this._nd.jsonLoader.load(this._nd.path.join(this._cwd,PACKAGE_JSON),this._nd,function(errMsg){_self._appCtx.error(errMsg);_self._appCtx.warn("Defaulting to "+_self._appCtx.defaultJetVer);error=true});if(!error&&ojetPackage&&ojetPackage.dependencies){ver=ojetPackage.dependencies[DEPENDENCIES_VER_PROP];if(ver){for(i=0;i<ver.length;i++){if(!isNaN(ver.charAt(i))){ver=ver.substring(i);break}}ver=ver.replace(".tgz","");i=ver.lastIndexOf(".");ver=ver.substring(0,i)}}return ver?ver:this._appCtx.defaultJetVer};Scaffold.prototype._getTheme=function(){var dt=this._jetConfig.defaultTheme;if(dt){dt=dt.charAt(0).toUpperCase()+dt.substring(1).toLowerCase();if(dt===STABLE){dt="Redwood"}}return dt};Scaffold.prototype._getFolderName=function(){return this._nd.path.basename(this._cwd)};Scaffold.prototype._readJAFConfig=function(path){var error;var _self=this;var json=this._nd.jsonLoader.load(path,this._nd,function(errMsg){_self._appCtx.error(errMsg);error=true},true,this._appCtx.utils);if(error){this._appCtx.error(`JSON syntax error -> '${path}`)}return error?"error":json};Scaffold.prototype._writeJAFConfig=function(name,isOjet){var data,ret=false;try{data=`// JAF Generated ${isOjet?OJET_COMMENT:NON_OJET_COMMENT}\n// Updated: ${new Date().toString()}\n\n${JSON.stringify(this._jafConfig,null,3)}`;this._nd.fs.writeFileSync(this._nd.path.join(this._cwd,name),data);ret=true}catch(e){this._appCtx.error(e)}return ret};Scaffold.prototype._backupJAFConfig=function(fp){var data,ret=false;try{data=this._readFile(fp);if(data){this._nd.fs.writeFileSync(fp+".bak",data);ret=true}}catch(e){this._appCtx.error(e)}return ret};Scaffold.prototype._isOjetFileChange=function(ojPath){if(!this._md5){this._md5=require("md5")}var ojetMd5,ojafMd5;var jafConfig=this._jafConfig;ojetMd5=this._md5(this._readFile(ojPath));ojafMd5=jafConfig&&jafConfig.ojet&&jafConfig.ojet.md5;return ojetMd5!==ojafMd5?ojetMd5:false};Scaffold.prototype._readTsConfig=function(ojPath){var p,ret=false;p=this._nd.path.join(ojPath,TSCONFIG);if(this._fsUtils.fileExists(p)){ret=this._readFile(p)}return ret};Scaffold.prototype._readFile=function(fp){var data;try{data=this._nd.fs.readFileSync(fp,"utf8")}catch(e){}return typeof data==="string"?data:null};function _fwdSlashify(path){if(Array.isArray(path)){for(var i=0;i<path.length;i++){path[i]=path[i].replace(SLASHIFY,"/")}return path}else if(path){return path.replace(SLASHIFY,"/")}};Scaffold.prototype._createDefaultNonOjetConfig=function(){var o={"base":"$jafcwd","files":[],"exclude":[],"components":["./jet_components/**/component.json"],"builtinJetRules":true,"jetVer":this._appCtx.defaultJetVer,"ecmaVer":DEFAULTS.ECMAVER,"groups":["all"],"format":"prose","severity":"all","options":{verbose:false,color:true},"title":["+---------------------------------------------------------------------+","| Application Audit |","+---------------------------------------------------------------------+","JAF $jafver - Jet $jetver : ($jafdate, $jaftime)\n"]};if(this._tsConfigExists()){o.typescript={tsconfig:this._cwd}}return o};Scaffold.prototype._setFileProps=function(obj){var path,folder;folder="src";if(path=this._getPathTo(folder)){obj.files.push(path+"/**/*.html");obj.files.push(path+"/**/*.js");obj.files.push(path+"/**/*.ts");obj.files.push(path+"/**/*.css");obj.exclude.push(path+"/**/*-min.js");obj.exclude.push(path+"/**/*-min.css")}folder="jet-composites";path=this._getPathTo(folder);if(path){obj.components=[path];obj.exclude.push(path+"/**/extension/**/*.*");obj.exclude.push(path+"/**/resources/**/*.*")}obj.exclude.push("./**/node_modules/**/*.*")};Scaffold.prototype._getPathTo=function(folder){var path=this._fsUtils.findFile(this._cwd,folder,function(dir,file){return file!=="node_modules"&&!dir.includes("node_modules")});if(path){path=this._nd.path.join(path,folder);path=_fwdSlashify(path);path="."+path.replace(this._cwd,"")}else{path=null}return path};Scaffold.prototype._defaultConfigExists=function(){var file=this._nd.path.join(this._cwd,OJAF_DEFAULT_CONFIG);return this._fsUtils.fileExists(file)};Scaffold.prototype._ojetJafConfigExists=function(){var file=this._nd.path.join(this._cwd,OJAF_CONFIG);return this._fsUtils.fileExists(file)};Scaffold.prototype._tsConfigExists=function(){var file=this._nd.path.join(this._cwd,TSCONFIG);return this._fsUtils.fileExists(file)};Scaffold.prototype._scaffoldSuccessful=function(configName){var msg=this._appCtx.msg;msg(" __ ___");msg(" __ / /___ _/ _/ Configuration generation successful");msg(" / // // _ `/ _/ created: '@@'".replace("@@",configName));msg(" \\___/ \\_,_/_/\n")};module.exports=Scaffold;
|
|
6
|
+
const DEFAULTS=require("./defaults");const OJET_CONFIG="oraclejetconfig.json";const OJAF_CONFIG="oraclejafconfig.json";const OJAF_DEFAULT_CONFIG="jafconfig.json";const DEPENDENCIES_VER_PROP="@oracle/oraclejet";const PACKAGE_JSON="package.json";const TSCONFIG="tsconfig.json";const SUFFIX_HTML="/**/*.html";const SUFFIX_JS="/**/*.js";const SUFFIX_TS="/**/*.ts";const SUFFIX_CSS="/**/*.css";const SUFFIX_COMPJSON="/**/component.json";const OJET_COMMENT="OJET Based Configuration";const NON_OJET_COMMENT="Default Configuration";const SLASHIFY=/\\\\|\\/g;const STABLE="Stable";var Scaffold=function(cwd,nd,appCtx){this._cwd=_fwdSlashify(cwd);this._nd=nd;this._appCtx=appCtx;this._fsUtils=appCtx.fsUtils;this._ojet=null;this._jetConfig=null;this._jafConfig=null;this._ojetLib=null;this._md5=null};Scaffold.prototype.init=function(){if(!this._initDone){this._ojet=this.isOJET();if(!this._ojet&&this._ojetJafConfigExists()){this._appCtx.warn(`JAF Configuration '${OJAF_CONFIG}' found, but OJET configuration '${OJET_CONFIG}' no longer exists.\n`)}this._initDone=true}return this._ojet};Scaffold.prototype.isOJET=function(){return this._initDone?!!this._jetConfig:this._fsUtils.fileExists(this._nd.path.join(this._cwd,OJET_CONFIG))};Scaffold.prototype.handleOjetConfig=function(isScaffold){var ojetPath,ojafPath,doUpdate=false,temp,hash,tsHash,tsc,tsConfig,jafConfig,defaultExists,error=false;ojetPath=this._nd.path.join(this._cwd,OJET_CONFIG);this._jetConfig=this._nd.jsonLoader.load(ojetPath,this._nd,errMsg=>{this._appCtx.error(errMsg);error=true},false,this._appCtx.utils);if(isScaffold){if(error){this._appCtx.error("Cannot continue with --init");return"error"}else if(this._jetConfig){this._appCtx.msg(`Scaffolding JAF configuration in ${this._getFolderName()} ...`)}else{this._appCtx.error("OJET CLI config not found - cannot continue with --init");return"error"}}if(tsConfig=this._readTsConfig(ojetPath)){try{tsConfig=JSON.stringify(tsConfig)}catch(e){tsConfig=null}}this._ojetLib=this._appCtx.ojetLib=new this._nd.ojetUtils(this._jetConfig,tsConfig,this._cwd);ojafPath=this._nd.path.join(this._cwd,OJAF_CONFIG);if(this._fsUtils.fileExists(ojafPath)){this._jafConfig=this._readJAFConfig(ojafPath);if(this._jafConfig==="error"){return"error"}}if(isScaffold){defaultExists=this._defaultConfigExists();if(this._jafConfig||defaultExists){this._appCtx.warn(`Pre-existing configuration found '${defaultExists?OJAF_DEFAULT_CONFIG:OJAF_CONFIG}' : ojaf will not delete it.`);return"error"}}hash=this._isOjetFileChange(ojetPath);if(this._jafConfig){jafConfig=this._jafConfig;if(hash){if(jafConfig.ojet&&jafConfig.ojet.update){if(this._appCtx.verboseMode||this._appCtx.debugMode){if(hash){this._appCtx.info(`${OJET_CONFIG} change detected - updating ${OJAF_CONFIG}`)}if(tsHash){if(typeof tsHash==="string"){this._appCtx.info(`${TSCONFIG} change detected - updating ${OJAF_CONFIG}`)}else{this._appCtx.info(`${TSCONFIG} no longer found - updating ${OJAF_CONFIG}`)}}}jafConfig.files=this._getFileSet();jafConfig.exclude=this._getExcludes();jafConfig.components=this._getComposites();if(tsc=this._getTsConfigPath()){if(jafConfig.typescript){jafConfig.typescript.tsconfig=tsc}else{jafConfig.typescript={tsconfig:tsc}}}else if(jafConfig.typescript&&jafConfig.typescript.tsconfig){delete jafConfig.typescript}if(jafConfig.tsconfig){delete jafConfig.tsconfig}temp=this._getJetVer();if(jafConfig.jetVer!==temp){jafConfig.jetVer=temp}if(temp=this._getTheme()){if(jafConfig.theme!==temp){jafConfig.theme=temp}}else if(jafConfig.theme){delete jafConfig.theme}if(!jafConfig.ojet){jafConfig.ojet={}}if(hash){jafConfig.ojet.md5=hash}if(typeof jafConfig.ojet.update!=="boolean"){jafConfig.ojet.update=true}if(typeof tsHash==="string"){jafConfig.ojet.tsmd5=tsHash}else if(tsHash&&jafConfig.ojet.tsmd5){delete jafConfig.ojet.tsmd5}doUpdate=true;this._backupJAFConfig(ojafPath)}else{const changeMsg=" changes detected, but oraclejafconfig updates are disabled";if(hash){this._appCtx.warn(OJET_CONFIG+changeMsg)}if(tsHash){this._appCtx.warn(TSCONFIG+changeMsg)}}}}else if(isScaffold){jafConfig={};jafConfig.title=["+---------------------------------------------------------------------+","| OJET Application Audit |","+---------------------------------------------------------------------+","JAF $jafver - Jet $jetver : ($jafdate, $jaftime)\n"];jafConfig.base="$jafcwd";jafConfig.files=this._getFileSet(),jafConfig.exclude=this._getExcludes(),jafConfig.components=this._getComposites(),jafConfig.builtinJetRules=true,jafConfig.jetVer=this._getJetVer(),jafConfig.ecmaVer=DEFAULTS.ECMAVER,jafConfig.format="prose",jafConfig.severity="all",jafConfig.groups=["all"];if(temp=this._getTheme()){jafConfig.theme=temp}if(tsc=this._getTsConfigPath()){jafConfig.typescript={compile:true}}if(tsHash){jafConfig.ojet.tsmd5=tsHash}jafConfig.options={verbose:false,color:true};jafConfig.ojet={update:true,md5:hash};this._jafConfig=jafConfig;doUpdate=true}if(doUpdate&&!this._writeJAFConfig(OJAF_CONFIG,true)){this.appCtx.error("Failed to "+(isScaffold?"scaffold":"update")+" OJAF config '"+this._nd.path.join(this._cwd,OJAF_CONFIG)+"'");return"error"}if(isScaffold){this._scaffoldSuccessful(OJAF_CONFIG)}if(this._appCtx.debugMode){this._appCtx.debug("JAFConfig :\n"+JSON.stringify(jafConfig,null,3))}return jafConfig};Scaffold.prototype.getOjetConfig=function(){return this._jetConfig};Scaffold.prototype.getOjetLib=function(){return this._ojetLib?this._ojetLib:new this._nd.ojetUtils(null,null,null)};Scaffold.prototype._getFileSet=function(){var source,src,files=[];if(this._jetConfig&&this._jetConfig.paths){if(source=this._jetConfig.paths.source){if(src=source.common){files.push("./"+src+SUFFIX_HTML);if(source.javascript){files.push("./"+src+SUFFIX_JS)}if(source.typescript){files.push("./"+src+SUFFIX_TS)}files.push("./"+src+SUFFIX_COMPJSON)}if(source.styles){files.push("./"+src+"/"+source.styles+SUFFIX_CSS)}}}return _fwdSlashify(files)};Scaffold.prototype.createNonOjetConfig=function(){var oj;oj=this._ojetJafConfigExists();if(oj||this._defaultConfigExists()){this._appCtx.error("Default configuration '"+(oj?OJAF_CONFIG:OJAF_DEFAULT_CONFIG)+"' exists - terminating --init");return"'error"}this._jafConfig=this._createDefaultNonOjetConfig();this._setFileProps(this._jafConfig);if(!this._writeJAFConfig(OJAF_DEFAULT_CONFIG,false)){this._appCtx.error("Failed to scaffold OJAF config '"+OJAF_DEFAULT_CONFIG+"'");return"error"}this._scaffoldSuccessful(OJAF_DEFAULT_CONFIG)};Scaffold.prototype._getExcludes=function(){var files=[],source;if(this._jetConfig.paths&&this._jetConfig.paths.source){source=this._jetConfig.paths.source.common;files.push("./"+this._nd.path.join(source,"**"+"/"+"*-min.js"));files.push("./"+this._nd.path.join(source,"**"+"/"+"*-min.css"));files.push("./**/node_modules/**/*.*")}return _fwdSlashify(files)};Scaffold.prototype._getComposites=function(){var a=[],dir;if(this._jetConfig.paths&&this._jetConfig.paths.exchangeComponents){dir="./exchange_components/**/component.json"}else{dir="./jet_components/**/component.json"}a.push(dir);if(dir=_getOjCPackComponentJson()){a.push(dir)}return _fwdSlashify(a)};function _getOjCPackComponentJson(){};Scaffold.prototype._getTsConfigPath=function(){return this._tsConfigExists()?".":null};Scaffold.prototype._getJetVer=function(){var i,ojetPackage,ver,error;var _self=this;ojetPackage=this._nd.jsonLoader.load(this._nd.path.join(this._cwd,PACKAGE_JSON),this._nd,function(errMsg){_self._appCtx.error(errMsg);_self._appCtx.warn("Defaulting to "+_self._appCtx.defaultJetVer);error=true});if(!error&&ojetPackage&&ojetPackage.dependencies){ver=ojetPackage.dependencies[DEPENDENCIES_VER_PROP];if(ver){for(i=0;i<ver.length;i++){if(!isNaN(ver.charAt(i))){ver=ver.substring(i);break}}ver=ver.replace(".tgz","");i=ver.lastIndexOf(".");ver=ver.substring(0,i)}}return ver?ver:this._appCtx.defaultJetVer};Scaffold.prototype._getTheme=function(){var dt=this._jetConfig.defaultTheme;if(dt){dt=dt.charAt(0).toUpperCase()+dt.substring(1).toLowerCase();if(dt===STABLE){dt="Redwood"}}return dt};Scaffold.prototype._getFolderName=function(){return this._nd.path.basename(this._cwd)};Scaffold.prototype._readJAFConfig=function(path){var error;var _self=this;var json=this._nd.jsonLoader.load(path,this._nd,function(errMsg){_self._appCtx.error(errMsg);error=true},true,this._appCtx.utils);if(error){this._appCtx.error(`JSON syntax error -> '${path}`)}return error?"error":json};Scaffold.prototype._writeJAFConfig=function(name,isOjet){var data,ret=false;try{data=`// JAF Generated ${isOjet?OJET_COMMENT:NON_OJET_COMMENT}\n// Updated: ${new Date().toString()}\n\n${JSON.stringify(this._jafConfig,null,3)}`;this._nd.fs.writeFileSync(this._nd.path.join(this._cwd,name),data);ret=true}catch(e){this._appCtx.error(e)}return ret};Scaffold.prototype._backupJAFConfig=function(fp){var data,ret=false;try{data=this._readFile(fp);if(data){this._nd.fs.writeFileSync(fp+".bak",data);ret=true}}catch(e){this._appCtx.error(e)}return ret};Scaffold.prototype._isOjetFileChange=function(ojPath){if(!this._md5){this._md5=require("md5")}var ojetMd5,ojafMd5;var jafConfig=this._jafConfig;ojetMd5=this._md5(this._readFile(ojPath));ojafMd5=jafConfig&&jafConfig.ojet&&jafConfig.ojet.md5;return ojetMd5!==ojafMd5?ojetMd5:false};Scaffold.prototype._readTsConfig=function(ojPath){var p,ret=false;p=this._nd.path.join(ojPath,TSCONFIG);if(this._fsUtils.fileExists(p)){ret=this._readFile(p)}return ret};Scaffold.prototype._readFile=function(fp){var data;try{data=this._nd.fs.readFileSync(fp,"utf8")}catch(e){}return typeof data==="string"?data:null};function _fwdSlashify(path){if(Array.isArray(path)){for(var i=0;i<path.length;i++){path[i]=path[i].replace(SLASHIFY,"/")}return path}else if(path){return path.replace(SLASHIFY,"/")}};Scaffold.prototype._createDefaultNonOjetConfig=function(){var o={"base":"$jafcwd","files":[],"exclude":[],"components":["./jet_components/**/component.json"],"builtinJetRules":true,"jetVer":this._appCtx.defaultJetVer,"ecmaVer":DEFAULTS.ECMAVER,"groups":["all"],"format":"prose","severity":"all","options":{verbose:false,color:true},"title":["+---------------------------------------------------------------------+","| Application Audit |","+---------------------------------------------------------------------+","JAF $jafver - Jet $jetver : ($jafdate, $jaftime)\n"]};if(this._tsConfigExists()){o.typescript={compile:true}}return o};Scaffold.prototype._setFileProps=function(obj){var path,folder;folder="src";if(path=this._getPathTo(folder)){obj.files.push(path+"/**/*.html");obj.files.push(path+"/**/*.js");obj.files.push(path+"/**/*.ts");obj.files.push(path+"/**/*.css");obj.exclude.push(path+"/**/*-min.js");obj.exclude.push(path+"/**/*-min.css")}folder="jet-composites";path=this._getPathTo(folder);if(path){obj.components=[path];obj.exclude.push(path+"/**/extension/**/*.*");obj.exclude.push(path+"/**/resources/**/*.*")}obj.exclude.push("./**/node_modules/**/*.*")};Scaffold.prototype._getPathTo=function(folder){var path=this._fsUtils.findFile(this._cwd,folder,function(dir,file){return file!=="node_modules"&&!dir.includes("node_modules")});if(path){path=this._nd.path.join(path,folder);path=_fwdSlashify(path);path="."+path.replace(this._cwd,"")}else{path=null}return path};Scaffold.prototype._defaultConfigExists=function(){var file=this._nd.path.join(this._cwd,OJAF_DEFAULT_CONFIG);return this._fsUtils.fileExists(file)};Scaffold.prototype._ojetJafConfigExists=function(){var file=this._nd.path.join(this._cwd,OJAF_CONFIG);return this._fsUtils.fileExists(file)};Scaffold.prototype._tsConfigExists=function(){var file=this._nd.path.join(this._cwd,TSCONFIG);return this._fsUtils.fileExists(file)};Scaffold.prototype._scaffoldSuccessful=function(configName){var msg=this._appCtx.msg;msg(" __ ___");msg(" __ / /___ _/ _/ Configuration generation successful");msg(" / // // _ `/ _/ created: '@@'".replace("@@",configName));msg(" \\___/ \\_,_/_/\n")};module.exports=Scaffold;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2024, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
var path;const ComponentFinder=function(preCompUtils,jafUtils,fsUtils,tsxUtils,msgCtx,nd){this._Utils=preCompUtils;this._jafUtils=jafUtils;this._fsUtils=fsUtils;this._tsxUtils=tsxUtils;this._msgCtx=msgCtx;path=nd.path;this.runOnce=false};ComponentFinder.prototype.findAllComponents=function(projectPathInfo,componentRoots,precompileCache){let masterComponentList=[];if(!this.runOnce){if(projectPathInfo.exchangeCacheFolder){masterComponentList=masterComponentList.concat(this._discoverComponentsFromRoot(path.join(projectPathInfo.base,projectPathInfo.exchangeCacheFolder),false,false,null,null))}if(componentRoots&&componentRoots.length>0){componentRoots.forEach(root=>{let target=root;if(this._fsUtils.getFileTypeSync(target)==="f"){target=path.dirname(root);this.msgCtx.msg(`Warning: Incorrectly defined "components" array entry in JAF configuration file. Entries should list folders only not explicit file names.\n Bad entry: "${root}"\nAudit will process the "${target}" folder instead.\n`)}masterComponentList=masterComponentList.concat(this._discoverComponentsFromRoot(target,true,projectPathInfo.isBuiltOutput,null,precompileCache))})}else{if(projectPathInfo.componentRootFolder){masterComponentList=masterComponentList.concat(this._discoverComponentsFromRoot(path.join(projectPathInfo.base,projectPathInfo.jsSource,projectPathInfo.componentRootFolder),true,projectPathInfo.isBuiltOutput,null,precompileCache));if(projectPathInfo.tsSource&&projectPathInfo.tsSource!==projectPathInfo.jsSource){masterComponentList=masterComponentList.concat(this._discoverComponentsFromRoot(path.join(projectPathInfo.base,projectPathInfo.tsSource,projectPathInfo.componentRootFolder),true,false,null,precompileCache))}}}this.runOnce=true;this.masterComponentList=masterComponentList}return this.masterComponentList};ComponentFinder.prototype._discoverComponentsFromRoot=function(rootDir,isLocal,builtOutput,parentPack,precompileCache){let componentArray=[];if(!this._fsUtils.pathExistsSync(rootDir)){return componentArray}const compFileStructure=this._fsUtils.readDir(rootDir);compFileStructure.forEach(l1file=>{let componentInfo;if(!l1file.isFile&&l1file.files.length>0){l1file.files.forEach(l2file=>{if(!builtOutput){if(l2file.isFile&&l2file.name==="component.json"){componentInfo=this._Utils.extractComponentInfoFromJSONFile(path.join(rootDir,l1file.name),"component.json",isLocal,false);componentArray.push(componentInfo);if(componentInfo.type&&componentInfo.type==="pack"){const packMembers=this._discoverComponentsFromRoot(this._Utils.toJAFPath(path.join(rootDir,l1file.name)),isLocal,false,componentInfo.name,precompileCache);componentArray=componentArray.concat(packMembers)}}else if(l2file.isFile&&path.extname(l2file.name)===".tsx"&&precompileCache){componentInfo=this._tsxUtils.extractComponentInfoFromTSXFile(path.join(rootDir,l1file.name),l2file.name,isLocal,precompileCache);if(componentInfo){componentArray.push(componentInfo)}}}else{if(!l2file.isFile&&l2file.files.length>0){l2file.files.forEach(l3file=>{if(l3file.isFile&&l3file.name==="component.json"){componentInfo=this._Utils.extractComponentInfoFromJSONFile(path.join(rootDir,l1file.name,l2file.name),"component.json",isLocal,false);if(!componentInfo.pack){componentArray.push(componentInfo);if(componentInfo.type==="pack"){const packMembers=this._discoverComponentsFromRoot(this._Utils.toJAFPath(path.join(rootDir,l1file.name,l2file.name)),isLocal,false,componentInfo.name,precompileCache);componentArray=componentArray.concat(packMembers)}}}else if(l3file.isFile&&path.extname(l3file.name)===".tsx"&&precompileCache){componentInfo=this._tsxUtils.extractComponentInfoFromTSXFile(path.join(rootDir,l1file.name,l2file.name),l3file.name,isLocal,precompileCache);if(componentInfo){componentArray.push(componentInfo)}}})}}})}else{if(l1file.isFile&&l1file.name==="component.json"){componentInfo=this._Utils.extractComponentInfoFromJSONFile(rootDir,"component.json",isLocal,false);if(componentInfo.type!=="pack"||componentInfo.name!==parentPack){componentArray.push(componentInfo)}}else if(l1file.isFile&&path.extname(l1file.name)===".tsx"&&precompileCache){componentInfo=this._tsxUtils.extractComponentInfoFromTSXFile(rootDir,l1file.name,isLocal,precompileCache);if(componentInfo){componentArray.push(componentInfo)}}}});return componentArray};module.exports=ComponentFinder;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2024, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const JAF_TEMP="jaf";const WORKING_ROOT_FOLDER="ts-temp";const TSCONFIG_JSON="tsconfig.json";var path;const PreCompiler=function(utils,jafUtils,fsUtils,msgCtx,semVer,nd){this._utils=utils;this._jafUtils=jafUtils;this._fsUtils=fsUtils;this._semVer=semVer;this._error=msgCtx.error;this._info=msgCtx.info;this._msg=msgCtx.msg;this._debug=msgCtx.debug;this._jafMsg=msgCtx.jafMsg;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._isVerboseOrDebug=this._isVerbose||this._isDebug;path=nd.path;this._workingRootFolder=this._utils.toJAFPath(path.join(nd.os.tmpdir(),JAF_TEMP,WORKING_ROOT_FOLDER));this._runOnce=false;this._vfiles=null};PreCompiler.prototype.getPrecompileCache=function(auditBase,tsSource,componentRootFolder){if(!this.runOnce){this._runOnce=true;this._precompileCache=this._transformVComponents(path.join(auditBase,TSCONFIG_JSON),auditBase,tsSource,componentRootFolder)}return this._precompileCache};PreCompiler.prototype.getVFiles=function(){return this._vfiles};PreCompiler.prototype._transformVComponents=function(tsConfigPath,auditBase,sourceBase,componentBase){const normalizedTsConfigPath=this._fsUtils.toJAFPath(tsConfigPath);if(!this._fsUtils.fileExistsSync(normalizedTsConfigPath)){if(this._isVerboseOrDebug){this._info(`Typescript configuration file '${tsConfigPath}' not found, pre-compilation will be skipped`)}return}const outputFolder=this._fsUtils.getUniqueFileNameSync("_XXXXXX");const compiledOutputFolder=this._utils.toJAFPath(`${this._workingRootFolder}/js${outputFolder}`);const compiledJSONFolder=this._utils.toJAFPath(`${this._workingRootFolder}/json${outputFolder}`);const allTsConfig=this._fsUtils.readJsonSync(tsConfigPath,true,error=>this._error(`Typescript configuration file ${tsConfigPath} cannot be read, unable to process VComponents.\nError: ${error}`));if(!allTsConfig){return}if(this._isVerboseOrDebug){this._msg(`VComponent Processing: Compiling project...`)}allTsConfig.compilerOptions.paths[`${componentBase}/*`]=[`${auditBase}/${sourceBase}/${componentBase}/*`];const sourceBaseRoot=sourceBase.includes("/")?sourceBase.split("/")[0]:sourceBase;Object.entries(allTsConfig.compilerOptions.paths).forEach(([pathKey,pathValues])=>{const remapped=pathValues.map(mappedPath=>{return this._remapPath(mappedPath,sourceBaseRoot,auditBase)});allTsConfig.compilerOptions.paths[pathKey]=remapped});allTsConfig.compilerOptions.typeRoots=allTsConfig.compilerOptions.typeRoots.map(typeroot=>this._remapPath(typeroot,sourceBaseRoot,auditBase));if(allTsConfig.compilerOptions.hasOwnProperty("types")){allTsConfig.compilerOptions.types=allTsConfig.compilerOptions.types.map(type=>this._remapPath(type,sourceBaseRoot,auditBase))}allTsConfig.compilerOptions.rootDir=auditBase;allTsConfig.compilerOptions.outDir=compiledOutputFolder;if(!this._fsUtils.pathExistsSync(this._workingRootFolder)){this._fsUtils.createFolderSync(this._workingRootFolder)}else{this._fsUtils.deleteFolderSync(this._workingRootFolder,false)}if(this._isVerboseOrDebug){this._msg(`VComponent Processing: Typescript will be compiled into ${this._workingRootFolder}`)}let nodeJetRoot=path.join(auditBase,"node_modules","@oracle","oraclejet");if(!this._fsUtils.pathExistsSync(nodeJetRoot)){nodeJetRoot=path.normalize(path.join(auditBase,"..","..","node_modules","@oracle","oraclejet"))}let nodeJetPackage=path.join(nodeJetRoot,"package.json");let customTsc=this._utils.toJAFPath(path.join(nodeJetRoot,"dist","custom-tsc"));if(!this._fsUtils.pathExistsSync(customTsc)||!this._fsUtils.pathExistsSync(nodeJetPackage)){this._error("Unable to run VComponent pre-compilation -the required packages are not available. Run \"ojet restore\" or \"npm install\" to correct this.");return}let jetVerString;const packageJson=this._fsUtils.readJsonSync(nodeJetPackage);if(packageJson){jetVerString=packageJson.version}if(this._isVerboseOrDebug){this._msg(`VComponent Processing: oraclejet package version -> ${jetVerString?jetVerString:"not found"}`)}const CustomTypescriptCompiler=require(customTsc);const readFrom=path.join(auditBase,sourceBase);let files=this._discoverCompilableFiles(readFrom,readFrom);if(!files||!files.length){return}files.forEach((file,x)=>{files[x]=this._utils.toJAFPath(file)});if(this._isDebug){this._displayCompilableList(files)}const buildOptions={debug:false,dtDir:compiledJSONFolder,version:"",jetVersion:"",templatePath:path.join(customTsc,"templates"),tsBuiltDir:compiledOutputFolder,typesDir:compiledOutputFolder};const compileOptionsPre12={files,compilerOptions:allTsConfig.compilerOptions,buildOptions:buildOptions};const compileOptions1201={tsconfigJson:{compilerOptions:allTsConfig.compilerOptions,files},buildOptions:buildOptions};let compileOptions;if(jetVerString){if(this._semVer.gt(jetVerString,"12.0.0")){compileOptions=compileOptions1201}else{compileOptions=compileOptionsPre12}if(this._semVer.lt(jetVerString,"16.0.0")){compileOptions.mainEntryFile="loader.d.ts"}}if(compileOptions){try{if(this._isDebug){this._debug(`VComponents: compiling ${files.length} file${files.length>1?"s":""}...`)}const{errors}=CustomTypescriptCompiler.compile(compileOptions);if(errors.length){this._error(`${errors.length} Error${errors.length>1?"s":""} found during Typescript pre-compilation of VComponents`);errors.forEach(error=>{if(error.hasOwnProperty("message")){this._error(error.message);this._error(error.stack)}else{this._jafMsg("jaf-ts-precompile",JSON.stringify(error))}})}else{this._msg(`VComponent Processing: Typescript compilation of ${files.length} file${files.length!==1?"s":""} successful ...`)}if(!errors.length){this._vfiles=files}return compiledJSONFolder}catch(uncaughtFromCompile){this._error("Uncaught error during Typescript pre-compilation of VComponents");this._error(uncaughtFromCompile.stack)}}else{this._error("Unable to run VComponent pre-compilation, cannot detect JET custom compiler version")}};PreCompiler.prototype._discoverCompilableFiles=function(root,pathPrefix){const allSources=this._fsUtils.readDirSync(root);return allSources?this._extractCompilables(allSources,"").map(sourceFile=>`${pathPrefix}/${sourceFile}`):null};PreCompiler.prototype._extractCompilables=function(sources,folder){return sources.reduce((compilables,candidate)=>{if(candidate.isFile&&(candidate.name.endsWith(".ts")||candidate.name.endsWith(".tsx"))){compilables.push(`${folder}/${candidate.name}`)}else if(candidate.files){compilables=compilables.concat(this._extractCompilables(candidate.files,`${folder}/${candidate.name}`))}return compilables},new Array)};PreCompiler.prototype._remapPath=function(definedPath,sourceFolder,auditBase){let newPath=definedPath;const segs=definedPath.split("/");if(segs[0]==="."){segs.shift()}switch(segs[0]){case"node_modules":case"jet_components":case"exchange_components":case sourceFolder:newPath=`${auditBase}${segs.join("/")}`;break}return newPath};PreCompiler.prototype._displayCompilableList=function(files){let count=0;let flist;if(files&&files.length){count=files.length;flist="\n "+files.join("\n ")}this._debug(`VComponents: discovered ${count} compilable files:${flist}`)};module.exports=PreCompiler;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2024, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
var path;const TsxUtils=function(preCompUtils,jafUtils,fsUtils,msgCtx,nd){this._utils=preCompUtils;this._jafUtils=jafUtils;this._fsUtils=fsUtils;this._msgCtx=msgCtx;path=nd.path};TsxUtils.prototype.extractComponentInfoFromTSXFile=function(componentFolder,fileName,isLocal,precompileCache){const packRegEx=/@ojmetadata[\s]*pack[\s]*[\"|'](?<pack>[a-zA-Z\-0-9]*)[\"|']/mg;const versionRegEx=/@ojmetadata[\s]*version[\s]*[\"|'](?<version>[\.0-9\-a-zA-Z]*)[\"|']/mg;const jetVersionRegEx=/@ojmetadata[\s]*jetVersion[\s]*[\"|'](?<version>[\.0-9\-a-zA-Z^~><=]*)[\"|']/mg;let componentInfo={};const tsxFile=path.join(componentFolder,fileName);const fileAsStr=this._fsUtils.readFileSync(tsxFile);const componentIdentification=this._getVComponentElementNameAndImpl(fileAsStr);const fullName=componentIdentification.elementName;const className=componentIdentification.class;const componentName=this._getVComponentComponentName(fileAsStr);let fullNameMetadata=false;if(precompileCache){let mdSource=null;if(fullName){this._msgCtx.debug(`Processing tsx and metadata for ${fullName}`);mdSource=`${precompileCache}/${fullName}.json`;if(!this._fsUtils.fileExistsSync(mdSource)){mdSource=`${precompileCache}/${componentName}.json`;if(!componentName||!this._fsUtils.fileExistsSync(mdSource)){mdSource=null}}else{fullNameMetadata=true}}if(mdSource!==null){componentInfo=this._utils.extractComponentInfoFromJSONFile(precompileCache,`${fullNameMetadata?fullName:componentName}.json`,isLocal,true);componentInfo.rootFolder=this._utils.toJAFPath(componentFolder);componentInfo.compiledMetadata=mdSource;componentInfo.vcomponent=true;componentInfo.viewModel={resolved:true,path:this._utils.toJAFPath(tsxFile)};componentInfo.viewModel.className=className;if(!componentName){componentInfo.inferredName=true}if(componentInfo.pack){const matchPack=packRegEx.exec(fileAsStr);if(!matchPack||!matchPack.groups.pack){componentInfo.inferredPack=true}}const matchVer=versionRegEx.exec(fileAsStr);if(!matchVer||!matchVer.groups.version){componentInfo.inferredVersion=true}const matchJetVer=jetVersionRegEx.exec(fileAsStr);if(!matchJetVer||!matchJetVer.groups.version){componentInfo.inferredJetVersion=true}return componentInfo}else{return}}else{if(fullName){this._msgCtx.error(`Unable to audit VComponent ${fullName}, pre-compiled metadata is not available`)}return}};TsxUtils.prototype._getVComponentElementNameAndImpl=function(sourceCode){var resolvedElementName,implementationClass;const elementRegExForFunction=/export const\s*(?<className>\w+)[\w\s\<\>:]*=\s*registerCustomElement[\s<>\w]*\(\s*[\"\'](?<fullName>[\w-]*)\s*[\"\']\s*,/mg;const matchElementFunction=elementRegExForFunction.exec(sourceCode);if(matchElementFunction&&matchElementFunction.groups&&matchElementFunction.groups.fullName&&matchElementFunction.groups.className){resolvedElementName=matchElementFunction.groups.fullName;implementationClass=matchElementFunction.groups.className}else{const elementRegExForClass=/\s*@customElement\s*\(\s*[\"\']\s*(?<fullName>[\w-]*)\s*[\"\']\s*\)/mg;const matchElementClass=elementRegExForClass.exec(sourceCode);if(matchElementClass&&matchElementClass.groups&&matchElementClass.groups.fullName){resolvedElementName=matchElementClass.groups.fullName}const elementRegExForClassImpl=/[\s]*export[\s]*class[\s]*(?<className>[a-zA-Z\-0-9_]*)[\s]*extends[\s]*(?<superClass>[a-zA-Z\-0-9_]*)/mg;while((classDef=elementRegExForClassImpl.exec(sourceCode))!==null){if(classDef.groups.superClass==="Component"){implementationClass=classDef.groups.className}}}if(resolvedElementName&&!implementationClass){this._msgCtx.info(`WARNING: Unable to determine VComponent class-name for ${resolvedElementName}`)}return{elementName:resolvedElementName,class:implementationClass}};TsxUtils.prototype._getVComponentComponentName=function(sourceCode){const nameRegEx=/@ojmetadata[\s]*name [\"|'](?<componentName>[a-zA-Z\-0-9]*)[\"|']/mg;const matchElement=nameRegEx.exec(sourceCode);var ret;if(matchElement&&matchElement.groups&&matchElement.groups.componentName){ret=matchElement.groups.componentName}return ret};TsxUtils.prototype.matchToVComponentImpl=function(testFileName){let componentInfo;let fileNameCanonical=this._utils.toJAFPath(testFileName);if(fileNameCanonical.endsWith(".tsx")){const componentMatch=this._utils.matchComponentPath(fileNameCanonical);if(componentMatch){const testPossibleComponentInfo=this._utils.componentInfo(componentMatch);if(testPossibleComponentInfo.viewModel&&fileNameCanonical===testPossibleComponentInfo.viewModel.path){componentInfo=testPossibleComponentInfo}}}return componentInfo};module.exports=TsxUtils;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2018, 2024, Oracle and/or its affiliates.
|
|
3
|
+
* Licensed under The Universal Permissive License (UPL), Version 1.0
|
|
4
|
+
* as shown at https://oss.oracle.com/licenses/upl/
|
|
5
|
+
*/
|
|
6
|
+
const COMPONENT_FINDER=require("./ComponentFinder");const TSXUTILS_PRECOMP=require("./TsxUtils");const OJET_CONFIG="oraclejetconfig.json";const JET_COMPONENTS="jet_components";const JET_COMPOSITES="jet-composites";var path;function Utils(ojetCfg,jafUtils,fsUtils,msgCtx,nd){this._ojetConfig=ojetCfg;this._jafUtils=jafUtils;this._fsUtils=fsUtils;this._msgCtx=msgCtx;this._nd=nd;path=nd.path};Utils.prototype.getKeyPathInfo=function(auditBase){const paths={componentRootFolder:null,exchangeCacheFolder:null,generalSourceRoot:"src",jsSource:null,tsSource:null,base:null};let jetConfig=this._ojetConfig;if(!jetConfig&&auditBase){const remoteConfig=path.join(auditBase,OJET_CONFIG);if(this._fsUtils.pathExistsSync(remoteConfig)){jetConfig=this._fsUtils.readJsonSync(remoteConfig)}}let jsDir="js";let tsDir="ts";paths.base=this.toJAFPath(path.resolve(auditBase));if(jetConfig){jsDir=jetConfig.paths.source.javascript||"js";tsDir=jetConfig.paths.source.typescript||"ts";paths.exchangeCacheFolder=jetConfig.paths.source.exchangeComponents||JET_COMPONENTS;paths.componentRootFolder=jetConfig.paths.source.components||JET_COMPOSITES;paths.generalSourceRoot=jetConfig.paths.source.common||"src"}paths.jsSource=this.toJAFPath(path.join(paths.generalSourceRoot,jsDir));paths.tsSource=this.toJAFPath(path.join(paths.generalSourceRoot,tsDir));return paths};Utils.prototype.getComponentFinder=function(){if(!this._compFinder){this._tsxUtils=new TSXUTILS_PRECOMP(this,this._jafUtils,this._fsUtils,this._msgCtx,this._nd);this._compFinder=new COMPONENT_FINDER(this._ojetConfig,this._jafUtils,this._fsUtils,this._tsxUtils,this._msgCtx,this._nd)}return this._compFinder};Utils.prototype.extractComponentInfoFromJSONFile=function(auditContext,componentFolder,fileName,isLocal,fromPrecompile){let componentInfo={};const mdFile=`${componentFolder}/${fileName}`;const compMetadata=auditContext.utils.fsUtils.readJsonSync(mdFile);if(!compMetadata){this._msgCtx.msg.error(`Invalid JSON in component metadata ${mdFile}, component ignored`);return}componentInfo.name=compMetadata.name;componentInfo.pack=compMetadata.pack;if(fromPrecompile&&compMetadata.pack){if(compMetadata.name.startsWith(`${compMetadata.pack}-`)){componentInfo.name=compMetadata.name.substring(compMetadata.pack.length+1)}}componentInfo.fullName=componentInfo.pack?`${componentInfo.pack}-${componentInfo.name}`:componentInfo.name;componentInfo.displayName=compMetadata.displayName;componentInfo.description=compMetadata.description;componentInfo.version=compMetadata.version;componentInfo.jetVersion=compMetadata.jetVersion;componentInfo.license=compMetadata.license;componentInfo.extension=compMetadata.extension;if(compMetadata.icon){componentInfo.icon=compMetadata.icon}componentInfo.type=compMetadata.type?compMetadata.type:"composite";componentInfo.subcomponentType=compMetadata.subcomponentType;componentInfo.local=isLocal;componentInfo.rootFolder=this.toJAFPath(componentFolder);componentInfo.requirePaths=new Set;switch(componentInfo.type){case"reference":if(compMetadata.extension&&compMetadata.extension.oracle&&compMetadata.extension.oracle.businessApprovals){componentInfo.ba=compMetadata.extension.oracle.businessApprovals}if(compMetadata.paths&&compMetadata.paths.name){componentInfo.requirePaths.add(compMetadata.paths.name)}else{const extractPathSegments=compMetadata.package.split("/");if(extractPathSegments.length>1){componentInfo.requirePaths.add(extractPathSegments[1])}else{componentInfo.requirePaths.add(extractPathSegments[0])}}break;case"composite":if(compMetadata.styleClasses){componentInfo.styleClasses=compMetadata.styleClasses}if(compMetadata.styleVariables){componentInfo.styleVariables=compMetadata.styleVariables}if(compMetadata.slots){componentInfo.slots=compMetadata.slots}if(compMetadata.properties){componentInfo.properties=compMetadata.properties}if(compMetadata.events){componentInfo.events=compMetadata.events}if(compMetadata.methods&&Object.keys(compMetadata.methods).length>0){componentInfo.methods=compMetadata.methods}componentInfo.viewModel={resolved:false};if(compMetadata&&compMetadata.extension&&compMetadata.extension.audit&&compMetadata.extension.audit.jetwc&&compMetadata.extension.audit.jetwc.hasOwnProperty("viewModel")){const overrideVM=compMetadata.extension.audit.jetwc.viewModel;if(overrideVM){componentInfo.viewModel={path:this.toJAFPath(path.resolve(".",componentInfo.rootFolder,overrideVM)),resolved:true,skip:false}}else{componentInfo.viewModel={skip:true}}}case"resource":componentInfo.requirePaths.add(".");if(compMetadata.pack){componentInfo.requirePaths.add(`${componentInfo.pack}/${componentInfo.name}`)}else{componentInfo.requirePaths.add(componentInfo.name)}if(compMetadata.dependencies){componentInfo.dependencies=[];Object.keys(compMetadata.dependencies).forEach(depname=>{componentInfo.dependencies.push({name:depname,range:compMetadata.dependencies[depname]})})}break}return componentInfo};Utils.prototype.toJAFPath=function(sourcePath){if(sourcePath){sourcePath=path.normalize(sourcePath);if(this._jafUtils.isWindows()){sourcePath=sourcePath.replace(/\\/g,"/")}}return sourcePath};Utils.prototype.toNativePath=function(sourcePath){if(sourcePath){sourcePath=path.normalize(sourcePath)}return sourcePath};module.exports=Utils;
|