@oracle/oraclejet-audit 18.1.5 → 19.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.
Files changed (86) hide show
  1. package/corePackMigrator/corePackMigrator.js +1 -1
  2. package/corePackMigrator/metadata/badgeMetadata.json +66 -0
  3. package/corePackMigrator/metadata/checkboxsetMetadata.json +101 -0
  4. package/corePackMigrator/metadata/inputNumberMetadata.json +0 -3
  5. package/corePackMigrator/metadata/inputTextMetadata.json +0 -3
  6. package/corePackMigrator/metadata/labelMetadata.json +285 -222
  7. package/corePackMigrator/metadata/labelValueMetadata.json +226 -137
  8. package/corePackMigrator/metadata/listviewMetadata.json +7 -0
  9. package/corePackMigrator/metadata/radiosetMetadata.json +20 -9
  10. package/corePackMigrator/metadata/selectorMetadata.json +6 -0
  11. package/corePackMigrator/resource/astUtils.js +1 -1
  12. package/corePackMigrator/resource/componentMigrator.js +1 -1
  13. package/corePackMigrator/resource/fileScanner.js +1 -1
  14. package/corePackMigrator/resource/htmlUtils.js +1 -1
  15. package/corePackMigrator/resource/manifest.json +57 -49
  16. package/corePackMigrator/resource/migrationConfig.json +1 -1
  17. package/corePackMigrator/utilities/logging.js +2 -2
  18. package/jaf-amd.js +1 -1
  19. package/lib/Components.js +1 -1
  20. package/lib/Config.js +1 -1
  21. package/lib/FsUtils.js +1 -1
  22. package/lib/HtmlUtils.js +1 -1
  23. package/lib/JafLib.js +1 -1
  24. package/lib/MetaLib.js +1 -1
  25. package/lib/OjCPack.js +1 -1
  26. package/lib/RegTypes.js +1 -1
  27. package/lib/Registry.js +1 -1
  28. package/lib/Rules.js +1 -1
  29. package/lib/Ts.js +1 -1
  30. package/lib/TsUtils.js +1 -1
  31. package/lib/TsxUtils.js +1 -1
  32. package/lib/checkage.js +1 -1
  33. package/lib/defaults.js +1 -1
  34. package/lib/extends.js +1 -1
  35. package/lib/ns.js +1 -1
  36. package/lib/scaffold.js +1 -1
  37. package/lib/scopewalker.js +1 -1
  38. package/lib/sublib/precomp/Precompiler.js +1 -1
  39. package/libext/expparser.js +1 -1
  40. package/meta/18.0.0/jetauditmeta.js +1 -1
  41. package/meta/18.1.0/jetauditmeta.js +1 -1
  42. package/meta/19.0.0/jetauditmeta.js +9 -0
  43. package/meta/metaverlist.json +1 -1
  44. package/package.json +4 -4
  45. package/profiles/best-practice.json +3 -0
  46. package/profiles/redwood-strict.json +10 -1
  47. package/rulepacks/jetwc/jetwc-use-public-apis.js +6 -0
  48. package/rulepacks/jetwc/msgid.json +1 -1
  49. package/rulepacks/jetwc/rules.json +1 -1
  50. package/rulepacks/jetwc-lib/jetwcutils-componentAuditUtils.js +1 -1
  51. package/rulepacks/jetwc-lib/jetwcutils-componentFinder.js +1 -1
  52. package/rulepacks/jetwco/jetwco-cacc-properties.js +1 -1
  53. package/rulepacks/jetwco/rules.json +1 -1
  54. package/rules/jet/msgid.json +1 -1
  55. package/rules/jet/oj-acc-aria-accessible.js +1 -1
  56. package/rules/jet/oj-acc-aria-prop.js +1 -1
  57. package/rules/jet/oj-acc-navigable-link.js +6 -0
  58. package/rules/jet/oj-acc-select-aria-label.js +1 -1
  59. package/rules/jet/oj-cca-compjson-prop-conflict.js +6 -0
  60. package/rules/jet/oj-css-bp-zindex.js +7 -0
  61. package/rules/jet/oj-html-badge-maintenance.js +6 -0
  62. package/rules/jet/oj-html-binding-as-slot-child.js +1 -1
  63. package/rules/jet/oj-html-corequired.js +6 -0
  64. package/rules/jet/oj-html-nav-tab-nointeractive.js +6 -0
  65. package/rules/jet/oj-html-oj-ux-ico-slot.js +6 -0
  66. package/rules/jet/oj-html-ojtag-id.js +1 -1
  67. package/rules/jet/oj-html-redwood-ojoption-disabled.js +6 -0
  68. package/rules/jet/oj-html-slot-pref-content.js +1 -1
  69. package/rules/jet/oj-html-tabbar-progressive-popup.js +1 -1
  70. package/rules/jet/oj-html-wctag-for.js +1 -1
  71. package/rules/jet/oj-html-wctag-id.js +1 -1
  72. package/rules/jet/oj-html-wctag-maintenance.js +1 -1
  73. package/rules/jet/oj-html-wctag-packprivate.js +1 -1
  74. package/rules/jet/oj-js-poly-promise.js +1 -1
  75. package/rules/jet/oj-ts-poly-promise.js +1 -1
  76. package/rules/jet/oj-tsx-acc-navigable-link.js +6 -0
  77. package/rules/jet/oj-tsx-aria-prop.js +1 -1
  78. package/rules/jet/oj-tsx-corequired.js +6 -0
  79. package/rules/jet/oj-tsx-prop-ko-binding.js +6 -0
  80. package/rules/jet/oj-tsx-tabbar-progressive-popup.js +6 -0
  81. package/rules/jet/oj-tsx-wctag-packprivate.js +1 -1
  82. package/rules/jet/rules.json +1 -1
  83. package/schema/component-schema.json +1 -1
  84. package/src/JafCore.js +1 -1
  85. package/types/index.d.ts +5 -0
  86. package/corePackMigrator/metadata/messagesMetadata.json +0 -41
package/lib/extends.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 TSCONFIG="tsconfig.json";const PROFILE_DIR="profiles";const MERGEABLE_BY_DEFAULT={components:true,componentUrls:true,exclude:true,files:true,groups:true,message:true,nameSpaces:true,options:true,ruleMods:true,ruleNames:true,rulePacks:true,sevMap:true,typescript:true};const MERGEABLE_BY_OPTION={};const EXOPT_IGNORE="ignore";const EXOPT_MERGE="merge";const MSG={OBJ:"Config '%s' is not an object - %p",ARRAY:"Config '%s' is not an array - %p",STR:"Config '%s' is not a string - %p",STR_OR_AR_STR:"Config '%s' is not a string or an array of strings - %p",AR_OBJ:"Config '%s' is not an array of objects - %p",AR_STR:"Config '%s' is not an array of strings - %p",AR_STR_OBJ:"Config '%s' is not an array of strings or objects - %p",BOOL:"Config '%s' is not a boolean - %p",EXT_OPT:"Config 'extendOptions.%s' cannot be 'merge' - %p",EXT_OPT_VAL:"Config 'extendOptions.%s' not 'ignore' or 'merge' - %p",UNKNOWN:"Unknown config prop - '%s' - %p"};const REPL_PROP="%s";const REPL_PATH="%p";const DUMMY_FP="$_$";class Extends{constructor(configEx,configInst,cfg,path,nd,msgCtx,utils,fsUtils,isAMD){this._path=path;this._cfg=cfg;this._fp=cfg.base;this._nd=nd;this._msgCtx=msgCtx;this._utils=utils;this._fsUtils=fsUtils;this._cwd=nd.process.cwd();this._cfgEx=configEx;this._cfgInst=configInst;this._isAMD=isAMD;this._stack=[];this._extendOpts=null;this._profResult=null;this._error=msgCtx.error;this._info=msgCtx.info;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._mergeHandlers={components:this._mergePropComponents.bind(this),componentUrls:this._mergePropCompUrls.bind(this),exclude:this._mergePropExclude.bind(this),files:this._mergePropFiles.bind(this),groups:this._mergePropGroups.bind(this),messages:this._mergePropMessages,nameSpaces:this._mergePropNameSpaces.bind(this),options:this._mergePropOptions.bind(this),ruleMods:this._mergePropRuleMods.bind(this),ruleNames:this._mergePropRuleNames.bind(this),rulePacks:this._mergePropRulePacks,sevMap:this._mergePropSevMap.bind(this),typescript:this._mergePropTypescript.bind(this)}}extend(){if(!this._isDebug){this._isDebug=this._cfg.options&&this._cfg.options.debug}if(!this._isVerbose){this._isVerbose=this._cfg.options&&this._cfg.options.verbose}if(this._isDebug||this._isVerbose){this._msgCtx.info("[Info]: Merging configurations...","I",true)}if(!this._createStack()){return null}if(this._isDebug){this._dumpStack()}if(!this._isError){this._checkMergePropTypes();if(this._isError){return null}}if(!this._checkStackEnableDisableConflicts()||!this._checkUnsupportedProfileProps()||!this._checkProfileExtend()||!this._checkExtendOptionsProfile()||this._isError){return null}if(!this._stack.length){return this._cfg}return this._mergeStack()}_createStack(fp){var cfg,json,fp,first,stkEntry,profile;if(first=!fp){cfg=this._cfg;fp=this._isAMD?DUMMY_FP:this._path?this._path:this._fp}if(!fp){return true}if(this._utils.isObject(fp)){if(!(fp=this._resolveProfilePath(fp))){return false}if(fp.profile){profile=fp.profile}fp=fp.path}else if(!first&&typeof fp==="string"&&this._isAMD){this._error("Config cannot extend a non-profile config in AMD mode");return false}if(first){json=cfg}else if(this._isAMD){if(profile){if(json=this._nd.AmdProfLoader(profile)){json=this._parseJson(json)}if(!json){return false}}else{this._error("Config extends must contain a 'profile' propery in AMD mode");return false}fp=null}else{fp=this._getAbsolutePath(fp);if(!this._fsUtils.fileExists(fp)){let err=profile?`Configuration profile '${profile}' not found`:`Configuration file not found : ${fp}`;this._error(err);return false}if(this._isCircular(fp)){this._error(`Circular configuration 'extends' detected : ${fp}`);return false}try{if(!(json=this._readParseConfig(fp))){return false}}catch(e){this._error(`Error reading 'extends' config : ${fp}`);return false}}if(fp===DUMMY_FP){fp=null}stkEntry={path:fp,cfg:json};if(profile){stkEntry.profile=profile}this._stack.push(stkEntry);if(profile){if(!this._profResult){this._profResult={profiles:[profile]};if(json.ruleMods){if(json.ruleMods.enable){this._profResult.enable=json.ruleMods.enable}else{this._profResult.enable=[]}if(json.ruleMods.disable){this._profResult.disable=json.ruleMods.disable}else{this._profResult.disable=[]}}}else{this._profResult.profiles.push(profile)}}if(json.extends){if(!this._createStack(json.extends)){return false}}return true}_readParseConfig(fp){var json;json=this._nd.fs.readFileSync(fp,"utf8");json=this._nd.decomment(json);if(!(json=this._preprocessRawJson(json,fp))){return null}return this._parseJson(json,fp)}_parseJson(json,fp){var o;o=this._utils.parseJson(json,false);if(o.msg){let pos=`[${o.line}, ${o.col}]`;fp=fp?" : "+fp:"";this._error(`Config 'extends' error at ${pos} : ${o.msg}${fp}`);return null}return o.obj}_preprocessRawJson(txt,fp){var json=this._cfgInst.processIncludes(txt,fp);if(this._cfgInst.isOk()){json=this._cfgInst.processTokens(json);if(this._cfgInst.isOk()){}}return this._cfgInst.isOk()?json:null}_mergeStack(){if(!this._fixupPaths()){return null}for(let i=this._stack.length-1;i>0;i--){if(!this._mergePair(this._stack[i-1],this._stack[i])){return null}}if(this._isMergeProp("files")){if(this._stack[0].cfg.hasOwnProperty("files")){this._stack[0].cfg.files=_removeDupes(this._stack[0].cfg.files)}}if(this._isMergeProp("exclude")){if(this._stack[0].cfg.hasOwnProperty("exclude")){this._stack[0].cfg.exclude=_removeDupes(this._stack[0].cfg.exclude)}}if(this._stack[0].cfg.extends){delete this._stack[0].cfg.extends}return this._stack[0].cfg}_mergePair(parSE,chSE){var props,parent,child,merger,ret=true;parent=parSE.cfg;child=chSE.cfg;this._extendOpts=parSE.cfg.extendOptions||{};props=Object.keys(child);props.forEach(prop=>{if(prop.startsWith("_")||prop==="base"||prop==="extends"||prop==="tokens"||this._extendOpts[prop]===EXOPT_IGNORE){return}if(prop==="title"&&chSE.profile){return}if(!parent.hasOwnProperty(prop)){parent[prop]=child[prop];return}if(!this._isMergeProp(prop)){return}if(merger=this._mergeHandlers[prop]){if(!merger(parSE,chSE)){ret=false}}});if(!ret){return ret}if(!parSE.profile&&parSE.cfg.ruleNames){if(!this._checkRuleNamesProfileConflicts(parSE)){return false}}let type,what;if(chSE.profile){type="profile";what=chSE.profile}else{type="config";what=chSE.path}this._msgCtx.info(`[Info]: Inheriting ${type} '${what}'`,"I",true);return true}_checkMergePropTypes(){var cfg,se,prop,prop2,val;for(let i=0;i<this._stack.length;i++){se=this._stack[i];cfg=se.cfg;if(!this._cfgEx.checkPropNames(cfg,se.path)){this._isError=true}if(cfg.extendOptions){if(this._utils.isObject(cfg.extendOptions)){this._extendOpts=cfg.extendOptions;for(prop in this._extendOpts){val=this._extendOpts[prop];if(val===EXOPT_MERGE&&!MERGEABLE_BY_OPTION[prop]){this._emitErrorMsg(MSG.EXT_OPT,prop,se.path);return}else if(val!==EXOPT_MERGE&&val!==EXOPT_IGNORE){this._emitErrorMsg(MSG.EXT_OPT_VAL,prop,se.path);return}}}else{this._emitErrorMsg(MSG.OBJ,"extendOptions",se.path);return}}else{this._extendOpts={}}for(prop in cfg){if(!this._isMergeProp(prop)){continue}val=cfg[prop];if(prop==="components"||prop==="componentUrls"){if(typeof val!=="string"&&!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.STR_OR_AR_STR,prop,se.path)}}else if(prop==="files"){if(!Array.isArray(val)){this._emitErrorMsg(prop,prop,se.path)}if(!this._utils.isArrayContentsType(val,["string","object"])){this._emitErrorMsg(MSG.AR_STR_OBJ,prop,se.path)}}else if(prop==="exclude"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.STR_OR_AR_STR,prop,se.path)}}else if(prop==="groups"){if(!Array.isArray(val)){this._emitErrorMsg(MSG.STR,prop,se.path)}}else if(prop==="messages"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}if(se.messages.reject){if(!Array.isArray(se.messages.reject)){this._emitErrorMsg(MSG.OBJ,"messages.reject",se.path)}}if(se.messages.accept){if(!Array.isArray(se.messages.accept)){this._emitErrorMsg(MSG.OBJ,"messages.accept",se.path)}}}else if(prop==="nameSpaces"){if(!Array.isArray(val)){this._emitErrorMsg(MSG.AR_STR,prop,se.path)}}else if(prop==="options"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}}else if(prop==="ruleMods"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path);continue}for(prop2 in val){if(prop2==="enable"||prop2==="disable"){if(!Array.isArray(val[prop2])){this._emitErrorMsg(MSG.AR_OBJ,prop2==="enable"?"ruleMods.enable":"ruleMods.disable",se.path)}}else{if(!this._utils.isObject(val[prop2])){this._emitErrorMsg(MSG.AR_OBJ,prop+"."+prop2,se.path)}}}}else if(prop==="ruleNames"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.AR_STR,prop,se.path)}}else if(prop==="rulePacks"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"object")){this._emitErrorMsg(MSG.AR_OBJ,prop,se.path)}}else if(prop==="sevMap"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}if(val.sevMsg&&!this._utils.isObject(val.sevMsg)){this._emitErrorMsg(MSG.OBJ,prop+".sevMsg",se.path)}if(val.sevSet&&!this._utils.isObject(val.sevSet)){this._emitErrorMsg(MSG.OBJ,prop+".sevSet",se.path)}}else if(prop==="tokens"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}}else if(prop==="typescript"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}for(prop2 in val){if(prop2==="tsconfig"&&typeof val[prop2]!=="string"){this._emitErrorMsg(MSG.STR,"typescript.tsconfig",se.path)}if(prop2==="compile"&&typeof val[prop2]!=="boolean"){this._emitErrorMsg(MSG.BOOL,"typescript.compile",se.path)}}}else{this._error(`JAF ERROR: unhandled 'extends' property '${prop}' - ${se.path}`);this._isError=true}}}}_checkStackEnableDisableConflicts(){var config,i,b=true;for(i=this._stack.length-1;i>=0;i--){config=this._stack[i];if(!this._cfgEx.processRuleMods(config.cfg,config.profile?`profile '${config.profile}'`:config.path)){b=false}}if(!b){this._isError=true}return b}_checkRuleNamesProfileConflicts(parSE){var enable,rules,rule,i,profiles,isSet,b=true;if(!(this._profResult&&this._profResult.enable)){return true}rules=parSE.cfg.ruleNames;enable=this._profResult.enable;isSet=this._profResult.profiles.length>1;profiles=(isSet?"set [":"'")+this._profResult.profiles.join(", ")+(isSet?"]":"'");for(i=0;i<enable.length;i++){rule=enable[i];if(!rules.includes(rule)){this._msgCtx.error(`Config 'ruleNames' cannot disable rule '${rule}' enabled in profile ${profiles} - ${parSE.path}`);b=false}}if(!b){this._isError=true}return b}_checkUnsupportedProfileProps(){var se,config,i,b=true;var _self=this;function _emitUnsupProfileError(prof,prop){_self._msgCtx.error(`Property '${prop}' is not supported in profile ('${prof}')`);_self._isError=true;b=false}for(i=this._stack.length-1;i>=0;i--){se=this._stack[i];if(se.profile){config=se.cfg;if(config.ruleNames){_emitUnsupProfileError(se.profile,"ruleNames")}if(config.groups){_emitUnsupProfileError(se.profile,"groups")}}}return b}_checkProfileExtend(){var i;var stk=this._stack;for(i=0;i<stk.length;i++){if(!stk[i].profile){continue}for(i=i+1;i<stk.length;i++){if(!stk[i].profile){this._msgCtx.error(`Profile '${stk[i-1].profile}' cannot extend from a non-profile config - ${stk[i].path}`);return false}}break}return true}_checkExtendOptionsProfile(){if(this._profResult){let stk=this._stack;let opts;for(let i=0;i<stk.length;i++){if(opts=stk[i].cfg.extendOptions){if(opts.ruleMods==="ignore"){let isSet=this._profResult.profiles.length>1;let profiles=(isSet?"set [":"'")+this._profResult.profiles.join(", ")+(isSet?"]":"'");this._msgCtx.error(`Config cannot use 'extendsOptions.ruleMods' to ignore inherited 'ruleMods' from profile ${profiles} - ${stk[i].path}`);return false}}}}return true}_resolveProfilePath(o){var prof,ret;if(!(prof=o.profile)){this._error(`JAF ERROR: 'extends' declared as an object but property 'profile' is missing.`);this._isError=true;return null}ret={profile:o.profile};if(!this._isAMD){ret.path=this._nd.path.join(__dirname,"../"+PROFILE_DIR,prof)+".json"};return ret}_fixupPaths(){var se,ret=true;for(let i=this._stack.length-1;i>=0;i--){se=this._stack[i];if(!(this._cleanBase(se)&&this._fixupConfig(se))){ret=false;break}}return ret}_cleanBase(se){if(this._isAMD){return true}var src,ft;var nd=this._nd;src=se.cfg.base;if(src==="$jafcwd"){src=this._cwd}else{if(!src){src=this._nd.path.dirname(se.path)}src=nd.path.normalize(src);if(!nd.path.isAbsolute(src)){src=nd.path.join(nd.path.dirname(se.path),src)}ft=this._fsUtils.getFileType(src);if(ft!=="d"){this._msgCtx.error(`Config file 'base' is not a directory - '${src}' in ${se.path}`);return false}}se.cfg.base=src;this._info(`[Info]: Using config base '${src}' in ${se.path}`,"I");return true}_fixupConfig(se){var nd,cfg,src,dir,ft,i;nd=this._nd;cfg=se.cfg;if(cfg.files){if(!this._cfgEx.validateFileList(cfg.files)){this._bErrors=true;return}if(src=se.cfg.files){for(i=0;i<src.length;i++){if(!src[i].startsWith("http")){src[i]=nd.path.normalize(src[i]);src[i]=nd.path.resolve(cfg.base,src[i])}}}}if(cfg.exclude){if(!this._cfgEx.validateFileList(cfg.exclude)){this._bErrors=true;return}if(src=cfg.exclude){for(i=0;i<src.length;i++){src[i]=nd.path.normalize(src[i]);src[i]=nd.path.resolve(cfg.base,src[i])}}}src=cfg.components;if(src){for(i=0;i<src.length;i++){dir=nd.path.normalize(src[i]);dir=nd.path.resolve(cfg.base,dir);cfg.components[i]=dir}}src=cfg.outPath;if(src&&src!=="$noout"){src=nd.path.normalize(src);src=nd.path.resolve(cfg.base,src);cfg.outPath=src}src=cfg.rulePacks;if(src){for(i=0;i<src.length;i++){dir=src[i].path;dir=nd.path.normalize(dir);src[i].path=nd.path.resolve(cfg.base,dir);if(src[i].path.endsWith(".zip")){continue}ft=this._fsUtils.getFileType(src[i].path);if(ft!=="d"){this._error("'rulePacks (entry "+(i+1)+"): path' is not a directory - \""+src[i].path+"\"");this._bErrors=true}}}if(cfg.typescript&&cfg.typescript.tsconfig){src=cfg.typescript.tsconfig;if(src&&typeof src==="string"){if(!nd.path.isAbsolute(src)){dir=nd.path.normalize(src);dir=nd.path.resolve(cfg.base,dir)}else{dir=src}if(!dir.endsWith(TSCONFIG)){dir=nd.path.join(dir,TSCONFIG)}cfg.typescript.tsconfig=dir}}if(this._bErrors){this._error(`Errors found in inherited config '${se.path}'`)}return!this._bErrors}_getAbsolutePath(fp){if(this._nd.path.isAbsolute(fp)){return fp}let prevFp,prevBase,p;prevFp=this._stack[this._stack.length-1].path;prevFp=this._nd.path.dirname(prevFp);prevBase=this._stack[this._stack.length-1].cfg.base;if(prevBase){if(!this._nd.path.isAbsolute(prevBase)){p=this._nd.path.join(prevFp,prevBase,fp)}else{p=this._nd.path.join(prevBase,fp)}}else{p=this._nd.path.join(prevFp,fp)}if(!this._nd.path.isAbsolute(p)){p=this._nd.path.join(this._dir,p)}return p}_isCircular(fp){var ret;for(let i=0;i<this._stack.length;i++){if(this._stack[i].path===fp){ret=true;break}}return ret}_isMergeProp(p){return MERGEABLE_BY_DEFAULT[p]||this._extendOpts[p]===EXOPT_MERGE}_mergePropFiles(parSE,chSE){return this._mergePropFilesExclude(parSE,chSE,"files")}_mergePropExclude(parSE,chSE){return this._mergePropFilesExclude(parSE,chSE,"exclude")}_mergePropFilesExclude(parSE,chSE,prop){var parent,child,ch,i;var parent=parSE.cfg[prop];var child=chSE.cfg[prop];for(i=0;i<child.length;i++){ch=child[i];if(!parent.includes(ch)){parent.push(ch)}}return true}_mergePropOptions(parSE,chSE){return this._mergeObjects(parSE,chSE,"options")}_mergePropGroups(parSE,chSE){return this._mergeArrays(parSE,chSE,"groups")}_mergePropTokens(parSE,chSE){return this._mergeObjects(parSE,chSE,"tokens")}_mergePropNameSpaces(parSE,chSE){return this._mergeArrays(parSE,chSE,"nameSpaces")}_mergePropRuleMods(parSE,chSE){var pname,pack,parPack,rule,rval;var parent=parSE.cfg.ruleMods;var child=chSE.cfg.ruleMods;if(!this._mergeRuleModsEnableDisable(parSE,chSE)){return false}for(pname in child){if(pname==="enable"||pname==="disable"){continue}pack=child[pname];if(!parent[pname]){parent[pname]=pack;continue}this._mergeRuleModsPackObjects(parent[pname],pack)}parPack=parent[pname];for(rule in rval){if(!parPack[rule]){parPack[rule]=rval[rule]}}return true}_mergeRuleModsEnableDisable(parSE,chSE){var parent,child,val,x;var parEnable,parDisable,chEnable,chDisable;var parent=parSE.cfg.ruleMods;var child=chSE.cfg.ruleMods;parEnable=parent.enable;parDisable=parent.disable;chEnable=child.enable;chDisable=child.disable;var self=this;function _profVetoEnable(val){var ret=false;if(self._profResult&&self._profResult.disable){ret=self._profResult.disable.includes(val)}return ret}function _profVetoDisable(val){var ret=false;if(self._profResult&&self._profResult.enable){ret=self._profResult.enable.includes(val)}return ret}if(parEnable&&chDisable){for(val of parEnable){if(!(parSE.profile&&chSE.profile)){if(_profVetoEnable(val)){this._emitProfileVetoError(val,parSE.path,false);return false}}if((x=chDisable.indexOf(val))>=0){chDisable.splice(x,1)}}}if(parDisable&&chEnable){for(val of parDisable){if(!(parSE.profile&&chSE.profile)){if(_profVetoDisable(val)){this._emitProfileVetoError(val,parSE.path,true);return false}}if((x=chEnable.indexOf(val))>=0){chEnable.splice(x,1)}}}if(chEnable){if(!parEnable){parent.enable=parEnable=[]}for(val of chEnable){if(!parEnable.includes(val)){parEnable.push(val)}}}if(chDisable){if(!parDisable){parent.disable=parDisable=[]}for(val of chDisable){if(!parDisable.includes(val)){parDisable.push(val)}}}if(parSE.profile&&chSE.profile){if(!this._profResult){this._profResult={}}this._profResult.enable=parEnable;this._profResult.disable=parDisable;if(this._isDebug){console.log(`Profile merge: ${parSE.profile} <- ${chSE.profile}`)}}else{if(this._isDebug){console.log(`Merge: '${parSE.path}' <- '${chSE.profile?chSE.profile:chSE.path}'`)}}if(this._isDebug){console.log(`${parSE.path} <- ${chSE.path}`);console.log(`Enable = ${parEnable.join(",\n ")}`);console.log(`Disable = ${parDisable.join(",\n ")}\n`)}return true}_emitProfileVetoError(rule,cfgPath,disable){var profiles,temp,op1,op2;temp=[...this._profResult.profiles];temp.forEach((rule,i)=>{temp[i]="'"+rule+"'"});temp=temp.join(", ");if(disable){op1="disable";op2="enabled"}else{op1="enable";op2="disabled"}profiles="profile"+`${this._profResult.profiles.length>1?" set [":""} ${temp}${this._profResult.profiles.length>1?"]":""}`;cfgPath=cfgPath?`in ${cfgPath} `:"";this._error(`Config 'ruleMods' conflict: cannot ${op1} rule '${rule}' ${cfgPath}- ${op2} by ${profiles}`)}_mergePropRuleNames(parSE,chSE){return this._mergeArrays(parSE,chSE,"ruleNames")}_mergePropRulePacks(parSE,chSE){var parent=parSE.cfg.rulePacks;var child=chSE.cfg.rulePacks;for(let i=0;i<child.length;i++){let ch=child[i];let b=false;for(let j=0;j<parent.length;j++){let par=parent[j];if(ch.path===par.path){b=true;break}}if(!b){parent.push(ch)}}return true}_mergePropMessages(parSE,chSE){var parent=parSE.cfg.messages;var child=chSE.cfg.messages;var parReject=parent.reject;var chReject=child.reject;if(!parReject&&chReject){parent.reject=chReject}else if(parReject&&chReject){parent.reject=_removeDupes(parReject.concat(chReject))}var parAccept=parent.accept;var chAccept=child.accept;if(!parAccept&&chAccept){parent.accept=chAccept}else if(parAccept&&chAccept){parent.accept=_removeDupes(parAccept.concat(chAccept))}return true}_mergePropComponents(parSE,chSE){return this._mergeArrays(parSE,chSE,"components")}_mergePropCompUrls(parSE,chSE){return this._mergeArrays(parSE,chSE,"componentUrls")}_mergePropTypescript(parSE,chSE){return this._mergeObjects(parSE,chSE,"typescript")}_mergePropSevMap(parSE,chSE){var parent=parSE.cfg.sevMap;var child=chSE.cfg.sevMap;var parSevMsg,chSevMsg;var parSevSet,chSevSet;if(parent){parSevMsg=parent.sevMsg;parSevSet=parent.sevSet}if(child){chSevMsg=child.sevMsg;chSevSet=child.sevSet}if(parSevMsg&&chSevMsg){let prop;for(prop in chSevMsg){if(!parSevMsg[prop]){parSevMsg[prop]=chSevMsg[prop]}}}else if(!parSevMsg&&chSevMsg){parent.sevMsg=chSevMsg}if(parSevSet&&chSevSet){let prop;for(prop in chSevSet){if(!parSevSet[prop]){parSevSet[prop]=chSevSet[prop]}}}else if(!parSevSet&&chSevSet){parent.sevSet=chSevSet}if(parent.sevSet&&parent.sevMsg){let sev,msg,oldsev,val;for(val in parent.sevSet){sev=parent.sevSet[val];for(msg in parent.sevMsg){oldsev=parent.sevMsg[msg];if(val===oldsev){parent.sevMsg[msg]=sev}}}}return true}_mergeObjects(parSE,chSE,prop){var parent,child;parent=parSE.cfg[prop];child=chSE.cfg[prop];for(let prop in child){if(!parent.hasOwnProperty(prop)){parent[prop]=child[prop]}}return true}_mergeRuleModsPackObjects(to,from){var rule;for(rule in from){if(!to[rule]){to[rule]=from[rule]}}}_mergeArrays(parSE,chSE,prop){var parent,child,isPS,isCS,isPA,isCA,val;parent=parSE.cfg[prop];child=chSE.cfg[prop];isPS=typeof parent==="string";isCS=typeof child==="string";if(isPS&&isCS&&parent===child){return}isPA=Array.isArray(parent);isCA=Array.isArray(child);parent=isPA?parent:[parent];child=isCA?child:[child];for(let i=0;i<child.length;i++){val=child[i];if(!parent.includes(val)){parent.push(val)}}return true}_emitErrorMsg(s,prop,path){var s=s||MSG.UNKNOWN;if(prop){s=s.replace(REPL_PROP,prop)}this._error(s.replace(REPL_PATH,path));this._isError=true}_parseError(msg){this._parseError=msg}_dumpStack(){var type,msg;this._msgCtx.info("[Info]: -- Config 'extends' stack --","I",true);for(let i=0;i<this._stack.length;i++){type=this._stack[i].profile;type=type?type:"config ";msg=!this._isAMD?`${type} ${this._stack[i].path}`:`${type}`;this._msgCtx.info(`[Info]: ${msg}`,"I",true)}}}function _removeDupes(ar){return Array.isArray(ar)?ar.filter((val,x)=>ar.indexOf(val)===x):ar};module.exports=Extends;
6
+ const TSCONFIG="tsconfig.json";const PROFILE_DIR="profiles";const MERGEABLE_BY_DEFAULT={components:true,componentUrls:true,exclude:true,files:true,groups:true,message:true,nameSpaces:true,options:true,ruleMods:true,ruleNames:true,rulePacks:true,sevMap:true,typescript:true};const MERGEABLE_BY_OPTION={};const EXOPT_IGNORE="ignore";const EXOPT_MERGE="merge";const MSG={OBJ:"Config '%s' is not an object - %p",ARRAY:"Config '%s' is not an array - %p",STR:"Config '%s' is not a string - %p",STR_OR_AR_STR:"Config '%s' is not a string or an array of strings - %p",AR_OBJ:"Config '%s' is not an array of objects - %p",AR_STR:"Config '%s' is not an array of strings - %p",AR_STR_OBJ:"Config '%s' is not an array of strings or objects - %p",BOOL:"Config '%s' is not a boolean - %p",EXT_OPT:"Config 'extendOptions.%s' cannot be 'merge' - %p",EXT_OPT_VAL:"Config 'extendOptions.%s' not 'ignore' or 'merge' - %p",UNKNOWN:"Unknown config prop - '%s' - %p"};const REPL_PROP="%s";const REPL_PATH="%p";const DUMMY_FP="$_$";class Extends{constructor(configEx,configInst,cfg,path,nd,msgCtx,utils,fsUtils,isAMD){this._path=path;this._cfg=cfg;this._fp=cfg.base;this._nd=nd;this._msgCtx=msgCtx;this._utils=utils;this._fsUtils=fsUtils;this._cwd=nd.process.cwd();this._cfgEx=configEx;this._cfgInst=configInst;this._isAMD=isAMD;this._stack=[];this._extendOpts=null;this._profResult=null;this._error=msgCtx.error;this._info=msgCtx.info;this._isDebug=msgCtx.isDebug;this._isVerbose=msgCtx.isVerbose;this._isWindows=msgCtx.isWindows;this._mergeHandlers={components:this._mergePropComponents.bind(this),componentUrls:this._mergePropCompUrls.bind(this),exclude:this._mergePropExclude.bind(this),files:this._mergePropFiles.bind(this),groups:this._mergePropGroups.bind(this),messages:this._mergePropMessages,nameSpaces:this._mergePropNameSpaces.bind(this),options:this._mergePropOptions.bind(this),ruleMods:this._mergePropRuleMods.bind(this),ruleNames:this._mergePropRuleNames.bind(this),rulePacks:this._mergePropRulePacks,sevMap:this._mergePropSevMap.bind(this),typescript:this._mergePropTypescript.bind(this)}}extend(){if(!this._isDebug){this._isDebug=this._cfg.options&&this._cfg.options.debug}if(!this._isVerbose){this._isVerbose=this._cfg.options&&this._cfg.options.verbose}if(this._isDebug||this._isVerbose){this._msgCtx.info("[Info]: Merging configurations...","I",true)}if(!this._createStack()){return null}if(this._isDebug){this._dumpStack()}if(!this._isError){this._checkMergePropTypes();if(this._isError){return null}}if(!this._checkStackEnableDisableConflicts()||!this._checkUnsupportedProfileProps()||!this._checkProfileExtend()||!this._checkExtendOptionsProfile()||this._isError){return null}if(!this._stack.length){return this._cfg}return this._mergeStack()}_createStack(fp){var cfg,json,fp,first,stkEntry,profile;if(first=!fp){cfg=this._cfg;fp=this._isAMD?DUMMY_FP:this._path?this._path:this._fp}if(!fp){return true}if(this._utils.isObject(fp)){if(!(fp=this._resolveProfilePath(fp))){return false}if(fp.profile){profile=fp.profile}fp=fp.path}else if(!first&&typeof fp==="string"&&this._isAMD){this._error("Config cannot extend a non-profile config in AMD mode");return false}if(first){json=cfg}else if(this._isAMD){if(profile){if(json=this._nd.AmdProfLoader(profile)){json=this._parseJson(json)}if(!json){return false}}else{this._error("Config extends must contain a 'profile' propery in AMD mode");return false}fp=null}else{fp=this._getAbsolutePath(fp);if(!this._fsUtils.fileExists(fp)){let err=profile?`Configuration profile '${profile}' not found`:`Configuration file not found : ${fp}`;this._error(err);return false}if(this._isCircular(fp)){this._error(`Circular configuration 'extends' detected : ${fp}`);return false}try{if(!(json=this._readParseConfig(fp))){return false}}catch(e){this._error(`Error reading 'extends' config : ${fp}`);return false}}if(fp===DUMMY_FP){fp=null}stkEntry={path:fp,cfg:json};if(profile){stkEntry.profile=profile}this._stack.push(stkEntry);if(profile){if(!this._profResult){this._profResult={profiles:[profile]};if(json.ruleMods){if(json.ruleMods.enable){this._profResult.enable=json.ruleMods.enable}else{this._profResult.enable=[]}if(json.ruleMods.disable){this._profResult.disable=json.ruleMods.disable}else{this._profResult.disable=[]}}}else{this._profResult.profiles.push(profile)}}if(json.extends){if(!this._createStack(json.extends)){return false}}return true}_readParseConfig(fp){var json;json=this._nd.fs.readFileSync(fp,"utf8");json=this._nd.decomment(json);if(!(json=this._preprocessRawJson(json,fp))){return null}return this._parseJson(json,fp)}_parseJson(json,fp){var o;o=this._utils.parseJson(json,false);if(o.msg){let pos=`[${o.line}, ${o.col}]`;fp=fp?" : "+fp:"";this._error(`Config 'extends' error at ${pos} : ${o.msg}${fp}`);return null}return o.obj}_preprocessRawJson(txt,fp){var json=this._cfgInst.processIncludes(txt,fp);if(this._cfgInst.isOk()){json=this._cfgInst.processTokens(json);if(this._cfgInst.isOk()){}}return this._cfgInst.isOk()?json:null}_mergeStack(){if(!this._fixupPaths()){return null}for(let i=this._stack.length-1;i>0;i--){if(!this._mergePair(this._stack[i-1],this._stack[i])){return null}}if(this._isMergeProp("files")){if(this._stack[0].cfg.hasOwnProperty("files")){this._stack[0].cfg.files=_removeDupes(this._stack[0].cfg.files)}}if(this._isMergeProp("exclude")){if(this._stack[0].cfg.hasOwnProperty("exclude")){this._stack[0].cfg.exclude=_removeDupes(this._stack[0].cfg.exclude)}}if(this._stack[0].cfg.extends){delete this._stack[0].cfg.extends}return this._stack[0].cfg}_mergePair(parSE,chSE){var props,parent,child,merger,ret=true;parent=parSE.cfg;child=chSE.cfg;this._extendOpts=parSE.cfg.extendOptions||{};props=Object.keys(child);props.forEach(prop=>{if(prop.startsWith("_")||prop==="base"||prop==="extends"||prop==="tokens"||this._extendOpts[prop]===EXOPT_IGNORE){return}if(prop==="title"&&chSE.profile){return}if(!parent.hasOwnProperty(prop)){parent[prop]=child[prop];return}if(!this._isMergeProp(prop)){return}if(merger=this._mergeHandlers[prop]){if(!merger(parSE,chSE)){ret=false}}});if(!ret){return ret}if(!parSE.profile&&parSE.cfg.ruleNames){if(!this._checkRuleNamesProfileConflicts(parSE)){return false}}let type,what;if(chSE.profile){type="profile";what=chSE.profile}else{type="config";what=chSE.path}this._msgCtx.info(`[Info]: Inheriting ${type} '${what}'`,"I",true);return true}_checkMergePropTypes(){var cfg,se,prop,prop2,val;for(let i=0;i<this._stack.length;i++){se=this._stack[i];cfg=se.cfg;if(!this._cfgEx.checkPropNames(cfg,se.path)){this._isError=true}if(cfg.extendOptions){if(this._utils.isObject(cfg.extendOptions)){this._extendOpts=cfg.extendOptions;for(prop in this._extendOpts){val=this._extendOpts[prop];if(val===EXOPT_MERGE&&!MERGEABLE_BY_OPTION[prop]){this._emitErrorMsg(MSG.EXT_OPT,prop,se.path);return}else if(val!==EXOPT_MERGE&&val!==EXOPT_IGNORE){this._emitErrorMsg(MSG.EXT_OPT_VAL,prop,se.path);return}}}else{this._emitErrorMsg(MSG.OBJ,"extendOptions",se.path);return}}else{this._extendOpts={}}for(prop in cfg){if(!this._isMergeProp(prop)){continue}val=cfg[prop];if(prop==="components"||prop==="componentUrls"){if(typeof val!=="string"&&!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.STR_OR_AR_STR,prop,se.path)}}else if(prop==="files"){if(!Array.isArray(val)){this._emitErrorMsg(prop,prop,se.path)}if(!this._utils.isArrayContentsType(val,["string","object"])){this._emitErrorMsg(MSG.AR_STR_OBJ,prop,se.path)}}else if(prop==="exclude"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.STR_OR_AR_STR,prop,se.path)}}else if(prop==="groups"){if(!Array.isArray(val)){this._emitErrorMsg(MSG.STR,prop,se.path)}}else if(prop==="messages"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}if(se.messages.reject){if(!Array.isArray(se.messages.reject)){this._emitErrorMsg(MSG.OBJ,"messages.reject",se.path)}}if(se.messages.accept){if(!Array.isArray(se.messages.accept)){this._emitErrorMsg(MSG.OBJ,"messages.accept",se.path)}}}else if(prop==="nameSpaces"){if(!Array.isArray(val)){this._emitErrorMsg(MSG.AR_STR,prop,se.path)}}else if(prop==="options"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}}else if(prop==="ruleMods"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path);continue}for(prop2 in val){if(prop2==="enable"||prop2==="disable"){if(!Array.isArray(val[prop2])){this._emitErrorMsg(MSG.AR_OBJ,prop2==="enable"?"ruleMods.enable":"ruleMods.disable",se.path)}}else{if(!this._utils.isObject(val[prop2])){this._emitErrorMsg(MSG.AR_OBJ,prop+"."+prop2,se.path)}}}}else if(prop==="ruleNames"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"string")){this._emitErrorMsg(MSG.AR_STR,prop,se.path)}}else if(prop==="rulePacks"){if(!Array.isArray(val)||!this._utils.isArrayContentsType(val,"object")){this._emitErrorMsg(MSG.AR_OBJ,prop,se.path)}}else if(prop==="sevMap"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}if(val.sevMsg&&!this._utils.isObject(val.sevMsg)){this._emitErrorMsg(MSG.OBJ,prop+".sevMsg",se.path)}if(val.sevSet&&!this._utils.isObject(val.sevSet)){this._emitErrorMsg(MSG.OBJ,prop+".sevSet",se.path)}}else if(prop==="tokens"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}}else if(prop==="typescript"){if(!this._utils.isObject(val)){this._emitErrorMsg(MSG.OBJ,prop,se.path)}for(prop2 in val){if(prop2==="tsconfig"&&typeof val[prop2]!=="string"){this._emitErrorMsg(MSG.STR,"typescript.tsconfig",se.path)}if(prop2==="compile"&&typeof val[prop2]!=="boolean"){this._emitErrorMsg(MSG.BOOL,"typescript.compile",se.path)}}}else{this._error(`JAF ERROR: unhandled 'extends' property '${prop}' - ${se.path}`);this._isError=true}}}}_checkStackEnableDisableConflicts(){var config,i,b=true;for(i=this._stack.length-1;i>=0;i--){config=this._stack[i];if(!this._cfgEx.processRuleMods(config.cfg,config.profile?`profile '${config.profile}'`:config.path)){b=false}}if(!b){this._isError=true}return b}_checkRuleNamesProfileConflicts(parSE){var enable,rules,rule,i,profiles,isSet,b=true;if(!(this._profResult&&this._profResult.enable)){return true}rules=parSE.cfg.ruleNames;enable=this._profResult.enable;isSet=this._profResult.profiles.length>1;profiles=(isSet?"set [":"'")+this._profResult.profiles.join(", ")+(isSet?"]":"'");for(i=0;i<enable.length;i++){rule=enable[i];if(!rules.includes(rule)){this._msgCtx.error(`Config 'ruleNames' cannot disable rule '${rule}' enabled in profile ${profiles} - ${parSE.path}`);b=false}}if(!b){this._isError=true}return b}_checkUnsupportedProfileProps(){var se,config,i,b=true;var _self=this;function _emitUnsupProfileError(prof,prop){_self._msgCtx.error(`Property '${prop}' is not supported in profile ('${prof}')`);_self._isError=true;b=false}for(i=this._stack.length-1;i>=0;i--){se=this._stack[i];if(se.profile){config=se.cfg;if(config.ruleNames){_emitUnsupProfileError(se.profile,"ruleNames")}if(config.groups){_emitUnsupProfileError(se.profile,"groups")}}}return b}_checkProfileExtend(){var i;var stk=this._stack;for(i=0;i<stk.length;i++){if(!stk[i].profile){continue}for(i=i+1;i<stk.length;i++){if(!stk[i].profile){this._msgCtx.error(`Profile '${stk[i-1].profile}' cannot extend from a non-profile config - ${stk[i].path}`);return false}}break}return true}_checkExtendOptionsProfile(){if(this._profResult){let stk=this._stack;let opts;for(let i=0;i<stk.length;i++){if(opts=stk[i].cfg.extendOptions){if(opts.ruleMods==="ignore"){let isSet=this._profResult.profiles.length>1;let profiles=(isSet?"set [":"'")+this._profResult.profiles.join(", ")+(isSet?"]":"'");this._msgCtx.error(`Config cannot use 'extendsOptions.ruleMods' to ignore inherited 'ruleMods' from profile ${profiles} - ${stk[i].path}`);return false}}}}return true}_resolveProfilePath(o){var prof,ret;if(!(prof=o.profile)){this._error(`JAF ERROR: 'extends' declared as an object but property 'profile' is missing.`);this._isError=true;return null}ret={profile:o.profile};if(!this._isAMD){ret.path=this._nd.path.join(__dirname,"../"+PROFILE_DIR,prof)+".json"};return ret}_fixupPaths(){var se,ret=true;for(let i=this._stack.length-1;i>=0;i--){se=this._stack[i];if(!(this._cleanBase(se)&&this._fixupConfig(se))){ret=false;break}}return ret}_cleanBase(se){if(this._isAMD){return true}var src,ft;var nd=this._nd;src=se.cfg.base;if(src==="$jafcwd"){src=this._cwd}else{if(!src){src=this._nd.path.dirname(se.path)}src=nd.path.normalize(src);if(!nd.path.isAbsolute(src)){src=nd.path.join(nd.path.dirname(se.path),src)}ft=this._fsUtils.getFileType(src);if(ft!=="d"){this._msgCtx.error(`Config file 'base' is not a directory - '${src}' in ${se.path}`);return false}}se.cfg.base=src;this._info(`[Info]: Using config base '${src}' in ${se.path}`,"I");return true}_fixupConfig(se){var nd,cfg,src,dir,ft,i;nd=this._nd;cfg=se.cfg;if(cfg.files){if(!this._cfgEx.validateFileList(cfg.files)){this._bErrors=true;return}if(src=cfg.files){for(i=0;i<src.length;i++){if(!src[i].startsWith("http")){src[i]=nd.path.normalize(src[i]);src[i]=nd.path.resolve(cfg.base,src[i]);if(this._isWindows){src[i]=src[i].replace(/\\/g,"/")}}}}}if(cfg.exclude){if(!this._cfgEx.validateFileList(cfg.exclude)){this._bErrors=true;return}if(src=cfg.exclude){for(i=0;i<src.length;i++){src[i]=nd.path.normalize(src[i]);src[i]=nd.path.resolve(cfg.base,src[i]);if(this._isWindows){src[i]=src[i].replace(/\\/g,"/")}}}}src=cfg.components;if(src){for(i=0;i<src.length;i++){dir=nd.path.normalize(src[i]);dir=nd.path.resolve(cfg.base,dir);cfg.components[i]=dir}}src=cfg.outPath;if(src&&src!=="$noout"){src=nd.path.normalize(src);src=nd.path.resolve(cfg.base,src);cfg.outPath=src}src=cfg.rulePacks;if(src){for(i=0;i<src.length;i++){dir=src[i].path;dir=nd.path.normalize(dir);src[i].path=nd.path.resolve(cfg.base,dir);if(src[i].path.endsWith(".zip")){continue}ft=this._fsUtils.getFileType(src[i].path);if(ft!=="d"){this._error("'rulePacks (entry "+(i+1)+"): path' is not a directory - \""+src[i].path+"\"");this._bErrors=true}}}if(cfg.typescript&&cfg.typescript.tsconfig){src=cfg.typescript.tsconfig;if(src&&typeof src==="string"){if(!nd.path.isAbsolute(src)){dir=nd.path.normalize(src);dir=nd.path.resolve(cfg.base,dir)}else{dir=src}if(!dir.endsWith(TSCONFIG)){dir=nd.path.join(dir,TSCONFIG)}cfg.typescript.tsconfig=dir}}if(this._bErrors){this._error(`Errors found in inherited config '${se.path}'`)}return!this._bErrors}_getAbsolutePath(fp){if(this._nd.path.isAbsolute(fp)){return fp}let prevFp,prevBase,p;prevFp=this._stack[this._stack.length-1].path;prevFp=this._nd.path.dirname(prevFp);prevBase=this._stack[this._stack.length-1].cfg.base;if(prevBase){if(!this._nd.path.isAbsolute(prevBase)){p=this._nd.path.join(prevFp,prevBase,fp)}else{p=this._nd.path.join(prevBase,fp)}}else{p=this._nd.path.join(prevFp,fp)}if(!this._nd.path.isAbsolute(p)){p=this._nd.path.join(this._dir,p)}return p}_isCircular(fp){var ret;for(let i=0;i<this._stack.length;i++){if(this._stack[i].path===fp){ret=true;break}}return ret}_isMergeProp(p){return MERGEABLE_BY_DEFAULT[p]||this._extendOpts[p]===EXOPT_MERGE}_mergePropFiles(parSE,chSE){return this._mergePropFilesExclude(parSE,chSE,"files")}_mergePropExclude(parSE,chSE){return this._mergePropFilesExclude(parSE,chSE,"exclude")}_mergePropFilesExclude(parSE,chSE,prop){var parent,child,ch,i;var parent=parSE.cfg[prop];var child=chSE.cfg[prop];for(i=0;i<child.length;i++){ch=child[i];if(!parent.includes(ch)){parent.push(ch)}}return true}_mergePropOptions(parSE,chSE){return this._mergeObjects(parSE,chSE,"options")}_mergePropGroups(parSE,chSE){return this._mergeArrays(parSE,chSE,"groups")}_mergePropTokens(parSE,chSE){return this._mergeObjects(parSE,chSE,"tokens")}_mergePropNameSpaces(parSE,chSE){return this._mergeArrays(parSE,chSE,"nameSpaces")}_mergePropRuleMods(parSE,chSE){var pname,pack,parPack,rule,rval;var parent=parSE.cfg.ruleMods;var child=chSE.cfg.ruleMods;if(!this._mergeRuleModsEnableDisable(parSE,chSE)){return false}for(pname in child){if(pname==="enable"||pname==="disable"){continue}pack=child[pname];if(!parent[pname]){parent[pname]=pack;continue}this._mergeRuleModsPackObjects(parent[pname],pack)}parPack=parent[pname];for(rule in rval){if(!parPack[rule]){parPack[rule]=rval[rule]}}return true}_mergeRuleModsEnableDisable(parSE,chSE){var parent,child,val,x;var parEnable,parDisable,chEnable,chDisable;var parent=parSE.cfg.ruleMods;var child=chSE.cfg.ruleMods;parEnable=parent.enable;parDisable=parent.disable;chEnable=child.enable;chDisable=child.disable;var self=this;function _profVetoEnable(val){var ret=false;if(self._profResult&&self._profResult.disable){ret=self._profResult.disable.includes(val)}return ret}function _profVetoDisable(val){var ret=false;if(self._profResult&&self._profResult.enable){ret=self._profResult.enable.includes(val)}return ret}if(parEnable&&chDisable){for(val of parEnable){if(!(parSE.profile&&chSE.profile)){if(_profVetoEnable(val)){this._emitProfileVetoError(val,parSE.path,false);return false}}if((x=chDisable.indexOf(val))>=0){chDisable.splice(x,1)}}}if(parDisable&&chEnable){for(val of parDisable){if(!(parSE.profile&&chSE.profile)){if(_profVetoDisable(val)){this._emitProfileVetoError(val,parSE.path,true);return false}}if((x=chEnable.indexOf(val))>=0){chEnable.splice(x,1)}}}if(chEnable){if(!parEnable){parent.enable=parEnable=[]}for(val of chEnable){if(!parEnable.includes(val)){parEnable.push(val)}}}if(chDisable){if(!parDisable){parent.disable=parDisable=[]}for(val of chDisable){if(!parDisable.includes(val)){parDisable.push(val)}}}if(parSE.profile&&chSE.profile){if(!this._profResult){this._profResult={}}this._profResult.enable=parEnable;this._profResult.disable=parDisable;if(this._isDebug){console.log(`Profile merge: ${parSE.profile} <- ${chSE.profile}`)}}else{if(this._isDebug){console.log(`Merge: '${parSE.path}' <- '${chSE.profile?chSE.profile:chSE.path}'`)}}if(this._isDebug){console.log(`${parSE.path} <- ${chSE.path}`);console.log(`Enable = ${parEnable.join(",\n ")}`);console.log(`Disable = ${parDisable.join(",\n ")}\n`)}return true}_emitProfileVetoError(rule,cfgPath,disable){var profiles,temp,op1,op2;temp=[...this._profResult.profiles];temp.forEach((rule,i)=>{temp[i]="'"+rule+"'"});temp=temp.join(", ");if(disable){op1="disable";op2="enabled"}else{op1="enable";op2="disabled"}profiles="profile"+`${this._profResult.profiles.length>1?" set [":""} ${temp}${this._profResult.profiles.length>1?"]":""}`;cfgPath=cfgPath?`in ${cfgPath} `:"";this._error(`Config 'ruleMods' conflict: cannot ${op1} rule '${rule}' ${cfgPath}- ${op2} by ${profiles}`)}_mergePropRuleNames(parSE,chSE){return this._mergeArrays(parSE,chSE,"ruleNames")}_mergePropRulePacks(parSE,chSE){var parent=parSE.cfg.rulePacks;var child=chSE.cfg.rulePacks;for(let i=0;i<child.length;i++){let ch=child[i];let b=false;for(let j=0;j<parent.length;j++){let par=parent[j];if(ch.path===par.path){b=true;break}}if(!b){parent.push(ch)}}return true}_mergePropMessages(parSE,chSE){var parent=parSE.cfg.messages;var child=chSE.cfg.messages;var parReject=parent.reject;var chReject=child.reject;if(!parReject&&chReject){parent.reject=chReject}else if(parReject&&chReject){parent.reject=_removeDupes(parReject.concat(chReject))}var parAccept=parent.accept;var chAccept=child.accept;if(!parAccept&&chAccept){parent.accept=chAccept}else if(parAccept&&chAccept){parent.accept=_removeDupes(parAccept.concat(chAccept))}return true}_mergePropComponents(parSE,chSE){return this._mergeArrays(parSE,chSE,"components")}_mergePropCompUrls(parSE,chSE){return this._mergeArrays(parSE,chSE,"componentUrls")}_mergePropTypescript(parSE,chSE){return this._mergeObjects(parSE,chSE,"typescript")}_mergePropSevMap(parSE,chSE){var parent=parSE.cfg.sevMap;var child=chSE.cfg.sevMap;var parSevMsg,chSevMsg;var parSevSet,chSevSet;if(parent){parSevMsg=parent.sevMsg;parSevSet=parent.sevSet}if(child){chSevMsg=child.sevMsg;chSevSet=child.sevSet}if(parSevMsg&&chSevMsg){let prop;for(prop in chSevMsg){if(!parSevMsg[prop]){parSevMsg[prop]=chSevMsg[prop]}}}else if(!parSevMsg&&chSevMsg){parent.sevMsg=chSevMsg}if(parSevSet&&chSevSet){let prop;for(prop in chSevSet){if(!parSevSet[prop]){parSevSet[prop]=chSevSet[prop]}}}else if(!parSevSet&&chSevSet){parent.sevSet=chSevSet}if(parent.sevSet&&parent.sevMsg){let sev,msg,oldsev,val;for(val in parent.sevSet){sev=parent.sevSet[val];for(msg in parent.sevMsg){oldsev=parent.sevMsg[msg];if(val===oldsev){parent.sevMsg[msg]=sev}}}}return true}_mergeObjects(parSE,chSE,prop){var parent,child;parent=parSE.cfg[prop];child=chSE.cfg[prop];for(let prop in child){if(!parent.hasOwnProperty(prop)){parent[prop]=child[prop]}}return true}_mergeRuleModsPackObjects(to,from){var rule;for(rule in from){if(!to[rule]){to[rule]=from[rule]}}}_mergeArrays(parSE,chSE,prop){var parent,child,isPS,isCS,isPA,isCA,val;parent=parSE.cfg[prop];child=chSE.cfg[prop];isPS=typeof parent==="string";isCS=typeof child==="string";if(isPS&&isCS&&parent===child){return}isPA=Array.isArray(parent);isCA=Array.isArray(child);parent=isPA?parent:[parent];child=isCA?child:[child];for(let i=0;i<child.length;i++){val=child[i];if(!parent.includes(val)){parent.push(val)}}return true}_emitErrorMsg(s,prop,path){var s=s||MSG.UNKNOWN;if(prop){s=s.replace(REPL_PROP,prop)}this._error(s.replace(REPL_PATH,path));this._isError=true}_parseError(msg){this._parseError=msg}_dumpStack(){var type,msg;this._msgCtx.info("[Info]: -- Config 'extends' stack --","I",true);for(let i=0;i<this._stack.length;i++){type=this._stack[i].profile;type=type?type:"config ";msg=!this._isAMD?`${type} ${this._stack[i].path}`:`${type}`;this._msgCtx.info(`[Info]: ${msg}`,"I",true)}}}function _removeDupes(ar){return Array.isArray(ar)?ar.filter((val,x)=>ar.indexOf(val)===x):ar};module.exports=Extends;
package/lib/ns.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 _ns=["oj-acx","oj-acx-assets","oj-adp","oj-approvals","oj-av","oj-bangylon","oj-bi","oj-bi-sac","oj-cagbu","oj-cda","oj-cegbu","oj-cegbu-scp","oj-cgbu","oj-cgm","oj-cic","oj-clm","oj-communities","oj-core","oj-cp","oj-cso","oj-csp","oj-cx","oj-cx-aiapps","oj-cx-ap","oj-cx-cg","oj-cx-dcs","oj-cx-fsvc","oj-cx-hd","oj-cx-interviews","oj-cx-iss","oj-cx-km","oj-cx-km-agent","oj-cx-marketing","oj-cx-ma","oj-cx-mc","oj-cx-ol","oj-cx-saleshub","oj-cx-svc","oj-cxi","oj-cxm","oj-dbt","oj-dcs","oj-doceng","oj-dyn","oj-ee","oj-ehrc","oj-em","oj-epm","oj-fa","oj-faw","oj-fa-fin","oj-fnd","oj-fom","oj-fsgbu","oj-fsgbu-demo","oj-fwk","oj-gbu","oj-gbu-comp","oj-gcs","oj-gtm","oj-hcm","oj-hed","oj-hsgbu","oj-hsp","oj-hsp-common","oj-hsp-cruise","oj-hsp-hdp","oj-hsp-ohip","oj-hsp-opera","oj-ia","oj-i18n","oj-idaas","oj-ips","oj-ircs","oj-j4s","oj-jv","oj-lux","oj-lx","oj-mca","oj-mcps","oj-nav","oj-oa","oj-oac","oj-oal","oj-oal-ni","oj-oal-ux","oj-oax","oj-ob","oj-oc","oj-oce","oj-ocm","oj-oda","oj-oda-chat","oj-odcs","oj-odcs-oit","oj-odps","oj-ofsc","oj-ogg","oj-ohi","oj-oic","oj-oit","oj-ofs","oj-ol","oj-omc","oj-omnichannel","oj-opa","oj-opaas","oj-opac","oj-pa","oj-psc","oj-prmt","oj-psm","oj-ref","oj-rgbu","oj-rgbu-jraf","oj-rw","oj-scs","oj-sp","oj-spatial","oj-spectra","oj-svc","oj-taui","oj-ugbu","oj-uw","oj-ux","oj-vb","oj-vb-sample","oj-vbdt","oj-wc","oj-wcc","oj","oj-c","oj-cc","oj-dynamic","oj-ext","oj-sample","oj-sample-internal","ns","ns-ui","demo","my","app"];const _setNS=new Set(_ns);module.exports={has:function(k){return _setNS.has(k)},getKeys:function(){return[..._setNS]}};
6
+ const _ns=["oj-acx","oj-acx-assets","oj-adp","oj-approvals","oj-av","oj-bangylon","oj-bi","oj-bi-sac","oj-cagbu","oj-cda","oj-cegbu","oj-cegbu-scp","oj-cgbu","oj-cgm","oj-cic","oj-clm","oj-communities","oj-core","oj-cp","oj-cso","oj-csp","oj-cx","oj-cx-aiapps","oj-cx-ap","oj-cx-cg","oj-cx-dcs","oj-cx-fsvc","oj-cx-hd","oj-cx-interviews","oj-cx-iss","oj-cx-km","oj-cx-km-agent","oj-cx-marketing","oj-cx-ma","oj-cx-mc","oj-cx-ol","oj-cx-saleshub","oj-cx-svc","oj-cxi","oj-cxm","oj-dbt","oj-dcs","oj-doceng","oj-dyn","oj-ee","oj-ehrc","oj-em","oj-epm","oj-fa","oj-faw","oj-fa-fin","oj-fnd","oj-fom","oj-fsgbu","oj-fsgbu-demo","oj-fwk","oj-gbu","oj-gbu-comp","oj-gcs","oj-gtm","oj-hcm","oj-hed","oj-hsgbu","oj-hsp","oj-hsp-common","oj-hsp-cruise","oj-hsp-hdp","oj-hsp-ohip","oj-hsp-opera","oj-ia","oj-i18n","oj-idaas","oj-ips","oj-ircs","oj-j4s","oj-jv","oj-lux","oj-lx","oj-mca","oj-mcps","oj-nav","oj-oa","oj-oac","oj-oal","oj-oal-ni","oj-oal-ux","oj-oax","oj-ob","oj-oc","oj-oce","oj-ocm","oj-oda","oj-oda-chat","oj-odcs","oj-odcs-oit","oj-odps","oj-ofs","oj-ofsc","oj-ogg","oj-ohai","oj-ohi","oj-ohiui","oj-oic","oj-oit","oj-ol","oj-omc","oj-omnichannel","oj-opa","oj-opaas","oj-opac","oj-pa","oj-psc","oj-prmt","oj-psm","oj-ref","oj-rgbu","oj-rgbu-jraf","oj-rw","oj-scs","oj-sp","oj-spatial","oj-spectra","oj-svc","oj-taui","oj-ugbu","oj-uw","oj-ux","oj-vb","oj-vb-sample","oj-vbdt","oj-wc","oj-wcc","oj","oj-c","oj-cc","oj-dynamic","oj-ext","oj-sample","oj-sample-internal","ns","ns-ui","demo","my","app"];const _setNS=new Set(_ns);module.exports={has:function(k){return _setNS.has(k)},getKeys:function(){return[..._setNS]}};
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={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;
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.message)}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.message)}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;
@@ -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 CPW="Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com> Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>";(function clone(exports){"use strict";var Syntax,VisitorOption,VisitorKeys,BREAK,SKIP,REMOVE;function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}Syntax={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ChainExpression:"ChainExpression",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",PrivateIdentifier:"PrivateIdentifier",Program:"Program",Property:"Property",PropertyDefinition:"PropertyDefinition",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression",ClassProperty:"ClassProperty",TSAsExpression:"TSAsExpression",TSImportEqualsDeclaration:"TSImportEqualsDeclaration",TSTypeAliasDeclaration:"TSTypeAliasDeclaration",TSTypeAssertion:"TSTypeAssertion",TSInterfaceDeclaration:"TSInterfaceDeclaration",TSExportAssignment:"TSExportAssignment",TSAbstractMethodDefinition:"TSAbstractMethodDefinition",TSDeclareFunction:"TSDeclareFunction",TSModuleDeclaration:"TSModuleDeclaration",TSParameterProperty:"TSParameterProperty",TSNonNullExpression:"TSNonNullExpression",JSXElement:"JsxElement",JSXFragment:"JsxFragment",JSXOpeningElement:"JSXOpeningElement"};VisitorKeys={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ChainExpression:["expression"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateIdentifier:[],Program:["body"],Property:["key","value"],PropertyDefinition:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],Super:[],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"],ClassProperty:[],TSAsExpression:[],TSEnumDeclaration:[],TSImportEqualsDeclaration:[],TSTypeAliasDeclaration:[],TSInterfaceDeclaration:[],TSNonNullExpression:[],TSExportAssignment:[],TSTypeAssertion:[],TSAbstractMethodDefinition:[],TSDeclareFunction:[],TSModuleDeclaration:[],TSParameterProperty:[],JSXElement:[],JSXFragment:[],JSXOpeningElement:[]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(Array.isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(Array.isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=null;if(visitor.fallback==="iteration"){this.__fallback=Object.keys}else if(typeof visitor.fallback==="function"){this.__fallback=visitor.fallback}this.__keys=VisitorKeys;if(visitor.keys){this.__keys=Object.assign(Object.create(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}function candidateExistsInLeaveList(leavelist,candidate){for(var i=leavelist.length-1;i>=0;--i){if(leavelist[i].node===candidate){return true}}return false}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=node.type||element.wrap;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=this.__fallback(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(Array.isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(candidateExistsInLeaveList(leavelist,candidate[current2])){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){if(candidateExistsInLeaveList(leavelist,candidate)){continue}worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=node.type||element.wrap;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=this.__fallback(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(Array.isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller;exports.cloneEnvironment=function(){return clone({})};return exports})(exports);
6
+ const CPW="Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com> Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>";(function clone(exports){"use strict";var Syntax,VisitorOption,VisitorKeys,BREAK,SKIP,REMOVE;function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}Syntax={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ChainExpression:"ChainExpression",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",PrivateIdentifier:"PrivateIdentifier",Program:"Program",Property:"Property",PropertyDefinition:"PropertyDefinition",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression",ClassProperty:"ClassProperty",TSAsExpression:"TSAsExpression",TSImportEqualsDeclaration:"TSImportEqualsDeclaration",TSTypeAliasDeclaration:"TSTypeAliasDeclaration",TSTypeAssertion:"TSTypeAssertion",TSInterfaceDeclaration:"TSInterfaceDeclaration",TSExportAssignment:"TSExportAssignment",TSAbstractMethodDefinition:"TSAbstractMethodDefinition",TSDeclareFunction:"TSDeclareFunction",TSModuleDeclaration:"TSModuleDeclaration",TSParameterProperty:"TSParameterProperty",TSEmptyBodyFunctionExpression:"TSEmptyBodyFunctionExpression",TSNonNullExpression:"TSNonNullExpression",JSXElement:"JsxElement",JSXFragment:"JsxFragment",JSXOpeningElement:"JSXOpeningElement"};VisitorKeys={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ChainExpression:["expression"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateIdentifier:[],Program:["body"],Property:["key","value"],PropertyDefinition:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],Super:[],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"],ClassProperty:[],TSAsExpression:[],TSEmptyBodyFunctionExpression:[],TSEnumDeclaration:[],TSImportEqualsDeclaration:[],TSTypeAliasDeclaration:[],TSInterfaceDeclaration:[],TSNonNullExpression:[],TSExportAssignment:[],TSTypeAssertion:[],TSAbstractMethodDefinition:[],TSDeclareFunction:[],TSModuleDeclaration:[],TSParameterProperty:[],JSXElement:[],JSXFragment:[],JSXOpeningElement:[]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(Array.isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(Array.isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=null;if(visitor.fallback==="iteration"){this.__fallback=Object.keys}else if(typeof visitor.fallback==="function"){this.__fallback=visitor.fallback}this.__keys=VisitorKeys;if(visitor.keys){this.__keys=Object.assign(Object.create(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}function candidateExistsInLeaveList(leavelist,candidate){for(var i=leavelist.length-1;i>=0;--i){if(leavelist[i].node===candidate){return true}}return false}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=node.type||element.wrap;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=this.__fallback(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(Array.isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(candidateExistsInLeaveList(leavelist,candidate[current2])){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){if(candidateExistsInLeaveList(leavelist,candidate)){continue}worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=node.type||element.wrap;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=this.__fallback(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(Array.isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller;exports.cloneEnvironment=function(){return clone({})};return exports})(exports);
@@ -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 JAF_TEMP="jaf";const WORKING_ROOT_FOLDER="ts-temp";const TSCONFIG_JSON="tsconfig.json";const VCOMP_MSG_PREFIX="VComponent Processing:";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(`Skipping pre-compilation - Typescript configuration file '${tsConfigPath}' not found!`)}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._isDebug){this._debug(`TypeScript Config ->\n${JSON.stringify(allTsConfig,null,3)}`)}if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} Compiling project ...`)}if(this._isDebug){this._debug("...transforming to full paths")}allTsConfig.compilerOptions.paths[`${componentBase}/*`]=[`${auditBase}/${sourceBase}/${componentBase}/*`];const sourceBaseRoot=sourceBase.includes("/")?sourceBase.split("/")[0]:sourceBase;Object.entries(allTsConfig.compilerOptions.paths).forEach(([pathKey,pathValues])=>{if(this._isDebug){this._debug(`pathKey -> ${pathKey} pathValues -> ${pathValues}`)};const remapped=pathValues.map(mappedPath=>{return this._remapPath(mappedPath,sourceBaseRoot,auditBase)});allTsConfig.compilerOptions.paths[pathKey]=remapped});if(allTsConfig.compilerOptions.hasOwnProperty("typeRoots")){allTsConfig.compilerOptions.typeRoots=allTsConfig.compilerOptions.typeRoots.map(typeroot=>this._remapPath(typeroot,sourceBaseRoot,auditBase))}else if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} tsconfig 'typeRoots' property not defined ...`)}if(allTsConfig.compilerOptions.hasOwnProperty("types")){allTsConfig.compilerOptions.types=allTsConfig.compilerOptions.types.map(type=>this._remapPath(type,sourceBaseRoot,auditBase))}else if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} tsconfig 'types' property not defined ...`)}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(`${VCOMP_MSG_PREFIX} 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(`${VCOMP_MSG_PREFIX} oraclejet package version -> ${jetVerString?jetVerString:"not found"}`)}let CustomTypeScriptCompiler;if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} loading TypeScript compiler...`)}try{CustomTypeScriptCompiler=require(customTsc)}catch(e){this._jafMsg("jaf-ts-loader",`${VCOMP_MSG_PREFIX} failure loading TypeScript <- '${customTsc}'`)}if(!CustomTypeScriptCompiler){return}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){if(this._isDebug){this._debug(`Using TypeScript compile options ->\n${JSON.stringify(compileOptions,null,3)}\n`)}try{if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} 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(`${VCOMP_MSG_PREFIX} 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;
6
+ const JAF_TEMP="jaf";const WORKING_ROOT_FOLDER="ts-temp";const TSCONFIG_JSON="tsconfig.json";const VCOMP_MSG_PREFIX="VComponent Processing:";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;if(this._isDebug){this._debug(`getPrecompileCache ->\n auditBase=\"${auditBase}\"\n tsSource=\"${tsSource}\"\n componentRootFolder=\"${componentRootFolder}\"`)}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(`Skipping pre-compilation - Typescript configuration file '${tsConfigPath}' not found!`)}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._isDebug){this._debug(`\nTypeScript Config ->\n${JSON.stringify(allTsConfig,null,3)}`)}if(this._isVerboseOrDebug){this._msg(`\n${VCOMP_MSG_PREFIX} Compiling project ...`)}if(this._isDebug){this._debug(`...transforming to full paths ->\n componentBase=\"${componentBase}\"\n auditBase=\"${auditBase}\"\n sourceBase=\"${sourceBase}\"\n componentBase=\"${componentBase}\"\n`)}if(typeof componentBase!=="string"){this._error(`\nCan't set tsconfig.compiler.paths property with key '${componentBase}/*' - project pre-compilation abandoned.`);return}allTsConfig.compilerOptions.paths[`${componentBase}/*`]=[`${auditBase}/${sourceBase}/${componentBase}/*`];const sourceBaseRoot=sourceBase.includes("/")?sourceBase.split("/")[0]:sourceBase;Object.entries(allTsConfig.compilerOptions.paths).forEach(([pathKey,pathValues])=>{if(this._isDebug){this._debug(`pathKey -> ${pathKey} pathValues -> ${pathValues}`)};const remapped=pathValues.map(mappedPath=>{return this._remapPath(mappedPath,sourceBaseRoot,auditBase)});allTsConfig.compilerOptions.paths[pathKey]=remapped});if(allTsConfig.compilerOptions.hasOwnProperty("typeRoots")){allTsConfig.compilerOptions.typeRoots=allTsConfig.compilerOptions.typeRoots.map(typeroot=>this._remapPath(typeroot,sourceBaseRoot,auditBase))}else if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} tsconfig 'typeRoots' property not defined ...`)}if(allTsConfig.compilerOptions.hasOwnProperty("types")){allTsConfig.compilerOptions.types=allTsConfig.compilerOptions.types.map(type=>this._remapPath(type,sourceBaseRoot,auditBase))}else if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} tsconfig 'types' property not defined ...`)}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(`${VCOMP_MSG_PREFIX} 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(`${VCOMP_MSG_PREFIX} oraclejet package version -> ${jetVerString?jetVerString:"not found"}`)}let CustomTypeScriptCompiler;if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} loading TypeScript compiler...`)}try{CustomTypeScriptCompiler=require(customTsc)}catch(e){this._jafMsg("jaf-ts-loader",`${VCOMP_MSG_PREFIX} failure loading TypeScript <- '${customTsc}'`)}if(!CustomTypeScriptCompiler){return}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){if(this._isDebug){this._debug(`Using TypeScript compile options ->\n${JSON.stringify(compileOptions,null,3)}\n`)}try{if(this._isVerboseOrDebug){this._msg(`${VCOMP_MSG_PREFIX} 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(`${VCOMP_MSG_PREFIX} 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;
@@ -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 ExpParser=function(){this.parse=function(expr){var context={index:0,expr:expr};var nodes=_gobbleExpressions(context);if(nodes.length===1){return nodes[0]}return{type:COMPOUND,body:nodes}};function _gobbleExpressions(context,untilICode){const expr=context.expr;const length=expr.length;const nodes=[];while(context.index<length){_gobbleSpaces(context);const ch_i=expr.charCodeAt(context.index);if(ch_i===SEMCOL_CODE||ch_i===COMMA_CODE){context.index++}else{const node=_gobbleExpression(context);if(node){nodes.push(node)}else if(context.index<length){if(ch_i===untilICode){break}_throwError("Unexpected \""+expr.charAt(context.index)+"\"",context.index)}}}return nodes}function _gobbleSpaces(context){var expr=context.expr;var ch=expr.charCodeAt(context.index);while(ch===32||ch===9||ch===10||ch===13){ch=expr.charCodeAt(++context.index)}}function _gobbleExpression(context){const expr=context.expr;let test=_gobbleArrowFunctionExpression(context)||_gobbleBinaryExpression(context),consequent,alternate;_gobbleSpaces(context);if(expr.charCodeAt(context.index)===QUMARK_CODE){context.index++;consequent=_gobbleExpression(context);if(!consequent){_throwError("Expected expression",context.index)}_gobbleSpaces(context);if(expr.charCodeAt(context.index)===COLON_CODE){context.index++;alternate=_gobbleExpression(context);if(!alternate){_throwError("Expected expression",context.index)}test={type:CONDITIONAL_EXP,test:test,consequent:consequent,alternate:alternate}}else{_throwError("Expected :",context.index)}}_updateBinariesToArrows(test);return test}function _gobbleBinaryOp(context){var expr=context.expr;_gobbleSpaces(context);var to_check=expr.substr(context.index,_max_binop_len),tc_len=to_check.length;while(tc_len>0){if(_binary_ops[to_check]&&(!_isIdentifierStart(expr.charCodeAt(context.index))||context.index+to_check.length<expr.length&&!_isIdentifierPart(expr.charCodeAt(context.index+to_check.length)))){context.index+=tc_len;return to_check}to_check=to_check.substr(0,--tc_len)}return false}function _gobbleBinaryExpression(context){var node,biop,prec,stack,biop_info,left,right,i,cur_biop,cur_prec;left=_gobbleToken(context);biop=_gobbleBinaryOp(context);if(!biop){return left}biop_info={value:biop,prec:_binaryPrecedence(biop)};right=biop==="=>"?_gobbleArrowFunctionBody(context):_gobbleToken(context);if(!right){_throwError("Expected expression after "+biop,context.index)}stack=[left,biop_info,right];cur_biop=biop;cur_prec=biop_info.prec;while(biop=_gobbleBinaryOp(context)){prec=_binaryPrecedence(biop,cur_biop,cur_prec);if(prec===0){break}biop_info={value:biop,prec:prec};cur_biop=biop;cur_prec=prec;while(stack.length>2&&prec<=stack[stack.length-2].prec){right=stack.pop();biop=stack.pop().value;left=stack.pop();node=_createBinaryExpression(biop,left,right,context);stack.push(node)}node=_gobbleToken(context);if(!node){_throwError("Expected expression after "+cur_biop,context.index)}stack.push(biop_info,node)}i=stack.length-1;node=stack[i];while(i>1){node=_createBinaryExpression(stack[i-1].value,stack[i-2],node,context);i-=2}return node}function _gobbleToken(context){var expr=context.expr;var ch,to_check,tc_len;_gobbleSpaces(context);ch=expr.charCodeAt(context.index);if(_isDecimalDigit(ch)||ch===PERIOD_CODE){return _gobbleNumericLiteral(context)}else if(ch===SQUOTE_CODE||ch===DQUOTE_CODE||ch===OBRACK_CODE){return _gobbleVariable(context)}else if(ch===OBRACE_CODE){return _gobbleObjectLiteral(context)}else if(ch===BTICK_CODE){return _gobbleTemplateLiteral(context)}to_check=expr.substr(context.index,_max_unop_len);tc_len=to_check.length;while(tc_len>0){if(to_check in _unary_ops&&(!_isIdentifierStart(expr.charCodeAt(context.index))||context.index+to_check.length<expr.length&&!_isIdentifierPart(expr.charCodeAt(context.index+to_check.length)))){context.index+=tc_len;return{type:UNARY_EXP,operator:to_check,argument:_gobbleToken(context),prefix:true}}to_check=to_check.substr(0,--tc_len)}var start=context.index;var funcEnd=context.index+8;if(expr.substring(start,funcEnd)==="function"&&!_isIdentifierPart(expr.charCodeAt(funcEnd))){context.index=funcEnd;return _gobbleFunction(context)}if(_isIdentifierStart(ch)||ch===OPAREN_CODE){return _gobbleVariable(context)}return false}function _gobbleNumericLiteral(context){var expr=context.expr;var number="",ch,chCode;while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}if(expr.charCodeAt(context.index)===PERIOD_CODE){number+=expr.charAt(context.index++);while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}}ch=expr.charAt(context.index);if(ch==="e"||ch==="E"){number+=expr.charAt(context.index++);ch=expr.charAt(context.index);if(ch==="+"||ch==="-"){number+=expr.charAt(context.index++)}while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}if(!_isDecimalDigit(expr.charCodeAt(context.index-1))){_throwError("Expected exponent ("+number+expr.charAt(context.index)+")",context.index)}}chCode=expr.charCodeAt(context.index);if(_isIdentifierStart(chCode)){_throwError("Variable names cannot start with a number ("+number+expr.charAt(context.index)+")",context.index)}else if(chCode===PERIOD_CODE){_throwError("Unexpected period",context.index)}return{type:LITERAL,value:parseFloat(number),raw:number}}function _gobbleStringLiteral(context){var expr=context.expr;var str="",quote=expr.charAt(context.index++),closed=false,ch;var length=expr.length;while(context.index<length){ch=expr.charAt(context.index++);if(ch===quote){closed=true;break}else if(ch==="\\"){ch=expr.charAt(context.index++);switch(ch){case"n":str+="\n";break;case"r":str+="\r";break;case"t":str+="\t";break;case"b":str+="\b";break;case"f":str+="\f";break;case"v":str+="\x0B";break;default:str+=ch}}else{str+=ch}}if(!closed){_throwError("Unclosed quote after \""+str+"\"",context.index)}return{type:LITERAL,value:str,raw:quote+str+quote}}function _gobbleIdentifier(context,bMemberExpr){var expr=context.expr;var ch=expr.charCodeAt(context.index),start=context.index,identifier;if(_isIdentifierStart(ch)){context.index++}else{_throwError("Unexpected "+expr.charAt(context.index),context.index)}var length=expr.length;while(context.index<length){ch=expr.charCodeAt(context.index);if(_isIdentifierPart(ch)){context.index++}else{break}}identifier=expr.slice(start,context.index);if(identifier==="new"&&!bMemberExpr){_gobbleSpaces(context);var constructorNode=_gobbleVariable(context,CALL_EXP);if(constructorNode.type!==CALL_EXP){_throwError("Expression of type: "+constructorNode.type+" not supported for constructor expression")}return{type:NEW_EXP,callee:constructorNode.callee,arguments:constructorNode.arguments}}if(_literals.has(identifier)){return{type:LITERAL,value:_literals.get(identifier),raw:identifier}}return{type:IDENTIFIER,name:identifier}}function _gobbleArguments(context,termination,identifiersOnly){var expr=context.expr;var length=expr.length;var ch_i,args=[],node,closed=false;var separator_count=0;while(context.index<length){_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i===termination){closed=true;context.index++;if(termination===CPAREN_CODE&&separator_count&&separator_count>=args.length){_throwError("Unexpected token "+String.fromCharCode(termination),context.index)}break}else if(ch_i===COMMA_CODE){context.index++;separator_count++;if(separator_count!==args.length){if(termination===CPAREN_CODE){_throwError("Unexpected token ,",context.index)}else if(termination===CBRACK_CODE){for(var arg=args.length;arg<separator_count;arg++){args.push(null)}}}}else{if(identifiersOnly){node=_gobbleIdentifier(context)}else{node=_gobbleExpression(context)}if(!node||args.length>separator_count){_throwError("Expected comma",context.index)}args.push(node)}}if(!closed){_throwError("Expected "+String.fromCharCode(termination),context.index)}return args}function _gobbleVariable(context,stopAtType){var expr=context.expr;var ch_i,node;ch_i=expr.charCodeAt(context.index);if(ch_i===OPAREN_CODE){node=_gobbleGroup(context)}else if(ch_i===SQUOTE_CODE||ch_i===DQUOTE_CODE){node=_gobbleStringLiteral(context)}else if(ch_i===OBRACK_CODE){node=_gobbleArray(context)}else{node=_gobbleIdentifier(context)}_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);while(ch_i===PERIOD_CODE||ch_i===OBRACK_CODE||ch_i===OPAREN_CODE||_isOptionalChaining(context)){context.index++;if(ch_i===PERIOD_CODE){_gobbleSpaces(context);node={type:MEMBER_EXP,computed:false,object:node,property:_gobbleIdentifier(context,true)}}else if(ch_i===QUMARK_CODE){context.index++;_gobbleSpaces(context);node={type:MEMBER_EXP,computed:false,optional:true,object:node,property:_gobbleIdentifier(context,true)}}else if(ch_i===OBRACK_CODE){node={type:MEMBER_EXP,computed:true,object:node,property:_gobbleExpression(context)};_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACK_CODE){_throwError("Unclosed [",context.index)}context.index++}else if(ch_i===OPAREN_CODE){node={type:CALL_EXP,arguments:_gobbleArguments(context,CPAREN_CODE),callee:node}}if(stopAtType===node.type){return node}_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index)}return node}function _gobbleGroup(context){context.index++;let nodes=_gobbleExpressions(context,CPAREN_CODE);if(context.expr.charCodeAt(context.index)===CPAREN_CODE){context.index++;if(nodes.length===1){return nodes[0]}else if(!nodes.length){return false}return{type:SEQUENCE_EXP,expressions:nodes}}_throwError("Unclosed (",context.index)}function _gobbleArray(context){context.index++;return{type:ARRAY_EXP,elements:_gobbleArguments(context,CBRACK_CODE)}}function _gobbleFunctionBody(context){_gobbleSpaces(context);const expr=context.expr;let ch_i=expr.charCodeAt(context.index);context.index++;_gobbleSpaces(context);let hasReturn=false;const start=context.index;if(expr.substring(start,start+6)==="return"){hasReturn=true;context.index+=6}_gobbleSpaces(context);const funcBody=_gobbleExpression(context);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i===SEMCOL_CODE){context.index++;_gobbleSpaces(context)}ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACE_CODE){_throwError("Expected },",context.index)}context.index++;return{type:BLOCK_STATEMENT,expr:expr.substring(start,context.index-1),body:hasReturn?{type:RETURN_STATEMENT,argument:funcBody}:funcBody}}function _gobbleFunction(context){var expr=context.expr;_gobbleSpaces(context);var ch_i=expr.charCodeAt(context.index);if(ch_i!==OPAREN_CODE){_throwError("Expected (,",context.index)}context.index++;var args=_gobbleArguments(context,CPAREN_CODE,true);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i!==OBRACE_CODE){_throwError("Expected {,",context.index)}return{type:FUNCTION_EXP,params:args,body:_gobbleFunctionBody(context)}}function _gobbleObjectLiteral(context){var expr=context.expr;context.index++;var props=[];var closed;var separator_count=0;var length=expr.length;while(context.index<length&&!closed){_gobbleSpaces(context);var ch_i=expr.charCodeAt(context.index);if(ch_i===CBRACE_CODE){closed=true;context.index++}else if(ch_i===COMMA_CODE){context.index++;separator_count++;if(separator_count!==props.length){_throwError("Unexpected token ,",context.index)}}else{var key=ch_i===SQUOTE_CODE||ch_i===DQUOTE_CODE?_gobbleStringLiteral(context):_gobbleIdentifier(context);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(key.type===IDENTIFIER&&(ch_i===COMMA_CODE||ch_i===CBRACE_CODE)){props.push({type:PROPERTY,key:key,value:key,shorthand:true})}else if(ch_i===COLON_CODE){context.index++;var writer=context.writer;var keyValue=getKeyValue(key);if(keyValue==="_ko_property_writers"){context.writer=1}try{props.push({type:PROPERTY,key:key,value:_gobbleExpression(context),shorthand:false})}finally{context.writer=writer}}else{_throwError("Expected ':'. Found "+String.fromCharCode(ch_i),context.index)}}}if(!closed){_throwError("Expected "+String.fromCharCode(CBRACE_CODE),context.index)}return{type:OBJECT_EXP,properties:props}}function _gobbleTemplateLiteral(context){const expr=context.expr;let ch_i=expr.charCodeAt(context.index);if(ch_i===BTICK_CODE){const node={type:TEMPLATE_LITERAL,quasis:[],expressions:[]};let cooked="";let raw="";let closed=false;const length=expr.length;const pushQuasi=()=>node.quasis.push({type:TEMPLATE_ELEMENT,value:{raw,cooked},tail:closed});while(context.index<length){let ch=expr.charAt(++context.index);if(ch==="`"){context.index+=1;closed=true;pushQuasi();return node}else if(ch==="$"&&expr.charAt(context.index+1)==="{"){context.index+=2;pushQuasi();raw="";cooked="";try{node.expressions.push(..._gobbleExpressions(context,CBRACE_CODE))}finally{ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACE_CODE){_throwError("Unclosed ${ in template literal",expr)}}}else if(ch==="\\"){raw+=ch;ch=expr.charAt(++context.index);raw+=ch;switch(ch){case"n":cooked+="\n";break;case"r":cooked+="\r";break;case"t":cooked+="\t";break;case"b":cooked+="\b";break;case"f":cooked+="\f";break;case"v":cooked+="\x0B";break;default:cooked+=ch}}else{cooked+=ch;raw+=ch}}if(context.index===length){_throwError("Unclosed backtick ` in template literal",expr)}}return false}function _gobbleArrowFunctionExpression(context){const expr=context.expr;let ch=expr.charCodeAt(context.index);let node;if(ch===OPAREN_CODE){const backupIndex=context.index;context.index++;_gobbleSpaces(context);ch=expr.charCodeAt(context.index);if(ch===CPAREN_CODE){context.index++;const biop=_gobbleBinaryOp(context);if(biop==="=>"){const body=_gobbleArrowFunctionBody(context);if(!body){_throwError("Expected expression after "+biop)}node={type:ARROW_EXP,params:[],body}}}if(!node){context.index=backupIndex}}return node}function _gobbleArrowFunctionBody(context){const expr=context.expr;_gobbleSpaces(context);let returnNode;if(expr.charCodeAt(context.index)===OBRACE_CODE){returnNode=_gobbleFunctionBody(context)}else{const startDef=context.index;_gobbleSpaces(context);const funcBody=_gobbleExpression(context);_gobbleSpaces(context);context.index++;returnNode={type:BLOCK_STATEMENT,expr:expr.substring(startDef,context.index-1),body:{type:RETURN_STATEMENT,argument:funcBody}}}return returnNode}function _updateBinariesToArrows(node){if(node){Object.values(node).forEach(val=>{if(val&&typeof val==="object"){_updateBinariesToArrows(val)}});if(node.operator==="=>"){node.type=ARROW_EXP;node.params=node.left?[node.left]:null;node.body=node.right;if(node.params&&node.params[0].type===SEQUENCE_EXP){node.params=node.params[0].expressions}delete node.left;delete node.right;delete node.operator}}}var PERIOD_CODE=46,COMMA_CODE=44,SQUOTE_CODE=39,DQUOTE_CODE=34,OPAREN_CODE=40,CPAREN_CODE=41,OBRACK_CODE=91,CBRACK_CODE=93,QUMARK_CODE=63,SEMCOL_CODE=59,COLON_CODE=58,BTICK_CODE=96,OBRACE_CODE=123,CBRACE_CODE=125;function _getMaxKeyLen(obj){return Object.keys(obj).reduce(function(curr,key){return Math.max(curr,key.length)},0)}var t=true,_unary_ops={"-":t,"!":t,"~":t,"+":t,typeof:t},_binary_ops={"=":1,"||":2,"??":2,"&&":3,"|":4,"^":5,"&":6,"==":7,"!=":7,"===":7,"!==":7,"<":8,">":8,"<=":8,">=":8,instanceof:8,"<<":9,">>":9,">>>":9,"+":10,"-":10,"*":11,"/":11,"%":11,"**":12,"=>":0.1},_max_unop_len=_getMaxKeyLen(_unary_ops),_max_binop_len=_getMaxKeyLen(_binary_ops);var _literals=new Map;_literals.set("true",true);_literals.set("false",false);_literals.set("null",null);_literals.set("undefined",undefined);function _binaryPrecedence(op_val,prev_op_val,prev_op_prec){const basePrec=_binary_ops[op_val]||0;if(basePrec!==12||prev_op_val===undefined||op_val!==prev_op_val){return basePrec}return(prev_op_prec+13)*0.5}function _createBinaryExpression(operator,left,right,context){if(operator==="="&&!context.writer){_throwError("Unexpected operator '='",context.index)}var type=operator==="||"||operator==="&&"||operator==="??"?LOGICAL_EXP:BINARY_EXP;return{type:type,operator:operator,left:left,right:right}}function _isOptionalChaining(context){var expr=context.expr;if(expr.charCodeAt(context.index)===QUMARK_CODE&&expr.charCodeAt(context.index+1)===PERIOD_CODE&&!_isDecimalDigit(expr.charCodeAt(context.index+2))){return true}return false}function _isDecimalDigit(ch){return ch>=48&&ch<=57}function _isIdentifierStart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=128&&!_binary_ops[String.fromCharCode(ch)]}function _isIdentifierPart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch>=128&&!_binary_ops[String.fromCharCode(ch)]}function _throwError(message,index){var error=new Error(message+" at character "+index);error.index=index;error.description=message;throw error}};const getKeyValue=function(keyObj){return keyObj.type===IDENTIFIER?keyObj.name:keyObj.value};module.exports=ExpParser;const COMPOUND="Compound";const IDENTIFIER="Identifier";const MEMBER_EXP="MemberExpression";const LITERAL="Literal";const CALL_EXP="CallExpression";const UNARY_EXP="UnaryExpression";const BINARY_EXP="BinaryExpression";const LOGICAL_EXP="LogicalExpression";const CONDITIONAL_EXP="ConditionalExpression";const ARRAY_EXP="ArrayExpression";const OBJECT_EXP="ObjectExpression";const FUNCTION_EXP="FunctionExpression";const NEW_EXP="NewExpression";const PROPERTY="Property";const TEMPLATE_LITERAL="TemplateLiteral";const TEMPLATE_ELEMENT="TemplateElement";const SEQUENCE_EXP="SequenceExpression";const ARROW_EXP="ArrowFunctionExpression";const RETURN_STATEMENT="ReturnStatement";const BLOCK_STATEMENT="BlockStatement";
6
+ const ExpParser=function(){this.parse=function(expr){var context={index:0,expr:expr};var nodes=_gobbleExpressions(context);if(nodes.length===1){return nodes[0]}return{type:COMPOUND,body:nodes}};function _gobbleExpressions(context,untilICode){const expr=context.expr;const length=expr.length;const nodes=[];while(context.index<length){_gobbleSpaces(context);const ch_i=expr.charCodeAt(context.index);if(ch_i===SEMCOL_CODE||ch_i===COMMA_CODE){context.index++}else{const node=_gobbleExpression(context);if(node){nodes.push(node)}else if(context.index<length){if(ch_i===untilICode){break}_throwError("Unexpected \""+expr.charAt(context.index)+"\"",context.index)}}}return nodes}function _gobbleSpaces(context){var expr=context.expr;var ch=expr.charCodeAt(context.index);while(ch===32||ch===9||ch===10||ch===13){ch=expr.charCodeAt(++context.index)}}function _gobbleExpression(context){const expr=context.expr;let test=_gobbleArrowFunctionExpression(context)||_gobbleBinaryExpression(context),consequent,alternate;_gobbleSpaces(context);if(expr.charCodeAt(context.index)===QUMARK_CODE){context.index++;consequent=_gobbleExpression(context);if(!consequent){_throwError("Expected expression",context.index)}_gobbleSpaces(context);if(expr.charCodeAt(context.index)===COLON_CODE){context.index++;alternate=_gobbleExpression(context);if(!alternate){_throwError("Expected expression",context.index)}test={type:CONDITIONAL_EXP,test:test,consequent:consequent,alternate:alternate}}else{_throwError("Expected :",context.index)}}_updateBinariesToArrows(test);return test}function _gobbleBinaryOp(context){var expr=context.expr;_gobbleSpaces(context);var to_check=expr.substr(context.index,_max_binop_len),tc_len=to_check.length;while(tc_len>0){if(_binary_ops[to_check]&&(!_isIdentifierStart(expr.charCodeAt(context.index))||context.index+to_check.length<expr.length&&!_isIdentifierPart(expr.charCodeAt(context.index+to_check.length)))){context.index+=tc_len;return to_check}to_check=to_check.substr(0,--tc_len)}return false}function _gobbleBinaryExpression(context){var node,biop,prec,stack,biop_info,left,right,i,cur_biop,cur_prec;left=_gobbleToken(context);biop=_gobbleBinaryOp(context);if(!biop){return left}biop_info={value:biop,prec:_binaryPrecedence(biop)};right=biop==="=>"?_gobbleArrowFunctionBody(context):_gobbleToken(context);if(!right){_throwError("Expected expression after "+biop,context.index)}stack=[left,biop_info,right];cur_biop=biop;cur_prec=biop_info.prec;while(biop=_gobbleBinaryOp(context)){prec=_binaryPrecedence(biop,cur_biop,cur_prec);if(prec===0){break}biop_info={value:biop,prec:prec};cur_biop=biop;cur_prec=prec;while(stack.length>2&&prec<=stack[stack.length-2].prec){right=stack.pop();biop=stack.pop().value;left=stack.pop();node=_createBinaryExpression(biop,left,right,context);stack.push(node)}node=_gobbleToken(context);if(!node){_throwError("Expected expression after "+cur_biop,context.index)}stack.push(biop_info,node)}i=stack.length-1;node=stack[i];while(i>1){node=_createBinaryExpression(stack[i-1].value,stack[i-2],node,context);i-=2}return node}function _gobbleToken(context){var expr=context.expr;var ch,to_check,tc_len;_gobbleSpaces(context);ch=expr.charCodeAt(context.index);if(_isDecimalDigit(ch)||ch===PERIOD_CODE){return _gobbleNumericLiteral(context)}else if(ch===SQUOTE_CODE||ch===DQUOTE_CODE||ch===OBRACK_CODE){return _gobbleVariable(context)}else if(ch===OBRACE_CODE){return _gobbleObjectLiteral(context)}else if(ch===BTICK_CODE){return _gobbleTemplateLiteral(context)}to_check=expr.substr(context.index,_max_unop_len);tc_len=to_check.length;while(tc_len>0){if(to_check in _unary_ops&&(!_isIdentifierStart(expr.charCodeAt(context.index))||context.index+to_check.length<expr.length&&!_isIdentifierPart(expr.charCodeAt(context.index+to_check.length)))){context.index+=tc_len;return{type:UNARY_EXP,operator:to_check,argument:_gobbleToken(context),prefix:true}}to_check=to_check.substr(0,--tc_len)}var start=context.index;var funcEnd=context.index+8;if(expr.substring(start,funcEnd)==="function"&&!_isIdentifierPart(expr.charCodeAt(funcEnd))){context.index=funcEnd;return _gobbleFunction(context)}if(_isIdentifierStart(ch)||ch===OPAREN_CODE){return _gobbleVariable(context)}return false}function _gobbleNumericLiteral(context){var expr=context.expr;var number="",ch,chCode;while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}if(expr.charCodeAt(context.index)===PERIOD_CODE){number+=expr.charAt(context.index++);while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}}ch=expr.charAt(context.index);if(ch==="e"||ch==="E"){number+=expr.charAt(context.index++);ch=expr.charAt(context.index);if(ch==="+"||ch==="-"){number+=expr.charAt(context.index++)}while(_isDecimalDigit(expr.charCodeAt(context.index))){number+=expr.charAt(context.index++)}if(!_isDecimalDigit(expr.charCodeAt(context.index-1))){_throwError("Expected exponent ("+number+expr.charAt(context.index)+")",context.index)}}chCode=expr.charCodeAt(context.index);if(_isIdentifierStart(chCode)){_throwError("Variable names cannot start with a number ("+number+expr.charAt(context.index)+")",context.index)}else if(chCode===PERIOD_CODE){_throwError("Unexpected period",context.index)}return{type:LITERAL,value:parseFloat(number),raw:number}}function _gobbleStringLiteral(context){var expr=context.expr;var str="",quote=expr.charAt(context.index++),closed=false,ch;var length=expr.length;while(context.index<length){ch=expr.charAt(context.index++);if(ch===quote){closed=true;break}else if(ch==="\\"){ch=expr.charAt(context.index++);switch(ch){case"n":str+="\n";break;case"r":str+="\r";break;case"t":str+="\t";break;case"b":str+="\b";break;case"f":str+="\f";break;case"v":str+="\x0B";break;default:str+=ch}}else{str+=ch}}if(!closed){_throwError("Unclosed quote after \""+str+"\"",context.index)}return{type:LITERAL,value:str,raw:quote+str+quote}}function _gobbleIdentifier(context,bMemberExpr){var expr=context.expr;var ch=expr.charCodeAt(context.index),start=context.index,identifier;if(_isIdentifierStart(ch)){context.index++}else{_throwError("Unexpected "+expr.charAt(context.index),context.index)}var length=expr.length;while(context.index<length){ch=expr.charCodeAt(context.index);if(_isIdentifierPart(ch)){context.index++}else{break}}identifier=expr.slice(start,context.index);if(identifier==="new"&&!bMemberExpr){_gobbleSpaces(context);var constructorNode=_gobbleVariable(context,CALL_EXP);if(constructorNode.type!==CALL_EXP){_throwError("Expression of type: "+constructorNode.type+" not supported for constructor expression")}return{type:NEW_EXP,callee:constructorNode.callee,arguments:constructorNode.arguments}}if(_literals.has(identifier)){return{type:LITERAL,value:_literals.get(identifier),raw:identifier}}if(_unsupported.has(identifier)){_throwError(`The '${identifier}' keyword is not supported in expressions.`)}return{type:IDENTIFIER,name:identifier}}function _gobbleArguments(context,termination,identifiersOnly){var expr=context.expr;var length=expr.length;var ch_i,args=[],node,closed=false;var separator_count=0;while(context.index<length){_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i===termination){closed=true;context.index++;if(termination===CPAREN_CODE&&separator_count&&separator_count>=args.length){_throwError("Unexpected token "+String.fromCharCode(termination),context.index)}break}else if(ch_i===COMMA_CODE){context.index++;separator_count++;if(separator_count!==args.length){if(termination===CPAREN_CODE){_throwError("Unexpected token ,",context.index)}else if(termination===CBRACK_CODE){for(var arg=args.length;arg<separator_count;arg++){args.push(null)}}}}else{if(identifiersOnly){node=_gobbleIdentifier(context)}else{node=_gobbleExpression(context)}if(!node||args.length>separator_count){_throwError("Expected comma",context.index)}args.push(node)}}if(!closed){_throwError("Expected "+String.fromCharCode(termination),context.index)}return args}function _gobbleVariable(context,stopAtType){var expr=context.expr;var ch_i,node;ch_i=expr.charCodeAt(context.index);if(ch_i===OPAREN_CODE){node=_gobbleGroup(context)}else if(ch_i===SQUOTE_CODE||ch_i===DQUOTE_CODE){node=_gobbleStringLiteral(context)}else if(ch_i===OBRACK_CODE){node=_gobbleArray(context)}else{node=_gobbleIdentifier(context)}_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);while(ch_i===PERIOD_CODE||ch_i===OBRACK_CODE||ch_i===OPAREN_CODE||_isOptionalChaining(context)){context.index++;if(ch_i===PERIOD_CODE){_gobbleSpaces(context);node={type:MEMBER_EXP,computed:false,object:node,property:_gobbleIdentifier(context,true)}}else if(ch_i===QUMARK_CODE){context.index++;_gobbleSpaces(context);node={type:MEMBER_EXP,computed:false,optional:true,object:node,property:_gobbleIdentifier(context,true)}}else if(ch_i===OBRACK_CODE){node={type:MEMBER_EXP,computed:true,object:node,property:_gobbleExpression(context)};_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACK_CODE){_throwError("Unclosed [",context.index)}context.index++}else if(ch_i===OPAREN_CODE){node={type:CALL_EXP,arguments:_gobbleArguments(context,CPAREN_CODE),callee:node}}if(stopAtType===node.type){return node}_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index)}return node}function _gobbleGroup(context){context.index++;let nodes=_gobbleExpressions(context,CPAREN_CODE);if(context.expr.charCodeAt(context.index)===CPAREN_CODE){context.index++;if(nodes.length===1){return nodes[0]}else if(!nodes.length){return false}return{type:SEQUENCE_EXP,expressions:nodes}}_throwError("Unclosed (",context.index)}function _gobbleArray(context){context.index++;return{type:ARRAY_EXP,elements:_gobbleArguments(context,CBRACK_CODE)}}function _gobbleFunctionBody(context){_gobbleSpaces(context);const expr=context.expr;let ch_i=expr.charCodeAt(context.index);context.index++;_gobbleSpaces(context);let hasReturn=false;const start=context.index;if(expr.substring(start,start+6)==="return"){hasReturn=true;context.index+=6}_gobbleSpaces(context);const funcBody=_gobbleExpression(context);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i===SEMCOL_CODE){context.index++;_gobbleSpaces(context)}ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACE_CODE){_throwError("Expected },",context.index)}context.index++;return{type:BLOCK_STATEMENT,expr:expr.substring(start,context.index-1),body:hasReturn?{type:RETURN_STATEMENT,argument:funcBody}:funcBody}}function _gobbleFunction(context){var expr=context.expr;_gobbleSpaces(context);var ch_i=expr.charCodeAt(context.index);if(ch_i!==OPAREN_CODE){_throwError("Expected (,",context.index)}context.index++;var args=_gobbleArguments(context,CPAREN_CODE,true);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(ch_i!==OBRACE_CODE){_throwError("Expected {,",context.index)}return{type:FUNCTION_EXP,params:args,body:_gobbleFunctionBody(context)}}function _gobbleObjectLiteral(context){var expr=context.expr;context.index++;var props=[];var closed;var separator_count=0;var length=expr.length;while(context.index<length&&!closed){_gobbleSpaces(context);var ch_i=expr.charCodeAt(context.index);if(ch_i===CBRACE_CODE){closed=true;context.index++}else if(ch_i===COMMA_CODE){context.index++;separator_count++;if(separator_count!==props.length){_throwError("Unexpected token ,",context.index)}}else{var key=ch_i===SQUOTE_CODE||ch_i===DQUOTE_CODE?_gobbleStringLiteral(context):_gobbleIdentifier(context);_gobbleSpaces(context);ch_i=expr.charCodeAt(context.index);if(key.type===IDENTIFIER&&(ch_i===COMMA_CODE||ch_i===CBRACE_CODE)){props.push({type:PROPERTY,key:key,value:key,shorthand:true})}else if(ch_i===COLON_CODE){context.index++;var writer=context.writer;var keyValue=getKeyValue(key);if(keyValue==="_ko_property_writers"){context.writer=1}try{props.push({type:PROPERTY,key:key,value:_gobbleExpression(context),shorthand:false})}finally{context.writer=writer}}else{_throwError("Expected ':'. Found "+String.fromCharCode(ch_i),context.index)}}}if(!closed){_throwError("Expected "+String.fromCharCode(CBRACE_CODE),context.index)}return{type:OBJECT_EXP,properties:props}}function _gobbleTemplateLiteral(context){const expr=context.expr;let ch_i=expr.charCodeAt(context.index);if(ch_i===BTICK_CODE){const node={type:TEMPLATE_LITERAL,quasis:[],expressions:[]};let cooked="";let raw="";let closed=false;const length=expr.length;const pushQuasi=()=>node.quasis.push({type:TEMPLATE_ELEMENT,value:{raw,cooked},tail:closed});while(context.index<length){let ch=expr.charAt(++context.index);if(ch==="`"){context.index+=1;closed=true;pushQuasi();return node}else if(ch==="$"&&expr.charAt(context.index+1)==="{"){context.index+=2;pushQuasi();raw="";cooked="";try{node.expressions.push(..._gobbleExpressions(context,CBRACE_CODE))}finally{ch_i=expr.charCodeAt(context.index);if(ch_i!==CBRACE_CODE){_throwError("Unclosed ${ in template literal",expr)}}}else if(ch==="\\"){raw+=ch;ch=expr.charAt(++context.index);raw+=ch;switch(ch){case"n":cooked+="\n";break;case"r":cooked+="\r";break;case"t":cooked+="\t";break;case"b":cooked+="\b";break;case"f":cooked+="\f";break;case"v":cooked+="\x0B";break;default:cooked+=ch}}else{cooked+=ch;raw+=ch}}if(context.index===length){_throwError("Unclosed backtick ` in template literal",expr)}}return false}function _gobbleArrowFunctionExpression(context){const expr=context.expr;let ch=expr.charCodeAt(context.index);let node;if(ch===OPAREN_CODE){const backupIndex=context.index;context.index++;_gobbleSpaces(context);ch=expr.charCodeAt(context.index);if(ch===CPAREN_CODE){context.index++;const biop=_gobbleBinaryOp(context);if(biop==="=>"){const body=_gobbleArrowFunctionBody(context);if(!body){_throwError("Expected expression after "+biop)}node={type:ARROW_EXP,params:[],body}}}if(!node){context.index=backupIndex}}return node}function _gobbleArrowFunctionBody(context){const expr=context.expr;_gobbleSpaces(context);let returnNode;if(expr.charCodeAt(context.index)===OBRACE_CODE){returnNode=_gobbleFunctionBody(context)}else{const startDef=context.index;_gobbleSpaces(context);const funcBody=_gobbleExpression(context);_gobbleSpaces(context);returnNode={type:BLOCK_STATEMENT,expr:expr.substring(startDef,context.index),body:{type:RETURN_STATEMENT,argument:funcBody}}}return returnNode}function _updateBinariesToArrows(node){if(node){Object.values(node).forEach(val=>{if(val&&typeof val==="object"){_updateBinariesToArrows(val)}});if(node.operator==="=>"){node.type=ARROW_EXP;node.params=node.left?[node.left]:null;node.body=node.right;if(node.params&&node.params[0].type===SEQUENCE_EXP){node.params=node.params[0].expressions}delete node.left;delete node.right;delete node.operator}}}var PERIOD_CODE=46,COMMA_CODE=44,SQUOTE_CODE=39,DQUOTE_CODE=34,OPAREN_CODE=40,CPAREN_CODE=41,OBRACK_CODE=91,CBRACK_CODE=93,QUMARK_CODE=63,SEMCOL_CODE=59,COLON_CODE=58,BTICK_CODE=96,OBRACE_CODE=123,CBRACE_CODE=125;function _getMaxKeyLen(obj){return Object.keys(obj).reduce(function(curr,key){return Math.max(curr,key.length)},0)}var t=true,_unary_ops={"-":t,"!":t,"~":t,"+":t,typeof:t},_binary_ops={"=":1,"||":2,"??":2,"&&":3,"|":4,"^":5,"&":6,"==":7,"!=":7,"===":7,"!==":7,"<":8,">":8,"<=":8,">=":8,instanceof:8,"<<":9,">>":9,">>>":9,"+":10,"-":10,"*":11,"/":11,"%":11,"**":12,"=>":0.1},_max_unop_len=_getMaxKeyLen(_unary_ops),_max_binop_len=_getMaxKeyLen(_binary_ops);var _literals=new Map;_literals.set("true",true);_literals.set("false",false);_literals.set("null",null);_literals.set("undefined",undefined);var _unsupported=new Set(["await"]);function _binaryPrecedence(op_val,prev_op_val,prev_op_prec){const basePrec=_binary_ops[op_val]||0;if(basePrec!==12||prev_op_val===undefined||op_val!==prev_op_val){return basePrec}return(prev_op_prec+13)*0.5}function _createBinaryExpression(operator,left,right,context){if(operator==="="&&!context.writer){_throwError("Unexpected operator '='",context.index)}var type=operator==="||"||operator==="&&"||operator==="??"?LOGICAL_EXP:BINARY_EXP;return{type:type,operator:operator,left:left,right:right}}function _isOptionalChaining(context){var expr=context.expr;if(expr.charCodeAt(context.index)===QUMARK_CODE&&expr.charCodeAt(context.index+1)===PERIOD_CODE&&!_isDecimalDigit(expr.charCodeAt(context.index+2))){return true}return false}function _isDecimalDigit(ch){return ch>=48&&ch<=57}function _isIdentifierStart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=128&&!_binary_ops[String.fromCharCode(ch)]}function _isIdentifierPart(ch){return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch>=128&&!_binary_ops[String.fromCharCode(ch)]}function _throwError(message,index){var error=new Error(message+" at character "+index);error.index=index;error.description=message;throw error}};const getKeyValue=function(keyObj){return keyObj.type===IDENTIFIER?keyObj.name:keyObj.value};module.exports=ExpParser;const COMPOUND="Compound";const IDENTIFIER="Identifier";const MEMBER_EXP="MemberExpression";const LITERAL="Literal";const CALL_EXP="CallExpression";const UNARY_EXP="UnaryExpression";const BINARY_EXP="BinaryExpression";const LOGICAL_EXP="LogicalExpression";const CONDITIONAL_EXP="ConditionalExpression";const ARRAY_EXP="ArrayExpression";const OBJECT_EXP="ObjectExpression";const FUNCTION_EXP="FunctionExpression";const NEW_EXP="NewExpression";const PROPERTY="Property";const TEMPLATE_LITERAL="TemplateLiteral";const TEMPLATE_ELEMENT="TemplateElement";const SEQUENCE_EXP="SequenceExpression";const ARROW_EXP="ArrowFunctionExpression";const RETURN_STATEMENT="ReturnStatement";const BLOCK_STATEMENT="BlockStatement";