miniprogram-ci 1.6.1 → 1.6.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/@types/config.d.ts +1 -1
- package/dist/@types/core/js/generateMap.d.ts +3 -0
- package/dist/@types/types/miniprogram-json/projectconfig.d.ts +1 -0
- package/dist/ci/code-analyse.js +1 -1
- package/dist/ci/cos-upload.js +1 -1
- package/dist/ci/getCompiledResult.js +1 -1
- package/dist/ci/getDevSourceMap.js +1 -1
- package/dist/ci/getLatestVersion.js +1 -1
- package/dist/ci/jsserver.js +1 -1
- package/dist/ci/preview.js +1 -1
- package/dist/ci/project.js +1 -1
- package/dist/ci/projectattr.js +1 -1
- package/dist/ci/upload.js +1 -1
- package/dist/ci/utils/packfile.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/cloud/cloudapi.js +1 -1
- package/dist/cloud/createTimeTrigger.js +1 -1
- package/dist/cloud/uploadContainer.js +1 -1
- package/dist/cloud/uploadFile.js +1 -1
- package/dist/cloud/uploadFunction.js +1 -1
- package/dist/cloud/utils.js +1 -1
- package/dist/config.js +1 -1
- package/dist/core/compile/common.js +1 -1
- package/dist/core/compile/game.js +1 -1
- package/dist/core/compile/game_plugin.js +1 -1
- package/dist/core/compile/handler/js.js +1 -1
- package/dist/core/compile/handler/mpjson.js +1 -1
- package/dist/core/compile/handler/wxml.js +1 -1
- package/dist/core/compile/handler/wxss.js +1 -1
- package/dist/core/compile/index.js +1 -1
- package/dist/core/compile/mini_program.js +1 -1
- package/dist/core/compile/mini_program_plugin.js +1 -1
- package/dist/core/js/enhance.js +1 -1
- package/dist/core/js/generateMap.js +1 -0
- package/dist/core/js/index.js +1 -1
- package/dist/core/js/minifyjs_after_wrap.js +1 -1
- package/dist/core/json/app/checkAppFields.js +1 -1
- package/dist/core/json/app/getAppJSON.js +1 -1
- package/dist/core/json/app/getExtJSON.js +1 -1
- package/dist/core/json/app/index.js +1 -1
- package/dist/core/json/common.js +1 -1
- package/dist/core/json/game.js +1 -1
- package/dist/core/json/page/checkPageJSON.js +1 -1
- package/dist/core/json/page/getPageJSON.js +1 -1
- package/dist/core/json/plugin/plugin.js +1 -1
- package/dist/core/json/plugin/plugin_page.js +1 -1
- package/dist/core/json/projectWithMockBuffer.js +1 -1
- package/dist/core/json/projectconfig.js +1 -1
- package/dist/core/json/reactiveCache.js +1 -1
- package/dist/core/json/signaturejson.js +1 -1
- package/dist/core/json/sitemap.js +1 -1
- package/dist/core/json/theme.js +1 -1
- package/dist/core/npm/filterdeps.js +1 -1
- package/dist/core/npm/packnpm.js +1 -1
- package/dist/core/protect/file_flatter.js +1 -1
- package/dist/core/protect/uglifyfilenames.js +1 -1
- package/dist/core/validate/validate.js +1 -1
- package/dist/core/worker_thread/childprocess.js +1 -1
- package/dist/core/worker_thread/childprocess_manager.js +1 -1
- package/dist/core/worker_thread/fork.js +1 -1
- package/dist/core/worker_thread/index.js +1 -1
- package/dist/core/worker_thread/task/call_func.js +1 -1
- package/dist/core/worker_thread/task/compilejs.js +1 -1
- package/dist/core/worker_thread/task/compilewxss.js +1 -1
- package/dist/core/worker_thread/task/func.js +1 -1
- package/dist/core/worker_thread/task/minifywxml.js +1 -1
- package/dist/core/worker_thread/worker.js +1 -1
- package/dist/core/worker_thread/worker_manager.js +1 -1
- package/dist/core.js +1 -1
- package/dist/index.js +1 -1
- package/dist/manifest.json +2 -2
- package/dist/summer/devtool.js +1 -1
- package/dist/summer/entry_process.js +1 -1
- package/dist/summer/graph/appconf.js +1 -1
- package/dist/summer/graph/basegraph.js +1 -1
- package/dist/summer/graph/pluginconf.js +1 -1
- package/dist/summer/initPlugin.js +1 -1
- package/dist/summer/module.js +1 -1
- package/dist/summer/persist_cache.js +1 -1
- package/dist/summer/plugin_driver.js +1 -1
- package/dist/summer/plugins/base/es6module.js +1 -1
- package/dist/summer/plugins/base/javascript.js +1 -1
- package/dist/summer/plugins/base/wxss.js +1 -1
- package/dist/summer/plugins/enhance.js +1 -1
- package/dist/summer/plugins/less.js +1 -1
- package/dist/summer/plugins/sass.js +1 -1
- package/dist/summer/plugins/terser.js +1 -1
- package/dist/summer/plugins/typescript.js +1 -1
- package/dist/summer/project.js +1 -1
- package/dist/summer/resolver.js +1 -1
- package/dist/summer/summer.js +1 -1
- package/dist/summer/worker.js +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/miniprogram-json/index.js +1 -1
- package/dist/utils/babel_helper.js +1 -1
- package/dist/utils/cache.js +1 -1
- package/dist/utils/common.js +1 -1
- package/dist/utils/error.js +1 -1
- package/dist/utils/fsagent.js +1 -1
- package/dist/utils/glob.js +1 -1
- package/dist/utils/jsonParse.js +1 -1
- package/dist/utils/locales/locales.js +1 -1
- package/dist/utils/report.js +1 -1
- package/dist/utils/request.js +1 -1
- package/dist/utils/sign.js +1 -1
- package/dist/utils/taskstatus.js +1 -1
- package/dist/utils/tools.js +1 -1
- package/dist/utils/white_ext_list.js +1 -1
- package/dist/utils/wxvpkgreader/wxvpkgreader.js +1 -1
- package/dist/vendor/cloud-api/src/apis/apis.js +1 -1
- package/dist/vendor/cloud-api/src/apis/cdn/cdn.apis.js +1 -1
- package/dist/vendor/cloud-api/src/apis/cdn/index.js +1 -1
- package/dist/vendor/cloud-api/src/apis/flexdb/flexdb.apis.js +1 -1
- package/dist/vendor/cloud-api/src/apis/flexdb/index.js +1 -1
- package/dist/vendor/cloud-api/src/apis/scf/index.js +1 -1
- package/dist/vendor/cloud-api/src/apis/scf/scf.apis.js +1 -1
- package/dist/vendor/cloud-api/src/apis/ssl/index.js +1 -1
- package/dist/vendor/cloud-api/src/apis/ssl/ssl.apis.js +1 -1
- package/dist/vendor/cloud-api/src/apis/tcb/general.apis.js +1 -1
- package/dist/vendor/cloud-api/src/apis/tcb/index.js +1 -1
- package/dist/vendor/cloud-api/src/apis/tcb/tcb.apis.js +1 -1
- package/dist/vendor/cloud-api/src/index.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/contracts/cdn.contracts.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/contracts/contracts.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/contracts/flexdb.contracts.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/contracts/scf.contracts.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/contracts/ssl.contracts.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/contracts/tcb.contracts.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/validations/cdn.validations.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/validations/common.validations.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/validations/flexdb.validations.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/validations/scf.validations.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/validations/ssl.validations.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/validations/tcb.validations.js +1 -1
- package/dist/vendor/cloud-api/src/transaction/validations/validations.js +1 -1
- package/dist/vendor/schema/dist/app.js +1 -1
- package/dist/vendor/schema/dist/ext.js +1 -1
- package/dist/vendor/schema/dist/game.js +29 -1
- package/dist/vendor/schema/dist/page.js +1 -1
- package/dist/vendor/schema/dist/plugin.js +1 -1
- package/dist/vendor/schema/dist/pluginpage.js +1 -1
- package/dist/vendor/schema/dist/projectconfig.js +7 -1
- package/dist/vendor/schema/dist/sitemap.js +1 -1
- package/dist/vendor/schema/dist/theme.js +1 -1
- package/package.json +2 -1
package/dist/core/npm/packnpm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.packNpmManually=exports.packNpm=void 0;const tslib_1=require("tslib"),config_1=require("../../config"),lodash_1=tslib_1.__importDefault(require("lodash")),rimraf_1=tslib_1.__importDefault(require("rimraf")),path_1=tslib_1.__importDefault(require("path")),fs_1=tslib_1.__importDefault(require("fs")),glob_1=tslib_1.__importDefault(require("glob")),source_map_1=tslib_1.__importDefault(require("source-map")),filterdeps_1=tslib_1.__importDefault(require("./filterdeps")),locales_1=tslib_1.__importDefault(require("../../utils/locales/locales")),error_1=require("../../utils/error"),log_1=tslib_1.__importDefault(require("../../utils/log")),projectconfig_1=require("../json/projectconfig"),acorn=require("acorn"),NPM_RECORD={start_time:Date.now(),pack_time:0,miniprogram_pack_num:0,other_pack_num:0,warn_not_found_num:0,warn_require_var_num:0,warn_require_rename_num:0,extra1:"",extra2:"",extra3:""},REPORT_LIST=["pack_time","miniprogram_pack_num","other_pack_num","warn_not_found_num","warn_require_var_num","warn_require_rename_num","extra1","extra2","extra3"];function wrap(e,t){return function(...a){if(a.length){const e=a.pop();"function"!=typeof e&&a.push(e)}return new Promise((r,n)=>{a.push((e,t)=>{e?n(e):r(t)}),e.apply(t||null,a)})}}const statSync=wrap(fs_1.default.stat),mkdirSync=wrap(fs_1.default.mkdir),readFileSync=wrap(fs_1.default.readFile),writeFileSync=wrap(fs_1.default.writeFile),accessSync=wrap(fs_1.default.access),renameSync=wrap(fs_1.default.rename),globSync=wrap(glob_1.default);let seed=+new Date;function getId(){return++seed}function startRecord(){NPM_RECORD.start_time=Date.now(),REPORT_LIST.forEach(e=>NPM_RECORD[e]=0===e.indexOf("extra")?"":0)}function endRecord(e){NPM_RECORD.pack_time=Date.now()-NPM_RECORD.start_time;const t={};REPORT_LIST.forEach(e=>t[e]=NPM_RECORD[e]);try{null==e||e(t)}catch(e){}}async function recursiveMkdir(e){const t=path_1.default.posix.dirname(e);try{await accessSync(t)}catch(e){await recursiveMkdir(t)}try{await accessSync(e);const t=await statSync(e);t&&!t.isDirectory()&&(await renameSync(e,e+".bak"),log_1.default.warn(e+" already exists but is not a directory, so it will be rename to a file with the suffix ending in '.bak'"),await mkdirSync(e))}catch(t){await mkdirSync(e)}}async function copyFile(e,t){const a=await readFileSync(e);await writeFile(a,t)}async function writeFile(e,t){await recursiveMkdir(path_1.default.posix.dirname(t)),await writeFileSync(t,e)}function walkNode(e,t){t(e),Object.keys(e).forEach(a=>{const r=e[a];Array.isArray(r)&&r.forEach(e=>{(null==e?void 0:e.type)&&walkNode(e,t)}),(null==r?void 0:r.type)&&walkNode(r,t)})}function parseDeps(e,t,a){const r=[];let n,o=[];try{n=acorn.parse(e,{sourceType:"module",locations:!0,allowHashBang:!0,onComment(t,a,r,n){t||"#"!==e[r]||o.push({start:r,end:n,adjustContent:""})}})}catch(e){throw console.error(`parse js file (${t}) failed`),e}return walkNode(n,n=>{const i=n.callee,s=n.arguments;if("CallExpression"===n.type&&i&&"Identifier"===i.type&&"require"===i.name&&s&&1===s.length&&("Literal"===s[0].type?r.push(s[0].value):(a.push({jsPath:t,code:e.substring(n.start,n.end),startLine:n.loc.start.line,endLine:n.loc.end.line,tips:"require variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_VAR.format()}),NPM_RECORD.warn_require_var_num++)),"ExpressionStatement"===n.type&&n.expression&&"use strict"===n.expression.value&&o.push({start:n.start,end:n.end,adjustContent:""}),"ImportDeclaration"===n.type){const e=n.source,t=n.specifiers,a={start:n.start,end:n.end,adjustContent:""},i=[];e&&"Literal"===e.type&&(r.push(e.value),i.push(`var __TEMP__ = require('${e.value}');`)),t&&Array.isArray(t)&&t.forEach(e=>{if("ImportSpecifier"===e.type){const t=e.local,a=e.imported;"Identifier"===t.type&&"Identifier"===a.type&&i.push(`var ${t.name} = __TEMP__['${a.name}'];`)}else if("ImportDefaultSpecifier"===e.type){const t=e.local;"Identifier"===t.type&&i.push(`var ${t.name} = __REQUIRE_DEFAULT__(__TEMP__);`)}else if("ImportNamespaceSpecifier"===e.type){const t=e.local;"Identifier"===t.type&&i.push(`var ${t.name} = __REQUIRE_WILDCARD__(__TEMP__);`)}}),a.adjustContent=i.join(""),o.push(a)}if("ExportNamedDeclaration"===n.type){const t=n.source,a=n.specifiers,i=n.declaration;let s=!1;const p={start:n.start,end:n.end,adjustContent:""},c=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];if(t&&"Literal"===t.type&&(r.push(t.value),c.push(`var __TEMP__ = require('${t.value}');`),s=!0),i){if("VariableDeclaration"===i.type){const t=i.declarations;t&&Array.isArray(t)&&t.forEach(t=>{if("VariableDeclarator"===t.type){const a=t.id,r=t.init;a&&"Identifier"===a.type&&(p.notAddLines=!0,c.push(`var ${a.name} = exports.${a.name} = ${r?e.substring(r.start,r.end):"undefined"};`))}})}else if("FunctionDeclaration"===i.type){const t=i.id;t&&"Identifier"===t.type&&(p.notAddLines=!0,c.push(`${e.substring(i.start,i.end)};exports.${t.name} = ${t.name}`))}else if("ClassDeclaration"===i.type){const t=i.id;t&&"Identifier"===t.type&&(p.notAddLines=!0,c.push(`${e.substring(i.start,i.end)};exports.${t.name} = ${t.name}`))}}else;a&&Array.isArray(a)&&a.forEach(e=>{if("ExportSpecifier"===e.type){const t=e.local,a=e.exported;"Identifier"===t.type&&"Identifier"===a.type&&c.push(`Object.defineProperty(exports, '${a.name}', { enumerable: true, configurable: true, get: function() { return ${s?"__TEMP__.":""}${t.name}; } });`)}}),p.adjustContent=c.join(""),o.push(p)}else if("ExportAllDeclaration"===n.type){const e=n.source,t={start:n.start,end:n.end,adjustContent:""},a=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];e&&"Literal"===e.type&&(r.push(e.value),a.push(`var __TEMP__ = require('${e.value}');`)),a.push('Object.keys(__TEMP__).forEach(function(k) { if (k === "default" || k === "__esModule") return; Object.defineProperty(exports, k, { enumerable: true, configurable: true, get: function() { return __TEMP__[k]; } }); });'),t.adjustContent=a.join(""),o.push(t)}else if("ExportDefaultDeclaration"===n.type){const t=n.declaration,a={start:n.start,end:n.end,adjustContent:""},r=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];if(t)if(a.notAddLines=!0,t.id){const a=t.id;r.push(`${e.substring(t.start,t.end)};exports.default = ${a.name}`)}else r.push(`exports.default = ${e.substring(t.start,t.end)};`);a.adjustContent=r.join(""),o.push(a)}const p=n.expression;"ExpressionStatement"===n.type&&p&&"AssignmentExpression"===p.type&&"Identifier"===p.right.type&&"require"===p.right.name&&(a.push({jsPath:t,code:e.substring(n.start,n.end),startLine:n.loc.start.line,endLine:n.loc.end.line,tips:"assign require function to a variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_ASSIGN.format()}),NPM_RECORD.warn_require_rename_num++);const c=n.declarations;"VariableDeclaration"===n.type&&c.length>0&&c.forEach(r=>{const o=r.init;"VariableDeclarator"===r.type&&o&&"Identifier"===o.type&&"require"===o.name&&(a.push({jsPath:t,code:e.substring(n.start,n.end),startLine:n.loc.start.line,endLine:n.loc.end.line,tips:"assign require function to a variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_ASSIGN.format()}),NPM_RECORD.warn_require_rename_num++)})}),o=o.sort((e,t)=>t.start-e.start),o.forEach(t=>{const a=e.substring(t.start,t.end),r=t.notAddLines?0:a.split("\n").length;e=e.substring(0,t.start)+t.adjustContent+new Array(r).join("\n")+e.substring(t.end)}),{deps:r,parsedContent:e}}async function parseJs(e,t,a,r,n,o){if(n[t=path_1.default.posix.normalize(t)])return n[t];const i=await readFileSync(t,"utf8"),s=getId(),p=path_1.default.posix.relative(e,t);if(/\.json$/.test(t)){const e={id:s,name:p,content:"module.exports = "+i,deps:[],depsMap:{}};return n[t]=s,r.push(e),s}const{deps:c,parsedContent:_}=parseDeps(i,t,o),u={id:s,name:p,content:_,deps:c,depsMap:{}};n[t]=s,r.push(u);for(const i of c){let s,p=path_1.default.posix.join(path_1.default.posix.dirname(t),i);if(!/\.js$/.test(p)&&!/\.json$/.test(p)){const e=p+".js";try{await accessSync(e),p=e}catch(e){}}try{const e=await statSync(p);(null==e?void 0:e.isDirectory())&&(p=path_1.default.posix.join(p,"index.js"))}catch(e){}/\.js$/.test(p)||/\.json$/.test(p)||(p+=".js");try{await accessSync(p),s=await parseJs(e,p,a,r,n,o)}catch(e){}s&&(u.depsMap[i]=s)}return s}function addJsToMap(e,t,a,r){const n=t.split("\n").length;for(let o=1;o<=n;o++)e.addMapping({generated:{line:r+o,column:0},original:{line:o,column:0},source:a}),e.setSourceContent(a,t)}function findOutsideDeps(e){const t=new Set;return e.forEach(e=>{e.deps.forEach(a=>{Object.keys(e.depsMap).includes(a)||t.add(a)})}),Array.from(t)}async function packJs(e,t,a){try{const t=await statSync(e);(null==t?void 0:t.isDirectory())&&(e=path_1.default.posix.join(e,"index.js"))}catch(e){}/\.js$/.test(e)||/\.json$/.test(e)||(e+=".js");try{await accessSync(e)}catch(t){return a.push({jsPath:e,code:"",tips:"entry file is not found",msg:locales_1.default.config.NOT_FOUND_NPM_ENTRY.format()}),void NPM_RECORD.warn_not_found_num++}const r=new source_map_1.default.SourceMapGenerator({file:"index.js"}),n=[];await parseJs(path_1.default.posix.dirname(e),e,t,n,{},a);const o=findOutsideDeps(n),i=["module.exports = (function() {","var __MODS__ = {};","var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; };",'var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; };',"var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } };","var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; };"];if(n.length){const e=n.shift();i.push(`__DEFINE__(${e.id}, function(require, module, exports) {`),addJsToMap(r,e.content,e.name,i.length),i.push(e.content),i.push(`}, function(modId) {var map = ${JSON.stringify(e.depsMap)}; return __REQUIRE__(map[modId], modId); })`);for(const e of n)i.push(`__DEFINE__(${e.id}, function(require, module, exports) {`),addJsToMap(r,e.content,e.name,i.length),i.push(e.content),i.push(`}, function(modId) { var map = ${JSON.stringify(e.depsMap)}; return __REQUIRE__(map[modId], modId); })`);i.push(`return __REQUIRE__(${e.id});`)}return i.push("})()"),i.push("//miniprogram-npm-outsideDeps="+JSON.stringify(o)),i.push("//# sourceMappingURL=index.js.map"),{js:i.join("\n"),map:r.toString()}}async function checkIsMiniprogramPack(e,t){let a="miniprogram_dist";t.miniprogram&&"string"==typeof t.miniprogram&&(a=t.miniprogram);try{const t=path_1.default.posix.join(e,a);await accessSync(t);const r=await statSync(t);if(null==r?void 0:r.isDirectory())return t}catch(e){}return""}async function packNpm(e,t={}){const a=e.projectPath,r=e.type,n=await projectconfig_1.getProjectConfigJSON(e),o=n.pluginRoot||"",i=n.miniprogramRoot||"",s="miniProgramPlugin"===r||"miniGamePlugin"===r,{ignores:p,reporter:c}=t;if(!a)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("projectPath"),config_1.PARAM_ERROR);if("miniProgramPlugin"===r&&!o)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format('project.config.json "pluginRoot"'),config_1.PARAM_ERROR);startRecord();const _=path_1.default.isAbsolute(a)?a:path_1.default.posix.join(process.cwd(),a),u=[{searchRoot:path_1.default.posix.join(_,i),paths:await globSync("**/package.json",{cwd:path_1.default.posix.join(_,i),nodir:!0,dot:!0,ignore:(p||[]).concat("**/node_modules/**")})}];s&&u.push({searchRoot:path_1.default.posix.join(_,o),paths:await globSync("**/package.json",{cwd:path_1.default.posix.join(_,o),nodir:!0,dot:!0,ignore:(p||[]).concat("**/node_modules/**")})});lodash_1.default.flattenDeep(u.map(e=>e.paths.map(t=>path_1.default.posix.join(e.searchRoot,path_1.default.dirname(t),"miniprogram_npm")))).forEach(e=>rimraf_1.default.sync(e));const l=[];for(const e of u)for(const t of e.paths){const a=path_1.default.dirname(path_1.default.posix.join(e.searchRoot,t)),r=lodash_1.default.xorWith(e.paths,[t]).map(e=>path_1.default.posix.join(path_1.default.posix.dirname(e),"/**")).filter(e=>"**"!==e);let n=await globSync("**/package.json",{cwd:a.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:(p||[]).concat(r)});if(n=await filterdeps_1.default(a,n),n&&n.length)for(const e of n){const t=path_1.default.posix.join(a,e);let r=await readFileSync(t,"utf8");const n=path_1.default.dirname(t);let o=n.replace(/([\b/\\])node_modules([\b/\\])/g,(e,t,a)=>`${t}miniprogram_npm${a}`),i=path_1.default.basename(o);const s=i.split("@");s.length&&(i=s.pop()||""),o=o.replace(path_1.default.basename(o),i),r=JSON.parse(r);const p=path_1.default.posix.join(n,r.main||"index.js"),c=await checkIsMiniprogramPack(n,r);if(c){const e=await globSync("**/*",{cwd:c.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:"**/node_modules/**"});for(const t of e)await copyFile(path_1.default.posix.join(c,t),path_1.default.posix.join(o,t));NPM_RECORD.miniprogram_pack_num++}else{const e=await packJs(p,o,l);if(!e)continue;await writeFile(e.js,path_1.default.posix.join(o,"./index.js")),await writeFile(e.map,path_1.default.posix.join(o,"./index.js.map")),NPM_RECORD.other_pack_num++}}}if(endRecord(c),NPM_RECORD.miniprogram_pack_num+NPM_RECORD.other_pack_num<=0)throw new Error("__NO_NODE_MODULES__ "+locales_1.default.config.NOT_FOUND_NODE_MODULES.format());return"function"==typeof e.updateFiles&&e.updateFiles(),l}async function packNpmManually(e){let{packageJsonPath:t,miniprogramNpmDistDir:a}=e;const r=e.ignores||[],n={pack_time:0,miniprogram_pack_num:0,other_pack_num:0,warn_not_found_num:0,warn_require_var_num:0,warn_require_rename_num:0},o=[];if(!a)throw new Error("param miniprogramNpmDistDir is required");if(!t)throw new Error("param packageJsonPath is required");if(path_1.default.isAbsolute(a)||(a=path_1.default.join(process.cwd(),a)),path_1.default.isAbsolute(t)||(t=path_1.default.join(process.cwd(),t)),!fs_1.default.existsSync(t))throw new Error(`param packageJsonPath: ${t} file is not exited`);const i=path_1.default.dirname(t);let s=await globSync("**/package.json",{cwd:i.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:r||[]});if(s=await filterdeps_1.default(i,s),!s||!s.length)return log_1.default.warn("No miniprogram_npm package was built."),{miniProgramPackNum:0,otherNpmPackNum:0,warnList:[]};s=s.filter(e=>e.startsWith("node_modules"));for(const e of s){const t=path_1.default.posix.join(i,e);let r=await readFileSync(t,"utf8");const s=path_1.default.dirname(t);let p=s.replace(/([\b/\\])node_modules([\b/\\])/g,(e,t,a)=>`${t}miniprogram_npm${a}`);p=path_1.default.posix.normalize(path_1.default.posix.join(a,"miniprogram_npm",p.split(/[/\\]miniprogram_npm[/\\]/)[1]));let c=path_1.default.basename(p);const _=c.split("@");_.length&&(c=_.pop()||""),p=p.replace(path_1.default.basename(p),c),r=JSON.parse(r);const u=path_1.default.posix.join(s,r.main||"index.js"),l=await checkIsMiniprogramPack(s,r);if(l){const e=await globSync("**/*",{cwd:l.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:"**/node_modules/**"});for(const t of e)await copyFile(path_1.default.posix.join(l,t),path_1.default.posix.join(p,t));n.miniprogram_pack_num++}else{const e=await packJs(u,p,o);if(!e)continue;await writeFile(e.js,path_1.default.posix.join(p,"./index.js")),await writeFile(e.map,path_1.default.posix.join(p,"./index.js.map")),n.other_pack_num++}}return{miniProgramPackNum:n.miniprogram_pack_num,otherNpmPackNum:n.other_pack_num,warnList:o}}exports.packNpm=packNpm,exports.packNpmManually=packNpmManually;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.packNpmManually=exports.packNpm=void 0;const tslib_1=require("tslib"),config_1=require("../../config"),lodash_1=(0,tslib_1.__importDefault)(require("lodash")),rimraf_1=(0,tslib_1.__importDefault)(require("rimraf")),path_1=(0,tslib_1.__importDefault)(require("path")),fs_1=(0,tslib_1.__importDefault)(require("fs")),glob_1=(0,tslib_1.__importDefault)(require("glob")),source_map_1=(0,tslib_1.__importDefault)(require("source-map")),filterdeps_1=(0,tslib_1.__importDefault)(require("./filterdeps")),locales_1=(0,tslib_1.__importDefault)(require("../../utils/locales/locales")),error_1=require("../../utils/error"),log_1=(0,tslib_1.__importDefault)(require("../../utils/log")),projectconfig_1=require("../json/projectconfig"),acorn=require("acorn"),NPM_RECORD={start_time:Date.now(),pack_time:0,miniprogram_pack_num:0,other_pack_num:0,warn_not_found_num:0,warn_require_var_num:0,warn_require_rename_num:0,extra1:"",extra2:"",extra3:""},REPORT_LIST=["pack_time","miniprogram_pack_num","other_pack_num","warn_not_found_num","warn_require_var_num","warn_require_rename_num","extra1","extra2","extra3"];function wrap(e,t){return function(...a){if(a.length){const e=a.pop();"function"!=typeof e&&a.push(e)}return new Promise((r,n)=>{a.push((e,t)=>{e?n(e):r(t)}),e.apply(t||null,a)})}}const statSync=wrap(fs_1.default.stat),mkdirSync=wrap(fs_1.default.mkdir),readFileSync=wrap(fs_1.default.readFile),writeFileSync=wrap(fs_1.default.writeFile),accessSync=wrap(fs_1.default.access),renameSync=wrap(fs_1.default.rename),globSync=wrap(glob_1.default);let seed=+new Date;function getId(){return++seed}function startRecord(){NPM_RECORD.start_time=Date.now(),REPORT_LIST.forEach(e=>NPM_RECORD[e]=0===e.indexOf("extra")?"":0)}function endRecord(e){NPM_RECORD.pack_time=Date.now()-NPM_RECORD.start_time;const t={};REPORT_LIST.forEach(e=>t[e]=NPM_RECORD[e]);try{null==e||e(t)}catch(e){}}async function recursiveMkdir(e){const t=path_1.default.posix.dirname(e);try{await accessSync(t)}catch(e){await recursiveMkdir(t)}try{await accessSync(e);const t=await statSync(e);t&&!t.isDirectory()&&(await renameSync(e,e+".bak"),log_1.default.warn(e+" already exists but is not a directory, so it will be rename to a file with the suffix ending in '.bak'"),await mkdirSync(e))}catch(t){await mkdirSync(e)}}async function copyFile(e,t){const a=await readFileSync(e);await writeFile(a,t)}async function writeFile(e,t){await recursiveMkdir(path_1.default.posix.dirname(t)),await writeFileSync(t,e)}function walkNode(e,t){t(e),Object.keys(e).forEach(a=>{const r=e[a];Array.isArray(r)&&r.forEach(e=>{(null==e?void 0:e.type)&&walkNode(e,t)}),(null==r?void 0:r.type)&&walkNode(r,t)})}function parseDeps(e,t,a){const r=[];let n,o=[];try{n=acorn.parse(e,{sourceType:"module",locations:!0,allowHashBang:!0,onComment(t,a,r,n){t||"#"!==e[r]||o.push({start:r,end:n,adjustContent:""})}})}catch(e){throw console.error(`parse js file (${t}) failed`),e}return walkNode(n,n=>{const i=n.callee,s=n.arguments;if("CallExpression"===n.type&&i&&"Identifier"===i.type&&"require"===i.name&&s&&1===s.length&&("Literal"===s[0].type?r.push(s[0].value):(a.push({jsPath:t,code:e.substring(n.start,n.end),startLine:n.loc.start.line,endLine:n.loc.end.line,tips:"require variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_VAR.format()}),NPM_RECORD.warn_require_var_num++)),"ExpressionStatement"===n.type&&n.expression&&"use strict"===n.expression.value&&o.push({start:n.start,end:n.end,adjustContent:""}),"ImportDeclaration"===n.type){const e=n.source,t=n.specifiers,a={start:n.start,end:n.end,adjustContent:""},i=[];e&&"Literal"===e.type&&(r.push(e.value),i.push(`var __TEMP__ = require('${e.value}');`)),t&&Array.isArray(t)&&t.forEach(e=>{if("ImportSpecifier"===e.type){const t=e.local,a=e.imported;"Identifier"===t.type&&"Identifier"===a.type&&i.push(`var ${t.name} = __TEMP__['${a.name}'];`)}else if("ImportDefaultSpecifier"===e.type){const t=e.local;"Identifier"===t.type&&i.push(`var ${t.name} = __REQUIRE_DEFAULT__(__TEMP__);`)}else if("ImportNamespaceSpecifier"===e.type){const t=e.local;"Identifier"===t.type&&i.push(`var ${t.name} = __REQUIRE_WILDCARD__(__TEMP__);`)}}),a.adjustContent=i.join(""),o.push(a)}if("ExportNamedDeclaration"===n.type){const t=n.source,a=n.specifiers,i=n.declaration;let s=!1;const p={start:n.start,end:n.end,adjustContent:""},c=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];if(t&&"Literal"===t.type&&(r.push(t.value),c.push(`var __TEMP__ = require('${t.value}');`),s=!0),i){if("VariableDeclaration"===i.type){const t=i.declarations;t&&Array.isArray(t)&&t.forEach(t=>{if("VariableDeclarator"===t.type){const a=t.id,r=t.init;a&&"Identifier"===a.type&&(p.notAddLines=!0,c.push(`var ${a.name} = exports.${a.name} = ${r?e.substring(r.start,r.end):"undefined"};`))}})}else if("FunctionDeclaration"===i.type){const t=i.id;t&&"Identifier"===t.type&&(p.notAddLines=!0,c.push(`${e.substring(i.start,i.end)};exports.${t.name} = ${t.name}`))}else if("ClassDeclaration"===i.type){const t=i.id;t&&"Identifier"===t.type&&(p.notAddLines=!0,c.push(`${e.substring(i.start,i.end)};exports.${t.name} = ${t.name}`))}}else;a&&Array.isArray(a)&&a.forEach(e=>{if("ExportSpecifier"===e.type){const t=e.local,a=e.exported;"Identifier"===t.type&&"Identifier"===a.type&&c.push(`Object.defineProperty(exports, '${a.name}', { enumerable: true, configurable: true, get: function() { return ${s?"__TEMP__.":""}${t.name}; } });`)}}),p.adjustContent=c.join(""),o.push(p)}else if("ExportAllDeclaration"===n.type){const e=n.source,t={start:n.start,end:n.end,adjustContent:""},a=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];e&&"Literal"===e.type&&(r.push(e.value),a.push(`var __TEMP__ = require('${e.value}');`)),a.push('Object.keys(__TEMP__).forEach(function(k) { if (k === "default" || k === "__esModule") return; Object.defineProperty(exports, k, { enumerable: true, configurable: true, get: function() { return __TEMP__[k]; } }); });'),t.adjustContent=a.join(""),o.push(t)}else if("ExportDefaultDeclaration"===n.type){const t=n.declaration,a={start:n.start,end:n.end,adjustContent:""},r=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];if(t)if(a.notAddLines=!0,t.id){const a=t.id;r.push(`${e.substring(t.start,t.end)};exports.default = ${a.name}`)}else r.push(`exports.default = ${e.substring(t.start,t.end)};`);a.adjustContent=r.join(""),o.push(a)}const p=n.expression;"ExpressionStatement"===n.type&&p&&"AssignmentExpression"===p.type&&"Identifier"===p.right.type&&"require"===p.right.name&&(a.push({jsPath:t,code:e.substring(n.start,n.end),startLine:n.loc.start.line,endLine:n.loc.end.line,tips:"assign require function to a variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_ASSIGN.format()}),NPM_RECORD.warn_require_rename_num++);const c=n.declarations;"VariableDeclaration"===n.type&&c.length>0&&c.forEach(r=>{const o=r.init;"VariableDeclarator"===r.type&&o&&"Identifier"===o.type&&"require"===o.name&&(a.push({jsPath:t,code:e.substring(n.start,n.end),startLine:n.loc.start.line,endLine:n.loc.end.line,tips:"assign require function to a variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_ASSIGN.format()}),NPM_RECORD.warn_require_rename_num++)})}),o=o.sort((e,t)=>t.start-e.start),o.forEach(t=>{const a=e.substring(t.start,t.end),r=t.notAddLines?0:a.split("\n").length;e=e.substring(0,t.start)+t.adjustContent+new Array(r).join("\n")+e.substring(t.end)}),{deps:r,parsedContent:e}}async function parseJs(e,t,a,r,n,o){if(n[t=path_1.default.posix.normalize(t)])return n[t];const i=await readFileSync(t,"utf8"),s=getId(),p=path_1.default.posix.relative(e,t);if(/\.json$/.test(t)){const e={id:s,name:p,content:"module.exports = "+i,deps:[],depsMap:{}};return n[t]=s,r.push(e),s}const{deps:c,parsedContent:_}=parseDeps(i,t,o),u={id:s,name:p,content:_,deps:c,depsMap:{}};n[t]=s,r.push(u);for(const i of c){let s,p=path_1.default.posix.join(path_1.default.posix.dirname(t),i);if(!/\.js$/.test(p)&&!/\.json$/.test(p)){const e=p+".js";try{await accessSync(e),p=e}catch(e){}}try{const e=await statSync(p);(null==e?void 0:e.isDirectory())&&(p=path_1.default.posix.join(p,"index.js"))}catch(e){}/\.js$/.test(p)||/\.json$/.test(p)||(p+=".js");try{await accessSync(p),s=await parseJs(e,p,a,r,n,o)}catch(e){}s&&(u.depsMap[i]=s)}return s}function addJsToMap(e,t,a,r){const n=t.split("\n").length;for(let o=1;o<=n;o++)e.addMapping({generated:{line:r+o,column:0},original:{line:o,column:0},source:a}),e.setSourceContent(a,t)}function findOutsideDeps(e){const t=new Set;return e.forEach(e=>{e.deps.forEach(a=>{Object.keys(e.depsMap).includes(a)||t.add(a)})}),Array.from(t)}async function packJs(e,t,a){try{const t=await statSync(e);(null==t?void 0:t.isDirectory())&&(e=path_1.default.posix.join(e,"index.js"))}catch(e){}/\.js$/.test(e)||/\.json$/.test(e)||(e+=".js");try{await accessSync(e)}catch(t){return a.push({jsPath:e,code:"",tips:"entry file is not found",msg:locales_1.default.config.NOT_FOUND_NPM_ENTRY.format()}),void NPM_RECORD.warn_not_found_num++}const r=new source_map_1.default.SourceMapGenerator({file:"index.js"}),n=[];await parseJs(path_1.default.posix.dirname(e),e,t,n,{},a);const o=findOutsideDeps(n),i=["module.exports = (function() {","var __MODS__ = {};","var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; };",'var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; };',"var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } };","var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; };"];if(n.length){const e=n.shift();i.push(`__DEFINE__(${e.id}, function(require, module, exports) {`),addJsToMap(r,e.content,e.name,i.length),i.push(e.content),i.push(`}, function(modId) {var map = ${JSON.stringify(e.depsMap)}; return __REQUIRE__(map[modId], modId); })`);for(const e of n)i.push(`__DEFINE__(${e.id}, function(require, module, exports) {`),addJsToMap(r,e.content,e.name,i.length),i.push(e.content),i.push(`}, function(modId) { var map = ${JSON.stringify(e.depsMap)}; return __REQUIRE__(map[modId], modId); })`);i.push(`return __REQUIRE__(${e.id});`)}return i.push("})()"),i.push("//miniprogram-npm-outsideDeps="+JSON.stringify(o)),i.push("//# sourceMappingURL=index.js.map"),{js:i.join("\n"),map:r.toString()}}async function checkIsMiniprogramPack(e,t){let a="miniprogram_dist";t.miniprogram&&"string"==typeof t.miniprogram&&(a=t.miniprogram);try{const t=path_1.default.posix.join(e,a);await accessSync(t);const r=await statSync(t);if(null==r?void 0:r.isDirectory())return t}catch(e){}return""}async function packNpm(e,t={}){const a=e.projectPath,r=e.type,n=await(0,projectconfig_1.getProjectConfigJSON)(e),o=n.pluginRoot||"",i=n.miniprogramRoot||"",s="miniProgramPlugin"===r||"miniGamePlugin"===r,{ignores:p,reporter:c}=t;if(!a)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("projectPath"),config_1.PARAM_ERROR);if("miniProgramPlugin"===r&&!o)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format('project.config.json "pluginRoot"'),config_1.PARAM_ERROR);startRecord();const _=path_1.default.isAbsolute(a)?a:path_1.default.posix.join(process.cwd(),a),u=[{searchRoot:path_1.default.posix.join(_,i),paths:await globSync("**/package.json",{cwd:path_1.default.posix.join(_,i),nodir:!0,dot:!0,ignore:(p||[]).concat("**/node_modules/**")})}];s&&u.push({searchRoot:path_1.default.posix.join(_,o),paths:await globSync("**/package.json",{cwd:path_1.default.posix.join(_,o),nodir:!0,dot:!0,ignore:(p||[]).concat("**/node_modules/**")})});lodash_1.default.flattenDeep(u.map(e=>e.paths.map(t=>path_1.default.posix.join(e.searchRoot,path_1.default.dirname(t),"miniprogram_npm")))).forEach(e=>rimraf_1.default.sync(e));const l=[];for(const e of u)for(const t of e.paths){const a=path_1.default.dirname(path_1.default.posix.join(e.searchRoot,t)),r=lodash_1.default.xorWith(e.paths,[t]).map(e=>path_1.default.posix.join(path_1.default.posix.dirname(e),"/**")).filter(e=>"**"!==e);let n=await globSync("**/package.json",{cwd:a.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:(p||[]).concat(r).concat(["node_modules/@types/**"])});if(n=await(0,filterdeps_1.default)(a,n),n&&n.length)for(const e of n){const t=path_1.default.posix.join(a,e);let r=await readFileSync(t,"utf8");const n=path_1.default.dirname(t);let o=n.replace(/([\b/\\])node_modules([\b/\\])/g,(e,t,a)=>`${t}miniprogram_npm${a}`),i=path_1.default.basename(o);const s=i.split("@");s.length&&(i=s.pop()||""),o=o.replace(path_1.default.basename(o),i),r=JSON.parse(r);const p=path_1.default.posix.join(n,r.main||"index.js"),c=await checkIsMiniprogramPack(n,r);if(c){const e=await globSync("**/*",{cwd:c.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:"**/node_modules/**"});for(const t of e)await copyFile(path_1.default.posix.join(c,t),path_1.default.posix.join(o,t));NPM_RECORD.miniprogram_pack_num++}else{const e=await packJs(p,o,l);if(!e)continue;await writeFile(e.js,path_1.default.posix.join(o,"./index.js")),await writeFile(e.map,path_1.default.posix.join(o,"./index.js.map")),NPM_RECORD.other_pack_num++}}}if(endRecord(c),NPM_RECORD.miniprogram_pack_num+NPM_RECORD.other_pack_num<=0)throw new Error("__NO_NODE_MODULES__ "+locales_1.default.config.NOT_FOUND_NODE_MODULES.format());return"function"==typeof e.updateFiles&&e.updateFiles(),l}async function packNpmManually(e){let{packageJsonPath:t,miniprogramNpmDistDir:a}=e;const r=e.ignores||[],n={pack_time:0,miniprogram_pack_num:0,other_pack_num:0,warn_not_found_num:0,warn_require_var_num:0,warn_require_rename_num:0},o=[];if(!a)throw new Error("param miniprogramNpmDistDir is required");if(!t)throw new Error("param packageJsonPath is required");if(path_1.default.isAbsolute(a)||(a=path_1.default.join(process.cwd(),a)),path_1.default.isAbsolute(t)||(t=path_1.default.join(process.cwd(),t)),!fs_1.default.existsSync(t))throw new Error(`param packageJsonPath: ${t} file is not exited`);const i=path_1.default.dirname(t);let s=await globSync("**/package.json",{cwd:i.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:(r||[]).concat(["node_modules/@types/**"])});if(s=await(0,filterdeps_1.default)(i,s),!s||!s.length)return log_1.default.warn("No miniprogram_npm package was built."),{miniProgramPackNum:0,otherNpmPackNum:0,warnList:[]};s=s.filter(e=>e.startsWith("node_modules"));for(const e of s){const t=path_1.default.posix.join(i,e);let r=await readFileSync(t,"utf8");const s=path_1.default.dirname(t);let p=s.replace(/([\b/\\])node_modules([\b/\\])/g,(e,t,a)=>`${t}miniprogram_npm${a}`);p=path_1.default.posix.normalize(path_1.default.posix.join(a,"miniprogram_npm",p.split(/[/\\]miniprogram_npm[/\\]/)[1]));let c=path_1.default.basename(p);const _=c.split("@");_.length&&(c=_.pop()||""),p=p.replace(path_1.default.basename(p),c),r=JSON.parse(r);const u=path_1.default.posix.join(s,r.main||"index.js"),l=await checkIsMiniprogramPack(s,r);if(l){const e=await globSync("**/*",{cwd:l.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:"**/node_modules/**"});for(const t of e)await copyFile(path_1.default.posix.join(l,t),path_1.default.posix.join(p,t));n.miniprogram_pack_num++}else{const e=await packJs(u,p,o);if(!e)continue;await writeFile(e.js,path_1.default.posix.join(p,"./index.js")),await writeFile(e.map,path_1.default.posix.join(p,"./index.js.map")),n.other_pack_num++}}return{miniProgramPackNum:n.miniprogram_pack_num,otherNpmPackNum:n.other_pack_num,warnList:o}}exports.packNpm=packNpm,exports.packNpmManually=packNpmManually;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.tryTranslateSingleFile=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),parser=tslib_1.__importStar(require("@babel/parser")),traverse_1=tslib_1.__importDefault(require("@babel/traverse")),sourcemap=tslib_1.__importStar(require("source-map")),babel_code_frame_1=tslib_1.__importDefault(require("babel-code-frame"));class TranslateResult{constructor(){this.translated=!0,this.errMsg="",this.debugs=[],this.translatedContent="",this.fullPath="",this.translatedSourceMap=""}}function getErrorCodeFrame(e,n,t,r){let o;try{o=new sourcemap.SourceMapConsumer(n||""),e=o.sourceContentFor(t)||e}catch(e){}const i=[];for(const n of r){let t={line:n.line,column:n.column>0?n.column:0};try{o&&(t=o.originalPositionFor({line:n.line,column:n.column}))}catch(e){}const r=babel_code_frame_1.default(e,t.line,t.column);i.push(`${n.reason}\n${r}`)}return i.join("\n\n")}function translateCode(e,n){const t=e.replace(/\r\n/g,"\n").split("\n");for(let e=0;e<t.length;e++){const r=t[e],o=n[e+1];if(o){const n=[];let i=0;for(const e in o){const t=o[e];n.push(r.substr(i,t.column-i+1)),n.push(t.toString),i=t.column+t.fromString.length+1}n.push(r.substr(i)),t[e]=n.join("")}}return t.join("\n")}function translateSourceMap(e,n,t){const r=new sourcemap.SourceMapConsumer(e),o=new sourcemap.SourceMapGenerator({file:n});let i;return r.eachMapping(e=>{if("number"!=typeof e.originalLine||"number"!=typeof e.originalColumn)return;const n={generated:{line:e.generatedLine,column:e.generatedColumn},source:e.source,name:e.name,original:{line:e.originalLine,column:e.originalColumn}};if(i&&i.line===e.generatedLine?n.generated.column+=i.offset:i=void 0,t[e.generatedLine]){const n=t[e.generatedLine][e.generatedColumn];n&&(i&&i.line===n.line?i.offset+=n.offset:i={line:n.line,offset:n.offset})}o.addMapping(n)}),o.toString()}function dirname(e){const n=e.split("/");return n.pop(),n.join("/")}function getNpmRequirePath(e,n,t){if(e.startsWith(".")||e.startsWith("/"))return!1;{let r,o=n;for(;o;)if(o=dirname(o),r=e.endsWith(".js")?path_1.default.posix.join(o,"miniprogram_npm",e):path_1.default.posix.join(o,"miniprogram_npm",e,"index.js"),t.includes(r))return r;return!1}}const tryTranslateSingleFile=e=>{var n,t;const r=new TranslateResult,{filePath:o,nameMapping:i,code:a,rootPath:l,miniProgramJSFiles:s}=e;let u=path_1.default.posix.dirname(path_1.default.posix.relative(l,o));"."===u&&(u="");const c=[];let p;try{p=parser.parse(a)}catch(i){return c.push({line:(null===(n=i.loc)||void 0===n?void 0:n.line)||1,column:(null===(t=i.loc)||void 0===t?void 0:t.column)||1,reason:i.message}),r.translated=!1,r.errMsg=`in ${path_1.default.posix.join(l,o)}\n${getErrorCodeFrame(a,e.sourceMap,e.sourceFileName,c)}`,r}const d={};if(traverse_1.default(p,{AssignmentExpression(e){const n=e.node.loc.start;"Identifier"===e.node.left.type&&"require"===e.node.left.name&&c.push({line:n.line,column:n.column,reason:"assigning other name with 'require'"}),"Identifier"===e.node.right.type&&"require"===e.node.right.name&&c.push({line:n.line,column:n.column,reason:"'require' should not be renamed"})},VariableDeclarator(e){const n=e.node.loc.start;e.node.id&&"Identifier"===e.node.id.type&&"require"===e.node.id.name&&c.push({line:n.line,column:n.column,reason:"(init) assigning other name with 'require'"}),e.node.init&&"Identifier"===e.node.init.type&&"require"===e.node.init.name&&c.push({line:n.line,column:n.column,reason:"(init) 'require' should not be renamed"})},CallExpression(e){const n=e.node.loc.start;for(const t of e.node.arguments)"Identifier"===t.type&&"require"===t.name&&c.push({line:n.line,column:n.column,reason:"passing 'require' as a parameter is not a good taste"});if("Identifier"===e.node.callee.type&&"require"===e.node.callee.name&&(1===e.node.arguments.length&&"StringLiteral"===e.node.arguments[0].type||c.push({line:n.line,column:n.column,reason:"'require' requires one and only one static string literal"})),"require"===e.node.callee.name&&1===e.node.arguments.length&&"StringLiteral"===e.node.arguments[0].type){const n=e.node.arguments[0].loc.start,t=e.node.arguments[0].value;let a=path_1.default.posix.normalize(path_1.default.posix.join(u,t));/\.js$/.test(a)||(a+=".js"),/^\//.test(a)&&(a=a.replace(/^\//,""));let l=i[a];if(l)l=i[o]?path_1.default.posix.relative(path_1.default.posix.dirname(i[o]),l):path_1.default.posix.relative(u,l),d[n.line]||(d[n.line]={}),d[n.line][n.column]={line:n.line,column:n.column,fromString:t,toString:l,offset:l.length-t.length},r.debugs.push([o,t,"replace",[a,l]]);else{if(i[o]){const e=getNpmRequirePath(t,o,s);e&&(a=e),l=path_1.default.posix.relative(path_1.default.posix.dirname(i[o]),a),d[n.line]||(d[n.line]={}),d[n.line][n.column]={line:n.line,column:n.column,fromString:t,toString:l,offset:l.length-t.length},r.debugs.push([o,t,"replace",[a,l]])}r.debugs.push([o,t,"ignored"])}}},Identifier(e){const n=e.node.loc.start;if("require"===e.node.name){if("UnaryExpression"===e.parent.type&&"typeof"===e.parent.operator)return;"CallExpression"!==e.parent.type&&c.push({line:n.line,column:n.column,reason:`require is not being used properly in '${e.parent.type}'`})}}}),c.length>0)return r.translated=!1,r.errMsg=`in ${o}\n${getErrorCodeFrame(a,e.sourceMap,e.sourceFileName,c)}`,r;if(Object.keys(d).length>0){r.translatedContent=translateCode(a,d);try{r.translatedSourceMap=translateSourceMap(e.sourceMap||"",e.sourceFileName,d)}catch(e){}}else r.translatedContent=a,r.translatedSourceMap=e.sourceMap;return r};exports.tryTranslateSingleFile=tryTranslateSingleFile;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.tryTranslateSingleFile=void 0;const tslib_1=require("tslib"),path_1=(0,tslib_1.__importDefault)(require("path")),parser=(0,tslib_1.__importStar)(require("@babel/parser")),traverse_1=(0,tslib_1.__importDefault)(require("@babel/traverse")),sourcemap=(0,tslib_1.__importStar)(require("source-map")),babel_code_frame_1=(0,tslib_1.__importDefault)(require("babel-code-frame"));class TranslateResult{constructor(){this.translated=!0,this.errMsg="",this.debugs=[],this.translatedContent="",this.fullPath="",this.translatedSourceMap=""}}function getErrorCodeFrame(e,n,t,r){let o;try{o=new sourcemap.SourceMapConsumer(n||""),e=o.sourceContentFor(t)||e}catch(e){}const i=[];for(const n of r){let t={line:n.line,column:n.column>0?n.column:0};try{o&&(t=o.originalPositionFor({line:n.line,column:n.column}))}catch(e){}const r=(0,babel_code_frame_1.default)(e,t.line,t.column);i.push(`${n.reason}\n${r}`)}return i.join("\n\n")}function translateCode(e,n){const t=e.replace(/\r\n/g,"\n").split("\n");for(let e=0;e<t.length;e++){const r=t[e],o=n[e+1];if(o){const n=[];let i=0;for(const e in o){const t=o[e];n.push(r.substr(i,t.column-i+1)),n.push(t.toString),i=t.column+t.fromString.length+1}n.push(r.substr(i)),t[e]=n.join("")}}return t.join("\n")}function translateSourceMap(e,n,t){const r=new sourcemap.SourceMapConsumer(e),o=new sourcemap.SourceMapGenerator({file:n});let i;return r.eachMapping(e=>{if("number"!=typeof e.originalLine||"number"!=typeof e.originalColumn)return;const n={generated:{line:e.generatedLine,column:e.generatedColumn},source:e.source,name:e.name,original:{line:e.originalLine,column:e.originalColumn}};if(i&&i.line===e.generatedLine?n.generated.column+=i.offset:i=void 0,t[e.generatedLine]){const n=t[e.generatedLine][e.generatedColumn];n&&(i&&i.line===n.line?i.offset+=n.offset:i={line:n.line,offset:n.offset})}o.addMapping(n)}),o.toString()}function dirname(e){const n=e.split("/");return n.pop(),n.join("/")}function getNpmRequirePath(e,n,t){if(e.startsWith(".")||e.startsWith("/"))return!1;{let r,o=n;for(;o;)if(o=dirname(o),r=e.endsWith(".js")?path_1.default.posix.join(o,"miniprogram_npm",e):path_1.default.posix.join(o,"miniprogram_npm",e,"index.js"),t.includes(r))return r;return!1}}const tryTranslateSingleFile=e=>{var n,t;const r=new TranslateResult,{filePath:o,nameMapping:i,code:a,rootPath:l,miniProgramJSFiles:s}=e;let u=path_1.default.posix.dirname(path_1.default.posix.relative(l,o));"."===u&&(u="");const c=[];let p;try{p=parser.parse(a)}catch(i){return c.push({line:(null===(n=i.loc)||void 0===n?void 0:n.line)||1,column:(null===(t=i.loc)||void 0===t?void 0:t.column)||1,reason:i.message}),r.translated=!1,r.errMsg=`in ${path_1.default.posix.join(l,o)}\n${getErrorCodeFrame(a,e.sourceMap,e.sourceFileName,c)}`,r}const d={};if((0,traverse_1.default)(p,{AssignmentExpression(e){const n=e.node.loc.start;"Identifier"===e.node.left.type&&"require"===e.node.left.name&&c.push({line:n.line,column:n.column,reason:"assigning other name with 'require'"}),"Identifier"===e.node.right.type&&"require"===e.node.right.name&&c.push({line:n.line,column:n.column,reason:"'require' should not be renamed"})},VariableDeclarator(e){const n=e.node.loc.start;e.node.id&&"Identifier"===e.node.id.type&&"require"===e.node.id.name&&c.push({line:n.line,column:n.column,reason:"(init) assigning other name with 'require'"}),e.node.init&&"Identifier"===e.node.init.type&&"require"===e.node.init.name&&c.push({line:n.line,column:n.column,reason:"(init) 'require' should not be renamed"})},CallExpression(e){const n=e.node.loc.start;for(const t of e.node.arguments)"Identifier"===t.type&&"require"===t.name&&c.push({line:n.line,column:n.column,reason:"passing 'require' as a parameter is not a good taste"});if("Identifier"===e.node.callee.type&&"require"===e.node.callee.name&&(1===e.node.arguments.length&&"StringLiteral"===e.node.arguments[0].type||c.push({line:n.line,column:n.column,reason:"'require' requires one and only one static string literal"})),"require"===e.node.callee.name&&1===e.node.arguments.length&&"StringLiteral"===e.node.arguments[0].type){const n=e.node.arguments[0].loc.start,t=e.node.arguments[0].value;let a=path_1.default.posix.normalize(path_1.default.posix.join(u,t));/\.js$/.test(a)||(a+=".js"),/^\//.test(a)&&(a=a.replace(/^\//,""));let l=i[a];if(l)l=i[o]?path_1.default.posix.relative(path_1.default.posix.dirname(i[o]),l):path_1.default.posix.relative(u,l),d[n.line]||(d[n.line]={}),d[n.line][n.column]={line:n.line,column:n.column,fromString:t,toString:l,offset:l.length-t.length},r.debugs.push([o,t,"replace",[a,l]]);else{if(i[o]){const e=getNpmRequirePath(t,o,s);e&&(a=e),l=path_1.default.posix.relative(path_1.default.posix.dirname(i[o]),a),d[n.line]||(d[n.line]={}),d[n.line][n.column]={line:n.line,column:n.column,fromString:t,toString:l,offset:l.length-t.length},r.debugs.push([o,t,"replace",[a,l]])}r.debugs.push([o,t,"ignored"])}}},Identifier(e){const n=e.node.loc.start;if("require"===e.node.name){if("UnaryExpression"===e.parent.type&&"typeof"===e.parent.operator)return;"CallExpression"!==e.parent.type&&c.push({line:n.line,column:n.column,reason:`require is not being used properly in '${e.parent.type}'`})}}}),c.length>0)return r.translated=!1,r.errMsg=`in ${o}\n${getErrorCodeFrame(a,e.sourceMap,e.sourceFileName,c)}`,r;if(Object.keys(d).length>0){r.translatedContent=translateCode(a,d);try{r.translatedSourceMap=translateSourceMap(e.sourceMap||"",e.sourceFileName,d)}catch(e){}}else r.translatedContent=a,r.translatedSourceMap=e.sourceMap;return r};exports.tryTranslateSingleFile=tryTranslateSingleFile;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.uglifyFileNames=exports.getGameNameMapping=exports.getNameMapping=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),config_1=require("../../config"),error_1=require("../../utils/error"),tools_1=require("../../utils/tools"),game_1=tslib_1.__importDefault(require("../json/game")),app_1=require("../json/app"),file_flatter_1=require("./file_flatter"),url_config_1=require("../../utils/url_config"),request_1=require("../../utils/request"),sign_1=require("../../utils/sign"),jsonParse_1=require("../../utils/jsonParse"),locales_1=tslib_1.__importDefault(require("../../utils/locales/locales")),config=tslib_1.__importStar(require("../../config")),common_1=require("../../utils/common");function checkPrefix(e,t){for(const a of t)if(0===e.indexOf(a))return a;return""}const getNameMapping=async(e,t)=>{if(process.env.isDevtools)return e.nameMappingFromDevtools||{};{const a=e.getFileList(t,".js").map(e=>path_1.default.posix.relative(t,e));try{let
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.uglifyFileNames=exports.getGameNameMapping=exports.getNameMapping=void 0;const tslib_1=require("tslib"),path_1=(0,tslib_1.__importDefault)(require("path")),config_1=require("../../config"),error_1=require("../../utils/error"),tools_1=require("../../utils/tools"),game_1=(0,tslib_1.__importDefault)(require("../json/game")),app_1=require("../json/app"),file_flatter_1=require("./file_flatter"),url_config_1=require("../../utils/url_config"),request_1=require("../../utils/request"),sign_1=require("../../utils/sign"),jsonParse_1=require("../../utils/jsonParse"),locales_1=(0,tslib_1.__importDefault)(require("../../utils/locales/locales")),config=(0,tslib_1.__importStar)(require("../../config")),common_1=require("../../utils/common");function checkPrefix(e,t){for(const a of t)if(0===e.indexOf(a))return a;return""}const getNameMapping=async(e,t)=>{if(process.env.isDevtools)return e.nameMappingFromDevtools||{};{const a=e.getFileList(t,".js").map(e=>path_1.default.posix.relative(t,e));try{let r={};if("miniProgram"===e.type){const o=await(0,app_1.getAppJSON)(e);r=await getMiniProgramNameMapping(e,t,o,a)}if("miniGame"===e.type){const t=await(0,game_1.default)(e);r=await(0,exports.getGameNameMapping)(e,t,a)}return r}catch(e){throw new error_1.CodeError(e.toString(),config_1.CODE_PROTECT_TRANSLATE_FILENAME)}}};exports.getNameMapping=getNameMapping;const getMiniProgramNameMapping=async(e,t,a,r)=>{const o=[{type:"file",value:"app.js"},{type:"regex",value:/\/miniprogram_npm\/|^miniprogram_npm\//},{type:"folder",value:"functional-pages/"}],i=e.getFileList(t,".wxml").map(e=>path_1.default.posix.relative(t,e));for(const e of i)o.push({type:"file",value:""+e.replace(/\.wxml$/,".js")});let s=[];return a.subPackages&&(s=a.subPackages.map(e=>e.root)),a.widgets&&a.widgets.length>0&&a.widgets.forEach(e=>{o.push({type:"folder",value:/\/$/.test(e.path)?e.path:e.path+"/"})}),a.workers&&o.push({type:"folder",value:a.workers}),a.openDataContext&&(o.push({type:"file",value:path_1.default.posix.join(a.openDataContext,"index.js")}),s.push(a.openDataContext)),await _getNameMapping(e,r,o,s)},getGameNameMapping=async(e,t,a)=>{const r=[{type:"file",value:"game.js"},{type:"regex",value:/\/miniprogram_npm\/|^miniprogram_npm\//}],o=[];if(t.subPackages&&t.subPackages.forEach(e=>{const t=e.root.replace(/^\//,"");/\.js$/.test(t)?(r.push({type:"file",value:t}),o.push(path_1.default.posix.dirname(t))):(r.push({type:"file",value:path_1.default.posix.join(t,"./game.js")}),o.push(t))}),t.openDataContext&&(r.push({type:"file",value:path_1.default.posix.join(t.openDataContext,"index.js")}),o.push(t.openDataContext)),t.workers&&r.push({type:"folder",value:t.workers}),t.plugins)for(const e in t.plugins){const a=t.plugins[e];if(a.path){const e=a.path.replace(/^\//,"");r.push({type:"folder",value:e})}}return await _getNameMapping(e,a,r,o)};async function _getNameMapping(e,t,a,r=[]){const o={},i=[];for(const e of t){let t=!1;for(const r of a)if("file"===r.type&&r.value===e||"folder"===r.type&&0===e.indexOf(r.value)||"regex"===r.type&&r.value.test(e)){t=!0;break}t||i.push(e)}const s=await(0,sign_1.getSignature)(e.privateKey,e.appid),{body:n}=await(0,request_1.request)({url:url_config_1.TRANSLATE_FILENAME,method:"post",body:JSON.stringify({appid:e.appid,signature:s,arrPaths:i}),headers:{"content-type":"application/json"}}),p=(0,jsonParse_1.jsonRespParse)(n,url_config_1.TRANSLATE_FILENAME);if(0===p.errCode)return p.body.pairs.forEach(e=>{const t=checkPrefix(e.origin,r);o[e.origin]=(0,tools_1.normalizePath)(path_1.default.posix.join(t,e.translated+".js"))}),o;throw new Error(`errCode: ${p.errCode} errMsg: ${p.errMsg}`)}async function uglifyFileNames(e,t,a){let r={miniprogramRoot:""};try{r=JSON.parse(t["project.config.json"].toString())}catch(e){}let o=(0,tools_1.normalizePath)(r.miniprogramRoot);"."===o&&(o=""),a=a||await(0,exports.getNameMapping)(e,e.miniprogramRoot);const i=Object.keys(t).filter(e=>e.endsWith(".js")),s={};for(const e of i){if(/\/miniprogram_npm\/|^miniprogram_npm\//.test(e))continue;const r=e,n=t[e].toString(),p=t[e+".map"]||"";s[r]=(0,file_flatter_1.tryTranslateSingleFile)({rootPath:o,code:n,nameMapping:a,check:!0,sourceFileName:e,sourceMap:p,filePath:e,miniProgramJSFiles:i})}const n=Object.keys(t),p={};for(const e of n){p[(0,tools_1.normalizePath)(e)]=t[e]}for(const e in s){const t=(0,tools_1.normalizePath)(e);let r=t;const i=s[e];if(i.errMsg){if(!process.env.isDevtools)throw new Error(`\n${locales_1.default.config.COULD_NOT_USE_CODE_PROTECT}\n${i.errMsg}`);(0,common_1.throwError)({code:config.FILE_FLAT_ERR,msg:`${locales_1.default.config.COULD_NOT_USE_CODE_PROTECT}\n${i.errMsg}`,filePath:t})}const n=path_1.default.posix.relative(o,e);a[n]&&(r=(0,tools_1.normalizePath)(path_1.default.posix.join(o,a[n])),delete p[t],delete p[t+".map"]),p[r]=i.translatedContent,i.translatedSourceMap&&(p[r+".map"]=i.translatedSourceMap)}return p}exports.getGameNameMapping=getGameNameMapping,exports.uglifyFileNames=uglifyFileNames;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const tslib_1=require("tslib"),locales_1=tslib_1.__importDefault(require("../../utils/locales/locales"));function getType(e){return Object.prototype.toString.call(e).toLowerCase().split(" ")[1].replace("]","")}class T{constructor(e,t,r){this.type=e,this.required=t||!1;const o=this.valueType=getType(r);if("undefined"!==o)if(r instanceof T){if("array"!==e&&"object"!==e)throw new Error("value can be instance of ValidateType only when type is object or array");this.value=r}else if("array"!==o)if("regexp"!==o)if("object"!==o){if(e!==o)throw new Error(`value should be ${e} instead of ${o}`);this.value=r}else{if("object"!==e)throw new Error(e+" could not have object value");for(const e in r)if(!(r[e]instanceof T))throw new Error(`value["${e}"] should be instance of ValidateType`);this.value=r}else{if("regexp"!==e&&"string"!==e)throw new Error(e+" could not have regexp value");this.value=r}else{if("array"===e||"object"===e||"function"===e)throw new Error(e+" could not have optional value");for(let t=0,o=r.length;t<o;t++){const o=getType(r[t]);if(o!==e)throw new Error(`value[${t}] should be ${e} instead of ${o}`)}this.value=r}}static invalidKeys(e,t){const r=[];if(e instanceof T){try{e.check(t)}catch(e){return}if("object"!==e.type||"object"!==e.valueType||"object"!==getType(t))return;const o=e.value instanceof T;for(const i in t){let n=[];if(o)n=T.invalidKeys(e.value,t[i]);else{if(!e.value.hasOwnProperty(i)){r.push(`["${i}"]`);continue}n=T.invalidKeys(e.value[i],t[i])}n&&n.forEach(e=>{r.push(`["${i}"]${e}`)})}}else for(const o in t){if(!e.hasOwnProperty(o)){r.push(`["${o}"]`);continue}const i=T.invalidKeys(e[o],t[o]);i&&i.forEach(e=>{r.push(`["${o}"]${e}`)})}if(r.length>0)return r}check(e){const t=getType(e);if(!this.required&&"undefined"===t)return;if("ignore"===this.type)return;if(t!==this.type)throw new Error(locales_1.default.config.JSON_CONTENT_SHOULD_BE.format(["",this.type]));const r=this.valueType;if("undefined"!==r){if(this.value instanceof T){if("object"===this.type){for(const t in e)try{this.value.check(e[t])}catch(e){throw new Error(`["${t}"]${e.message}`)}return}if("array"===this.type){if(0===e.length&&this.value.required)throw new Error(locales_1.default.config.SHOULD_AT_LEAST_ONE_ITEM.format(""));for(let t=0,r=e.length;t<r;t++)try{this.value.check(e[t])}catch(e){throw new Error(`[${t}]${e.message}`)}return}}if("array"!==r)if("object"!==r)if("regexp"!==r){if(this.value!==e)throw new Error(locales_1.default.config.SHOULD_EQUAL.format(["",this.value.toString()]))}else{if("string"===this.type){if(!this.value.test(e))throw new Error(locales_1.default.config.SHOULD_MATCH.format(["",this.value.toString()]));return}if("regexp"===this.type&&this.value.toString()!==e.toString())throw new Error(locales_1.default.config.SHOULD_EQUAL.format(["",this.value.toString()]))}else for(const t in this.value){const r=this.value[t];try{r.check(e[t])}catch(e){throw new Error(`["${t}"]${e.message}`)}}else{let t=!1;for(const r of this.value)if(r===e){t=!0;break}if(!t)throw new Error(locales_1.default.config.JSON_CONTENT_SHOULD_BE.format(["",this.value.join(` ${locales_1.default.config.OR} `)]))}}}}module.exports=T;
|
|
1
|
+
"use strict";const tslib_1=require("tslib"),locales_1=(0,tslib_1.__importDefault)(require("../../utils/locales/locales"));function getType(e){return Object.prototype.toString.call(e).toLowerCase().split(" ")[1].replace("]","")}class T{constructor(e,t,r){this.type=e,this.required=t||!1;const o=this.valueType=getType(r);if("undefined"!==o)if(r instanceof T){if("array"!==e&&"object"!==e)throw new Error("value can be instance of ValidateType only when type is object or array");this.value=r}else if("array"!==o)if("regexp"!==o)if("object"!==o){if(e!==o)throw new Error(`value should be ${e} instead of ${o}`);this.value=r}else{if("object"!==e)throw new Error(e+" could not have object value");for(const e in r)if(!(r[e]instanceof T))throw new Error(`value["${e}"] should be instance of ValidateType`);this.value=r}else{if("regexp"!==e&&"string"!==e)throw new Error(e+" could not have regexp value");this.value=r}else{if("array"===e||"object"===e||"function"===e)throw new Error(e+" could not have optional value");for(let t=0,o=r.length;t<o;t++){const o=getType(r[t]);if(o!==e)throw new Error(`value[${t}] should be ${e} instead of ${o}`)}this.value=r}}static invalidKeys(e,t){const r=[];if(e instanceof T){try{e.check(t)}catch(e){return}if("object"!==e.type||"object"!==e.valueType||"object"!==getType(t))return;const o=e.value instanceof T;for(const i in t){let n=[];if(o)n=T.invalidKeys(e.value,t[i]);else{if(!e.value.hasOwnProperty(i)){r.push(`["${i}"]`);continue}n=T.invalidKeys(e.value[i],t[i])}n&&n.forEach(e=>{r.push(`["${i}"]${e}`)})}}else for(const o in t){if(!e.hasOwnProperty(o)){r.push(`["${o}"]`);continue}const i=T.invalidKeys(e[o],t[o]);i&&i.forEach(e=>{r.push(`["${o}"]${e}`)})}if(r.length>0)return r}check(e){const t=getType(e);if(!this.required&&"undefined"===t)return;if("ignore"===this.type)return;if(t!==this.type)throw new Error(locales_1.default.config.JSON_CONTENT_SHOULD_BE.format(["",this.type]));const r=this.valueType;if("undefined"!==r){if(this.value instanceof T){if("object"===this.type){for(const t in e)try{this.value.check(e[t])}catch(e){throw new Error(`["${t}"]${e.message}`)}return}if("array"===this.type){if(0===e.length&&this.value.required)throw new Error(locales_1.default.config.SHOULD_AT_LEAST_ONE_ITEM.format(""));for(let t=0,r=e.length;t<r;t++)try{this.value.check(e[t])}catch(e){throw new Error(`[${t}]${e.message}`)}return}}if("array"!==r)if("object"!==r)if("regexp"!==r){if(this.value!==e)throw new Error(locales_1.default.config.SHOULD_EQUAL.format(["",this.value.toString()]))}else{if("string"===this.type){if(!this.value.test(e))throw new Error(locales_1.default.config.SHOULD_MATCH.format(["",this.value.toString()]));return}if("regexp"===this.type&&this.value.toString()!==e.toString())throw new Error(locales_1.default.config.SHOULD_EQUAL.format(["",this.value.toString()]))}else for(const t in this.value){const r=this.value[t];try{r.check(e[t])}catch(e){throw new Error(`["${t}"]${e.message}`)}}else{let t=!1;for(const r of this.value)if(r===e){t=!0;break}if(!t)throw new Error(locales_1.default.config.JSON_CONTENT_SHOULD_BE.format(["",this.value.join(` ${locales_1.default.config.OR} `)]))}}}}module.exports=T;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _a;process.env&&process.env.isDevtools&&require("../../utils/hackrequire/index"),Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");(null===(_a=process.env)||void 0===_a?void 0:_a.isDevtools)&&require("../../utils/hackrequire/index");const config_1=require("./config"),worker_manager_1=require("./worker_manager"),log_1=tslib_1.__importDefault(require("../../utils/log")),logger_1=require("../utils/logger"),workerManager=worker_manager_1.getWorkerManager(!!process.env.isDevtools);class TaskManager{constructor(){this._taskSet=new Set,this._suicideTime=config_1.SUICIDE_TIME["miniprogram-ci"],process.env.isDevtools&&(this._suicideTime=config_1.SUICIDE_TIME.devtools)}runTask(e,s,i){clearTimeout(this._suicideTimer),this._taskSet.add(e),workerManager.runTask(s,i).then(this.onResolve.bind(this,e)).catch(this.onReject.bind(this,e))}onResolve(e,s){this._taskSet.delete(e),process.send({command:config_1.COMMAND.TASK_DONE,data:{taskId:e,result:s}}),this.setUpSuicideTimer()}onReject(e,s){process.send({command:config_1.COMMAND.TASK_DONE,data:{taskId:e,result:{error:s.toString()}}}),this.setUpSuicideTimer()}setUpSuicideTimer(){this._taskSet.size>0||(this._suicideTimer=setTimeout(()=>{clearTimeout(this._suicideTimer),process.exit(0)},this._suicideTime))}}const taskManager=new TaskManager;function suicide(){try{process.exit(0),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},5e3)}catch(e){process.kill(process.pid,"SIGTERM")}}process.on("message",e=>{if("object"!=typeof e)return void log_1.default.error("child process unrecognized message "+e);const{command:s,data:i}=e;s===config_1.COMMAND.RUN_TASK?(logger_1.logger.info("child-process recieve message",s,i.filePath),taskManager.runTask(i.taskId,i.taskName,i.data)):log_1.default.error("child process unrecognized message "+e)}),process.on("disconnect",()=>{suicide()});
|
|
1
|
+
var _a;process.env&&process.env.isDevtools&&require("../../utils/hackrequire/index"),Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");(null===(_a=process.env)||void 0===_a?void 0:_a.isDevtools)&&require("../../utils/hackrequire/index");const config_1=require("./config"),worker_manager_1=require("./worker_manager"),log_1=(0,tslib_1.__importDefault)(require("../../utils/log")),logger_1=require("../utils/logger"),workerManager=(0,worker_manager_1.getWorkerManager)(!!process.env.isDevtools);class TaskManager{constructor(){this._taskSet=new Set,this._suicideTime=config_1.SUICIDE_TIME["miniprogram-ci"],process.env.isDevtools&&(this._suicideTime=config_1.SUICIDE_TIME.devtools)}runTask(e,s,i){clearTimeout(this._suicideTimer),this._taskSet.add(e),workerManager.runTask(s,i).then(this.onResolve.bind(this,e)).catch(this.onReject.bind(this,e))}onResolve(e,s){this._taskSet.delete(e),process.send({command:config_1.COMMAND.TASK_DONE,data:{taskId:e,result:s}}),this.setUpSuicideTimer()}onReject(e,s){process.send({command:config_1.COMMAND.TASK_DONE,data:{taskId:e,result:{error:s.toString()}}}),this.setUpSuicideTimer()}setUpSuicideTimer(){this._taskSet.size>0||(this._suicideTimer=setTimeout(()=>{clearTimeout(this._suicideTimer),process.exit(0)},this._suicideTime))}}const taskManager=new TaskManager;function suicide(){try{process.exit(0),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},5e3)}catch(e){process.kill(process.pid,"SIGTERM")}}process.on("message",e=>{if("object"!=typeof e)return void log_1.default.error("child process unrecognized message "+e);const{command:s,data:i}=e;s===config_1.COMMAND.RUN_TASK?(logger_1.logger.info("child-process recieve message",s,i.filePath),taskManager.runTask(i.taskId,i.taskName,i.data)):log_1.default.error("child process unrecognized message "+e)}),process.on("disconnect",()=>{suicide()});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.childProcessManager=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),child_process_1=require("child_process"),config_1=require("./config"),events_1=tslib_1.__importDefault(require("events")),log_1=tslib_1.__importDefault(require("../../utils/log")),os=tslib_1.__importStar(require("os")),logger_1=require("../utils/logger"),cpus=os.cpus().length,FORK_PATH=path_1.default.posix.join(__dirname,"./childprocess.js"),MAX_TASK_TRY_TIME=2;class ChildProcessInstance extends events_1.default{constructor(s){super(),this.status=config_1.EChildProcessStatus.free,this._lastActiveTime=0,this._taskMap={},this._fullload_task_count=4,this._suicideTime=config_1.SUICIDE_TIME["miniprogram-ci"],this._fullload_task_count=s;const e={stdio:["pipe","pipe","pipe","ipc"],env:Object.assign(Object.assign({},process.env),{cpprocessEnv:"childprocess"})};if(e.env.isDevtools=process.__nwjs&&"wechatwebdevtools"===nw.App.manifest.appname,e.env.isDevtools){this._suicideTime=config_1.SUICIDE_TIME.devtools;let s=path_1.default.join(path_1.default.dirname(process.execPath),"node");"darwin"!==process.platform&&(s+=".exe"),e.execPath=s}logger_1.logger.info("fork childprocess start");const t=child_process_1.fork(FORK_PATH,["--expose-gc"],e);t.stdout.setEncoding("utf8"),logger_1.logger.info("fork childprocess end"),t.stdout.on("data",s=>{log_1.default.log("child process stdout: "+s)}),t.stderr.on("data",s=>{log_1.default.error("child process stderr: "+s)}),t.on("message",this.onChildProcessMessage.bind(this,t)),t.on("exit",s=>{this.emit("exit",{code:s,status:this.status,tasks:Object.values(this._taskMap),pid:t.pid})}),t.unref(),this._instance=t}onChildProcessMessage(s,e){if("object"!=typeof e)return void logger_1.logger.error("unrecognized message from child process",e);const{command:t,data:i}=e;t!==config_1.COMMAND.SEND_LOG?(logger_1.logger.info("onChildProcessMessage "+t,i),t===config_1.COMMAND.TASK_DONE?this.onTaskDone(i):t===config_1.COMMAND.SEND_LOG&&logger_1.logger.send(i.level,i.args)):logger_1.logger.send(i.level,i.args)}onTaskDone(s){const{taskId:e,result:t}=s,i=this._taskMap[e];delete this._taskMap[e],i?(i.resolve&&(i.onStatusUpdate(config_1.ETaskStatus.done),i.resolve(t)),0===Object.keys(this._taskMap).length&&(this.status=config_1.EChildProcessStatus.free,this.setUpSuicideTimer()),this.emit("taskDone")):log_1.default.error(`child process task: ${e} not found`)}setUpSuicideTimer(){this._suicideTimer=setTimeout(()=>{clearTimeout(this._suicideTimer),this.status===config_1.EChildProcessStatus.free?(this.status=config_1.EChildProcessStatus.dying,this._instance.kill("SIGTERM")):this._suicideTimer||this.setUpSuicideTimer()},this._suicideTime)}runTask(s){clearTimeout(this._suicideTimer),this.status=config_1.EChildProcessStatus.busy,this._lastActiveTime=Date.now();const e=getId();this._taskMap[e]=s,Object.keys(this._taskMap).length>=this._fullload_task_count?this.status=config_1.EChildProcessStatus.fullload:this.status=config_1.EChildProcessStatus.busy,s.onStatusUpdate(config_1.ETaskStatus.progress),this._instance.send({command:config_1.COMMAND.RUN_TASK,data:{taskId:e,taskName:s.name,data:s.data}})}}const getId=(()=>{let s=0;return()=>s++})();class TaskManager{constructor(){this._taskQueue=[],this.onChildProcessExit=s=>{const{code:e,status:t,tasks:i,pid:o}=s;if(this._instance=void 0,t===config_1.EChildProcessStatus.busy||t===config_1.EChildProcessStatus.fullload)for(const s of i)s.retryTimes+=1,s.retryTimes<=2?(log_1.default.error(`child process: ${o} exit with code: ${e} when it is busy, retry ${s.retryTimes} times`),this._taskQueue.push(s)):s.reject(`child process exit with code: ${e} when it is busy`);this._run()},this.onTaskDone=()=>{this._run()}}runTask(s,e,t=(()=>{})){return new Promise((i,o)=>{const r={name:s,data:e,resolve:i,reject:o,retryTimes:0,onStatusUpdate:t};t(config_1.ETaskStatus.waiting),this._taskQueue.push(r),this._run()})}_run(){if(0===this._taskQueue.length)return;const s=this.allocChildProcess();s.status!==config_1.EChildProcessStatus.fullload&&s.status!==config_1.EChildProcessStatus.dying&&(s.runTask(this._taskQueue.shift()),this._run())}allocChildProcess(){return this._instance||(this._instance=new ChildProcessInstance(2*cpus),this._instance.on("exit",this.onChildProcessExit),this._instance.on("taskDone",this.onTaskDone)),this._instance}}exports.childProcessManager=new TaskManager;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.childProcessManager=void 0;const tslib_1=require("tslib"),path_1=(0,tslib_1.__importDefault)(require("path")),child_process_1=require("child_process"),config_1=require("./config"),events_1=(0,tslib_1.__importDefault)(require("events")),log_1=(0,tslib_1.__importDefault)(require("../../utils/log")),os=(0,tslib_1.__importStar)(require("os")),logger_1=require("../utils/logger"),cpus=os.cpus().length,FORK_PATH=path_1.default.posix.join(__dirname,"./childprocess.js"),MAX_TASK_TRY_TIME=2;class ChildProcessInstance extends events_1.default{constructor(s){super(),this.status=config_1.EChildProcessStatus.free,this._lastActiveTime=0,this._taskMap={},this._fullload_task_count=4,this._suicideTime=config_1.SUICIDE_TIME["miniprogram-ci"],this._fullload_task_count=s;const e={stdio:["pipe","pipe","pipe","ipc"],env:Object.assign(Object.assign({},process.env),{cpprocessEnv:"childprocess"})};if(e.env.isDevtools=process.__nwjs&&"wechatwebdevtools"===nw.App.manifest.appname,e.env.isDevtools){this._suicideTime=config_1.SUICIDE_TIME.devtools;let s=path_1.default.join(path_1.default.dirname(process.execPath),"node");"darwin"!==process.platform&&(s+=".exe"),e.execPath=s}logger_1.logger.info("fork childprocess start");const t=(0,child_process_1.fork)(FORK_PATH,["--expose-gc"],e);t.stdout.setEncoding("utf8"),logger_1.logger.info("fork childprocess end"),t.stdout.on("data",s=>{log_1.default.log("child process stdout: "+s)}),t.stderr.on("data",s=>{log_1.default.error("child process stderr: "+s)}),t.on("message",this.onChildProcessMessage.bind(this,t)),t.on("exit",s=>{this.emit("exit",{code:s,status:this.status,tasks:Object.values(this._taskMap),pid:t.pid})}),t.unref(),this._instance=t}onChildProcessMessage(s,e){if("object"!=typeof e)return void logger_1.logger.error("unrecognized message from child process",e);const{command:t,data:i}=e;t!==config_1.COMMAND.SEND_LOG?(logger_1.logger.info("onChildProcessMessage "+t,i),t===config_1.COMMAND.TASK_DONE?this.onTaskDone(i):t===config_1.COMMAND.SEND_LOG&&logger_1.logger.send(i.level,i.args)):logger_1.logger.send(i.level,i.args)}onTaskDone(s){const{taskId:e,result:t}=s,i=this._taskMap[e];delete this._taskMap[e],i?(i.resolve&&(i.onStatusUpdate(config_1.ETaskStatus.done),i.resolve(t)),0===Object.keys(this._taskMap).length&&(this.status=config_1.EChildProcessStatus.free,this.setUpSuicideTimer()),this.emit("taskDone")):log_1.default.error(`child process task: ${e} not found`)}setUpSuicideTimer(){this._suicideTimer=setTimeout(()=>{clearTimeout(this._suicideTimer),this.status===config_1.EChildProcessStatus.free?(this.status=config_1.EChildProcessStatus.dying,this._instance.kill("SIGTERM")):this._suicideTimer||this.setUpSuicideTimer()},this._suicideTime)}runTask(s){clearTimeout(this._suicideTimer),this.status=config_1.EChildProcessStatus.busy,this._lastActiveTime=Date.now();const e=getId();this._taskMap[e]=s,Object.keys(this._taskMap).length>=this._fullload_task_count?this.status=config_1.EChildProcessStatus.fullload:this.status=config_1.EChildProcessStatus.busy,s.onStatusUpdate(config_1.ETaskStatus.progress),this._instance.send({command:config_1.COMMAND.RUN_TASK,data:{taskId:e,taskName:s.name,data:s.data}})}}const getId=(()=>{let s=0;return()=>s++})();class TaskManager{constructor(){this._taskQueue=[],this.onChildProcessExit=s=>{const{code:e,status:t,tasks:i,pid:o}=s;if(this._instance=void 0,t===config_1.EChildProcessStatus.busy||t===config_1.EChildProcessStatus.fullload)for(const s of i)s.retryTimes+=1,s.retryTimes<=2?(log_1.default.error(`child process: ${o} exit with code: ${e} when it is busy, retry ${s.retryTimes} times`),this._taskQueue.push(s)):s.reject(`child process exit with code: ${e} when it is busy`);this._run()},this.onTaskDone=()=>{this._run()}}runTask(s,e,t=(()=>{})){return new Promise((i,o)=>{const r={name:s,data:e,resolve:i,reject:o,retryTimes:0,onStatusUpdate:t};t(config_1.ETaskStatus.waiting),this._taskQueue.push(r),this._run()})}_run(){if(0===this._taskQueue.length)return;const s=this.allocChildProcess();s.status!==config_1.EChildProcessStatus.fullload&&s.status!==config_1.EChildProcessStatus.dying&&(s.runTask(this._taskQueue.shift()),this._run())}allocChildProcess(){return this._instance||(this._instance=new ChildProcessInstance(2*cpus),this._instance.on("exit",this.onChildProcessExit),this._instance.on("taskDone",this.onTaskDone)),this._instance}}exports.childProcessManager=new TaskManager;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib"),index_1=tslib_1.__importDefault(require("./task/index")),config_1=require("./config"),log_1=tslib_1.__importDefault(require("../../utils/log"));let isbusy=!1;process.on("message",e=>{const{command:s,data:i}=e;s===config_1.COMMAND.RUN_TASK&&(isbusy=!0,index_1.default(i.taskName,i.data).then(e=>{isbusy=!1,process.send({command:config_1.COMMAND.TASK_DONE,data:e})}).catch(e=>{isbusy=!1,process.send({command:config_1.COMMAND.TASK_DONE,data:{error:e.toString()}})}))}),process.on("SIGTERM",()=>{isbusy&&(log_1.default.error("forked sub process is kill when busy"),process.exit(1)),process.exit(0)});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib"),index_1=(0,tslib_1.__importDefault)(require("./task/index")),config_1=require("./config"),log_1=(0,tslib_1.__importDefault)(require("../../utils/log"));let isbusy=!1;process.on("message",e=>{const{command:s,data:i}=e;s===config_1.COMMAND.RUN_TASK&&(isbusy=!0,(0,index_1.default)(i.taskName,i.data).then(e=>{isbusy=!1,process.send({command:config_1.COMMAND.TASK_DONE,data:e})}).catch(e=>{isbusy=!1,process.send({command:config_1.COMMAND.TASK_DONE,data:{error:e.toString()}})}))}),process.on("SIGTERM",()=>{isbusy&&(log_1.default.error("forked sub process is kill when busy"),process.exit(1)),process.exit(0)});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.abortTask=exports.runTask=void 0;const tslib_1=require("tslib"),worker_manager_1=require("./worker_manager"),childprocess_manager_1=require("./childprocess_manager"),index_1=tslib_1.__importDefault(require("./task/index")),log_1=tslib_1.__importDefault(require("../../utils/log")),logger_1=require("../utils/logger");tslib_1.__exportStar(require("./config"),exports);const isDevtools=void 0!==process.env.__nwjs;async function runTask(r,e,a=(()=>{})){if(logger_1.logger.info("runTask",r,e.filePath),global.__MINIPROGRAM_CI_TEST__)return
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.abortTask=exports.runTask=void 0;const tslib_1=require("tslib"),worker_manager_1=require("./worker_manager"),childprocess_manager_1=require("./childprocess_manager"),index_1=(0,tslib_1.__importDefault)(require("./task/index")),log_1=(0,tslib_1.__importDefault)(require("../../utils/log")),logger_1=require("../utils/logger");(0,tslib_1.__exportStar)(require("./config"),exports);const isDevtools=void 0!==process.env.__nwjs;async function runTask(r,e,a=(()=>{})){if(logger_1.logger.info("runTask",r,e.filePath),global.__MINIPROGRAM_CI_TEST__)return(0,index_1.default)(r,e);try{if(process.__nwjs&&"wechatwebdevtools"===nw.App.manifest.appname)return await childprocess_manager_1.childProcessManager.runTask(r,e,a);const o=(0,worker_manager_1.getWorkerManager)(isDevtools);return await o.runTask(r,e,a)}catch(a){if(a===worker_manager_1.AbortEvent)throw a;return log_1.default.error("runTask catch error "+a),(0,index_1.default)(r,e)}}function abortTask(r){(0,worker_manager_1.getWorkerManager)(isDevtools).abort(r)}exports.runTask=runTask,exports.abortTask=abortTask;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.call=void 0;const tslib_1=require("tslib"),config_1=require("../config"),FUNC=tslib_1.__importStar(require("./func"));let workerThreads,supportWorkerThread=!1;try{workerThreads=require("worker_threads"),supportWorkerThread=!0}catch(r){supportWorkerThread=!1}const callMainThread=function(){if(!supportWorkerThread||workerThreads.isMainThread)return(r,e)=>{};let r=0;const e={};return workerThreads.parentPort.on("message",r=>{const{command:o,data:t}=r;if(o!==config_1.COMMAND.CALL_FUNC_RESULT)return;const{id:a,result:s,error:n}=t,i=e[a];return delete e[a],i?n?i.reject(n):void i.resolve(s):void 0}),(o,t)=>new Promise((a,s)=>{const n=r++;e[n]={resolve:a,reject:s},workerThreads.parentPort.postMessage({command:config_1.COMMAND.CALL_FUNC,data:{id:n,funcName:o,args:t}})})}();function call(r,...e){return!supportWorkerThread||workerThreads.isMainThread?FUNC[r].apply(null,e):callMainThread(r,e)}exports.call=call;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.call=void 0;const tslib_1=require("tslib"),config_1=require("../config"),FUNC=(0,tslib_1.__importStar)(require("./func"));let workerThreads,supportWorkerThread=!1;try{workerThreads=require("worker_threads"),supportWorkerThread=!0}catch(r){supportWorkerThread=!1}const callMainThread=function(){if(!supportWorkerThread||workerThreads.isMainThread)return(r,e)=>{};let r=0;const e={};return workerThreads.parentPort.on("message",r=>{const{command:o,data:t}=r;if(o!==config_1.COMMAND.CALL_FUNC_RESULT)return;const{id:a,result:s,error:n}=t,i=e[a];return delete e[a],i?n?i.reject(n):void i.resolve(s):void 0}),(o,t)=>new Promise((a,s)=>{const n=r++;e[n]={resolve:a,reject:s},workerThreads.parentPort.postMessage({command:config_1.COMMAND.CALL_FUNC,data:{id:n,funcName:o,args:t}})})}();function call(r,...e){return!supportWorkerThread||workerThreads.isMainThread?FUNC[r].apply(null,e):callMainThread(r,e)}exports.call=call;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const tslib_1=require("tslib"),fs_1=tslib_1.__importDefault(require("fs")),path_1=tslib_1.__importDefault(require("path")),locales_1=tslib_1.__importDefault(require("../../../utils/locales/locales")),tools_1=require("../../../utils/tools"),config_1=require("../../../config"),call_func_1=require("./call_func"),log_1=tslib_1.__importDefault(require("../../../utils/log")),babel_helper_1=require("../../../utils/babel_helper"),jsonParse_1=require("../../../utils/jsonParse"),sourcemap=()=>require("source-map"),enhanceCompile=()=>require("../../js/enhance"),es6Compile=()=>require("../../js/es6_transform"),minifyJS=()=>require("../../js/minifyjs"),minifyJSAfterWrap=()=>require("../../js/minifyjs_after_wrap"),MAX_CODE_LENGTH=512e3;async function tryGetInputSourceMap(e,r){try{const t=/\/\/[#|@] sourceMappingURL=[\s]*(\S*)[\s]*$/m.exec(e),s=path_1.default.posix.dirname(r),o=path_1.default.posix.basename(r);let i;if(null==t?void 0:t[1])if(/\.js\.map$/.test(t[1]))i=await
|
|
1
|
+
"use strict";const tslib_1=require("tslib"),fs_1=(0,tslib_1.__importDefault)(require("fs")),path_1=(0,tslib_1.__importDefault)(require("path")),locales_1=(0,tslib_1.__importDefault)(require("../../../utils/locales/locales")),tools_1=require("../../../utils/tools"),config_1=require("../../../config"),call_func_1=require("./call_func"),log_1=(0,tslib_1.__importDefault)(require("../../../utils/log")),babel_helper_1=require("../../../utils/babel_helper"),jsonParse_1=require("../../../utils/jsonParse"),sourcemap=()=>require("source-map"),enhanceCompile=()=>require("../../js/enhance"),es6Compile=()=>require("../../js/es6_transform"),minifyJS=()=>require("../../js/minifyjs"),minifyJSAfterWrap=()=>require("../../js/minifyjs_after_wrap"),generateMap=()=>require("../../js/generateMap"),MAX_CODE_LENGTH=512e3;async function tryGetInputSourceMap(e,r){try{const t=/\/\/[#|@] sourceMappingURL=[\s]*(\S*)[\s]*$/m.exec(e),s=path_1.default.posix.dirname(r),o=path_1.default.posix.basename(r);let i;if(null==t?void 0:t[1])if(/\.js\.map$/.test(t[1]))i=await(0,call_func_1.call)("readFileAsync",path_1.default.posix.join(s,t[1]),"utf-8");else{const e=t[1].split("base64,")[1];i=Buffer.from(e,"base64").toString()}else{const e=path_1.default.posix.join(s,o+".map");fs_1.default.existsSync(e)&&(i=await(0,call_func_1.call)("readFileAsync",e,"utf-8"))}if(i){const e=(0,jsonParse_1.jsonParse)(i);new(require("source-map").SourceMapConsumer)(e);return await insertSourcesContent(e,r),e}}catch(e){log_1.default.log(`try to get input sourcemap of ${r} catch error ${e}`)}}const insertSourcesContent=async(e,r)=>{if(Array.isArray(e.sources)&&!Array.isArray(e.sourcesContent)){const t=e.sourcesContent;try{const t=path_1.default.posix.dirname(r),s=[],o=e.sources;for(const e of o){const r=await(0,call_func_1.call)("readFileAsync",path_1.default.posix.join(t,e),"utf-8");s.push(r)}e.sourcesContent=s}catch(r){e.sourcesContent=t}}};async function compileJS(e){const{code:r,filePath:t,projectPath:s,setting:o,babelRoot:i="@babel/runtime",root:a="",babelIgnore:n=[]}=e,{es7:c,es6:l,disableUseStrict:u}=o,f="string"==typeof r?r:(0,tools_1.bufferToUtf8String)(Buffer.from(r)),p=path_1.default.posix.join(a,t),_=o.minify||o.minifyJS;if(void 0===f)return{error:{code:config_1.FILE_NOT_UTF8,path:p,message:locales_1.default.config.FILE_NOT_UTF8.format(p)}};const m=f.length>=512e3;let g=!1;c&&(g=(0,babel_helper_1.isIgnore)(n,t));const b=await tryGetInputSourceMap(f,path_1.default.posix.join(s,a,t));if(m||g)return{error:null,isLargeFile:m,isBabelIgnore:g,map:"object"==typeof b?JSON.stringify(b):b,code:f,helpers:[]};let h=f,d=b,j=[];if(c){const e=await require("../../js/enhance")({code:f,babelRoot:i,filePath:t,disableUseStrict:u,inputSourceMap:b});if(e.error)return{error:Object.assign(Object.assign({},e.error),{path:p})};h=e.code||"",d=e.map,j=e.helpers||[]}else if(l){const e=require("../../js/es6_transform")({code:f,filePath:t,inputSourceMap:b});if(e.error)return{error:Object.assign(Object.assign({},e.error),{path:p})};h=e.code||"",d=e.map}if(_){if(!l&&!c){const e=require("../../js/minifyjs_after_wrap")({filePath:t,code:h,inputSourceMap:d});if(e.error)return{error:Object.assign(Object.assign({},e.error),{path:p})};h=e.code,d=e.map}else{const e=require("../../js/minifyjs")({filePath:t,code:h,useTerser:!!c,inputSourceMap:d});if(e.error)return{error:Object.assign(Object.assign({},e.error),{path:p})};h=e.code,d=e.map}}if(void 0===d&&(d=require("../../js/generateMap")(t,h)),"string"!=typeof d)try{(null==d?void 0:d.sourcesContent)&&(d.sourcesContent=d.sourcesContent.map(e=>e.replace(/\r\n/g,"\n"))),d=JSON.stringify(d)}catch(e){d=""}else d=d.replace(/\\r\\n/g,"\\n");return{error:null,isLargeFile:m,isBabelIgnore:g,map:d,code:h.replace(/\r\n/g,"\n"),helpers:j||[]}}module.exports=compileJS;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),postcss_1=tslib_1.__importDefault(require("postcss")),autoprefixer_1=tslib_1.__importDefault(require("autoprefixer")),cssnano_1=tslib_1.__importDefault(require("cssnano")),locales_1=tslib_1.__importDefault(require("../../../utils/locales/locales")),tools_1=require("../../../utils/tools"),config_1=require("../../../config"),log_1=tslib_1.__importDefault(require("../../../utils/log")),wxssBrowser=["iOS >= 8","Chrome >= 37"];async function compileWXSS(e){const{code:r,filePath:o,setting:s={},root:t=""}=e,i=Buffer.from(r),l=tools_1.bufferToUtf8String(i),{minify:a,minifyWXSS:u,autoPrefixWXSS:_}=s,c=path_1.default.posix.join(t,o),f=a&&!1!==u||u;if(void 0===l)return{error:{code:config_1.FILE_NOT_UTF8,path:c,message:locales_1.default.config.FILE_NOT_UTF8.format(c)}};if(f||_)try{const e=[];_&&e.push(autoprefixer_1.default({overrideBrowserslist:wxssBrowser,remove:!1})),f&&e.push(cssnano_1.default({preset:["default",{reduceTransforms:!1,calc:!1,minifySelectors:!1,normalizeUrl:!1}]}));return{error:null,code:(await
|
|
1
|
+
"use strict";const tslib_1=require("tslib"),path_1=(0,tslib_1.__importDefault)(require("path")),postcss_1=(0,tslib_1.__importDefault)(require("postcss")),autoprefixer_1=(0,tslib_1.__importDefault)(require("autoprefixer")),cssnano_1=(0,tslib_1.__importDefault)(require("cssnano")),locales_1=(0,tslib_1.__importDefault)(require("../../../utils/locales/locales")),tools_1=require("../../../utils/tools"),config_1=require("../../../config"),log_1=(0,tslib_1.__importDefault)(require("../../../utils/log")),wxssBrowser=["iOS >= 8","Chrome >= 37"];async function compileWXSS(e){const{code:r,filePath:o,setting:s={},root:t=""}=e,i=Buffer.from(r),l=(0,tools_1.bufferToUtf8String)(i),{minify:a,minifyWXSS:u,autoPrefixWXSS:_}=s,c=path_1.default.posix.join(t,o),f=a&&!1!==u||u;if(void 0===l)return{error:{code:config_1.FILE_NOT_UTF8,path:c,message:locales_1.default.config.FILE_NOT_UTF8.format(c)}};if(f||_)try{const e=[];_&&e.push((0,autoprefixer_1.default)({overrideBrowserslist:wxssBrowser,remove:!1})),f&&e.push((0,cssnano_1.default)({preset:["default",{reduceTransforms:!1,calc:!1,minifySelectors:!1,normalizeUrl:!1}]}));return{error:null,code:(await(0,postcss_1.default)(e).process(l,{from:(0,tools_1.leading)(o,"/")})).css.replace(/\r\n/g,"\n")}}catch(e){return log_1.default.error("postcss error @ "+c),log_1.default.error(e),{error:{code:config_1.POST_WXSS_ERR,path:c,message:e.message}}}return{error:null,code:l.replace(/\r\n/g,"\n")}}process.env.BROWSERSLIST=process.env.BROWSERSLIST||"iOS >= 8, Chrome >= 37",module.exports=compileWXSS;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.readFileAsync=void 0;const tslib_1=require("tslib"),fs_1=tslib_1.__importDefault(require("fs"));function readFileAsync(e,r){return new Promise((s,i)=>{fs_1.default.readFile(e,r,(e,r)=>{if(e)return i(e);s(r)})})}exports.readFileAsync=readFileAsync;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.readFileAsync=void 0;const tslib_1=require("tslib"),fs_1=(0,tslib_1.__importDefault)(require("fs"));function readFileAsync(e,r){return new Promise((s,i)=>{fs_1.default.readFile(e,r,(e,r)=>{if(e)return i(e);s(r)})})}exports.readFileAsync=readFileAsync;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const tslib_1=require("tslib"),tools_1=require("../../../utils/tools"),path_1=tslib_1.__importDefault(require("path")),log_1=tslib_1.__importDefault(require("../../../utils/log")),config_1=require("../../../config"),locales_1=tslib_1.__importDefault(require("../../../utils/locales/locales"));function getCharCode(T){return T.charCodeAt(0)>=STATE.OTHERS?STATE.OTHERS:T.charCodeAt(0)}var TokenType,STATE,ACTION;!function(T){T[T.ATTR=0]="ATTR",T[T.STRING1=1]="STRING1",T[T.STRING2=2]="STRING2",T[T.OTHERS=3]="OTHERS"}(TokenType||(TokenType={})),function(T){T[T.ERROR=-1]="ERROR",T[T.NOT_SET=0]="NOT_SET",T[T.SIMPLE=1]="SIMPLE",T[T.TAG_START=2]="TAG_START",T[T.IN_TAG=3]="IN_TAG",T[T.IN_TAG_WORD=4]="IN_TAG_WORD",T[T.IN_STRING=5]="IN_STRING",T[T.IN_STRING_ESCAPE=6]="IN_STRING_ESCAPE",T[T.TAG_EQ=7]="TAG_EQ",T[T.IN_STRING2=9]="IN_STRING2",T[T.IN_STRING2_ESCAPE=10]="IN_STRING2_ESCAPE",T[T.IN_TEMPLATE_STRING=11]="IN_TEMPLATE_STRING",T[T.IN_TEMPLATE_STRING_ESCAPE=12]="IN_TEMPLATE_STRING_ESCAPE",T[T.IN_TEMPLATE_STRING2=13]="IN_TEMPLATE_STRING2",T[T.IN_TEMPLATE_STRING2_ESCAPE=14]="IN_TEMPLATE_STRING2_ESCAPE",T[T.WAIT_TEMPLATE_START=15]="WAIT_TEMPLATE_START",T[T.IN_TEMPLATE=16]="IN_TEMPLATE",T[T.WAIT_TEMPLATE_END=17]="WAIT_TEMPLATE_END",T[T.WAIT_FOR_RIGHT_BRACKET=18]="WAIT_FOR_RIGHT_BRACKET",T[T.IN_COMMENT=19]="IN_COMMENT",T[T.WAIT_FOR_COMMENT_END1=20]="WAIT_FOR_COMMENT_END1",T[T.WAIT_FOR_COMMENT_END2=21]="WAIT_FOR_COMMENT_END2",T[T.IN_COMMENT_BEGIN1=33]="IN_COMMENT_BEGIN1",T[T.IN_COMMENT_BEGIN2=34]="IN_COMMENT_BEGIN2",T[T.WXS_BEGIN_STEP1=22]="WXS_BEGIN_STEP1",T[T.WXS_BEGIN_STEP2=23]="WXS_BEGIN_STEP2",T[T.WXS_BEGIN_STEP3=24]="WXS_BEGIN_STEP3",T[T.WXS_BEGIN_STEP4=25]="WXS_BEGIN_STEP4",T[T.WXS_END_STEP1=26]="WXS_END_STEP1",T[T.WXS_END_STEP2=27]="WXS_END_STEP2",T[T.WXS_END_STEP3=28]="WXS_END_STEP3",T[T.WXS_END_STEP4=29]="WXS_END_STEP4",T[T.WXS_END_STEP5=30]="WXS_END_STEP5",T[T.IN_WXS=31]="IN_WXS",T[T.WXS_BEGIN_WAIT_FOR_RIGHT_BRACKET=32]="WXS_BEGIN_WAIT_FOR_RIGHT_BRACKET",T[T.SIMPLE_LINE_BREAK_BEGIN1=35]="SIMPLE_LINE_BREAK_BEGIN1",T[T.SIMPLE_LINE_BREAK_BEGIN2=36]="SIMPLE_LINE_BREAK_BEGIN2",T[T.SIMPLE_SPACE_OR_TAB=37]="SIMPLE_SPACE_OR_TAB",T[T.TEXT_BEGIN_STEP1=38]="TEXT_BEGIN_STEP1",T[T.TEXT_BEGIN_STEP2=39]="TEXT_BEGIN_STEP2",T[T.TEXT_BEGIN_STEP3=40]="TEXT_BEGIN_STEP3",T[T.TEXT_BEGIN_STEP4=41]="TEXT_BEGIN_STEP4",T[T.TEXT_BEGIN_STEP5=42]="TEXT_BEGIN_STEP5",T[T.TEXT_END_STEP1=43]="TEXT_END_STEP1",T[T.TEXT_END_STEP2=44]="TEXT_END_STEP2",T[T.TEXT_END_STEP3=45]="TEXT_END_STEP3",T[T.TEXT_END_STEP4=46]="TEXT_END_STEP4",T[T.TEXT_END_STEP5=47]="TEXT_END_STEP5",T[T.TEXT_END_STEP6=48]="TEXT_END_STEP6",T[T.IN_TEXT=49]="IN_TEXT",T[T.TEXT_BEGIN_WAIT_FOR_RIGHT_BRACKET=50]="TEXT_BEGIN_WAIT_FOR_RIGHT_BRACKET",T[T.END=99]="END",T[T.OTHERS=256]="OTHERS"}(STATE||(STATE={})),function(T){T[T.NOTHING=0]="NOTHING",T[T.DO_ACTION=65536]="DO_ACTION",T[T.STORE_TOKEN_EXCLUDE=131072]="STORE_TOKEN_EXCLUDE",T[T.STORE_TOKEN_INCLUDE=262144]="STORE_TOKEN_INCLUDE",T[T.IGNORE=524288]="IGNORE",T[T.REFEED=1048576]="REFEED",T[T.STORE_TOKEN_FIRST=2097152]="STORE_TOKEN_FIRST",T[T.STORE_ONE_SPACE=4194304]="STORE_ONE_SPACE",T[T.STORE_ONE_LINE_BREAK=8388608]="STORE_ONE_LINE_BREAK",T[T.GET_WHITECHARS_BEFORE=16777216]="GET_WHITECHARS_BEFORE",T[T.STORE_STATE_BEFORE_COMMENT=33554432]="STORE_STATE_BEFORE_COMMENT",T[T.SET_WXS_STATE=67108864]="SET_WXS_STATE",T[T.WXS_BACK=134217728]="WXS_BACK",T[T.SET_TEXT_STATE=268435456]="SET_TEXT_STATE",T[T.TEXT_BACK=536870912]="TEXT_BACK"}(ACTION||(ACTION={}));class Token{constructor(T,E){this.type=T,this.value=E}}class MachineState{constructor(){this.cur_pos=0,this.last_pos=0,this.line=1,this.col=1,this.last_line=this.line,this.last_col=1,this.state=STATE.SIMPLE}}class Machine{constructor(T,E){this.mState=new MachineState,this.TT=new Array(1024);for(let T=0;T<1024;T++){let E=new Array(257);this.TT[T]=E}this.InitTransitTable(),this.mPath=T,this.mSrc=E,this.stateBeforeComment=STATE.SIMPLE,this.wxsState=!1,this.textState=!1}Reset(){return this.mState.cur_pos=this.mState.last_pos=0,this.mState.line=1,this.mState.col=1,this.mState.last_line=this.mState.line,this.mState.last_col=1,this.mState.state=STATE.SIMPLE,0}Feed(T,E){let _,S,t,A,N;"\n"===T&&(this.mState.line++,this.mState.col=0);do{if(N=!1,void 0!==_&&_&ACTION.REFEED&&(N=!0),_=this.TT[this.mState.state][getCharCode(T)],_===STATE.NOT_SET&&(_=this.TT[this.mState.state][STATE.OTHERS]),_===STATE.NOT_SET)throw{msg:`BAD STATE MACHINE! AT INPUT ${this.mState.state} ${T}`};if(_<0)throw"\0"!==T?{msg:`${this.mState.line}:${this.mState.col}:unexpected character \`${T.replace("\n","\\n")}\``}:{msg:`${this.mState.line}:${this.mState.col}:unexpected end`};if(S=_,t=65535&_,A=this.mState.state,S&ACTION.STORE_STATE_BEFORE_COMMENT&&!N&&(this.stateBeforeComment=A),A===STATE.WAIT_FOR_RIGHT_BRACKET&&">"===T&&this.wxsState&&(this.wxsState=!1),A===STATE.WAIT_FOR_RIGHT_BRACKET&&">"===T&&this.textState&&(this.textState=!1),S&ACTION.SET_WXS_STATE&&(this.wxsState=!this.wxsState),S&ACTION.SET_TEXT_STATE&&(this.textState=!this.textState),">"===T&&t===STATE.SIMPLE&&this.wxsState&&(t=STATE.IN_WXS),">"===T&&t===STATE.SIMPLE&&this.textState&&(t=STATE.IN_TEXT),this.mState.state=t,S&ACTION.STORE_TOKEN_FIRST&&this.mState.cur_pos>this.mState.last_pos){let T=new Token(TokenType.OTHERS,this.mSrc.substring(this.mState.last_pos,this.mState.last_pos+1));E.push(T),this.mState.last_pos++,this.mState.last_col++}if(S&ACTION.STORE_ONE_LINE_BREAK){let T=new Token(TokenType.OTHERS,"\n");E.push(T),this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col,this.mState.last_line=this.mState.line}if(S&ACTION.STORE_ONE_SPACE){let T=new Token(TokenType.OTHERS," ");E.push(T),this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col,this.mState.last_line=this.mState.line}}while(_&ACTION.REFEED);if(S&ACTION.STORE_TOKEN_EXCLUDE){let T=this.mState.cur_pos,_=this.mState.last_pos;if(T>_){let S;S=A===STATE.IN_TAG_WORD&&_>0&&" \n\t\r".includes(this.mSrc[_-1])?new Token(TokenType.ATTR,this.mSrc.substring(_,T)):(this.wxsState&&STATE.IN_WXS,new Token(TokenType.OTHERS,this.mSrc.substring(_,T))),E.push(S),this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col,this.mState.last_line=this.mState.line}}if(S&ACTION.WXS_BACK){let T=new Token(TokenType.OTHERS,this.mSrc.substring(this.mState.last_pos,this.mState.cur_pos-4));E.push(T),this.mState.last_pos=this.mState.cur_pos-4,this.mState.last_col=this.mState.col-4,this.mState.last_line=this.mState.line}if(S&ACTION.TEXT_BACK){let T=new Token(TokenType.OTHERS,this.mSrc.substring(this.mState.last_pos,this.mState.cur_pos-5));E.push(T),this.mState.last_pos=this.mState.cur_pos-5,this.mState.last_col=this.mState.col-5,this.mState.last_line=this.mState.line}if(this.mState.cur_pos++,this.mState.col++,S&ACTION.STORE_TOKEN_INCLUDE){let T;T=A===STATE.IN_STRING?TokenType.STRING1:A===STATE.IN_STRING2?TokenType.STRING2:TokenType.OTHERS;let _=new Token(T,this.mSrc.substring(this.mState.last_pos,this.mState.cur_pos));E.push(_),this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col,this.mState.last_line=this.mState.line}return S&ACTION.IGNORE&&(this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col),S&ACTION.GET_WHITECHARS_BEFORE&&(this.mState.state=this.stateBeforeComment,this.stateBeforeComment!==STATE.SIMPLE_LINE_BREAK_BEGIN2&&this.stateBeforeComment!==STATE.SIMPLE_SPACE_OR_TAB||E.pop(),this.stateBeforeComment=STATE.SIMPLE),0}FillTT(T,E,_,S){for(let t of S)this.TT[T][getCharCode(t)]=E|_}FillTT_template_string(T,E){let _=T+1;this.TT[T][getCharCode("\\")]=_,this.TT[_][STATE.OTHERS]=T,this.TT[T][getCharCode(E)]=STATE.IN_TEMPLATE,this.TT[T][0]=STATE.ERROR,this.TT[T][STATE.OTHERS]=T}FillTT_string(T,E){let _=T+1;this.TT[T][getCharCode("\\")]=_,this.TT[T][getCharCode("\n")]=STATE.ERROR,this.TT[_][STATE.OTHERS]=T,this.TT[_][getCharCode("\n")]=STATE.IN_TAG|ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE,this.TT[T][getCharCode(E)]=STATE.IN_TAG|ACTION.STORE_TOKEN_INCLUDE,this.TT[T][0]=STATE.ERROR,this.TT[T][STATE.OTHERS]=T}InitTransitTable(){for(let T=0;T<1024;T++)this.TT[T].fill(0);let T="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-:";this.TT[STATE.END][STATE.OTHERS]=STATE.END,this.TT[STATE.SIMPLE][getCharCode("<")]=STATE.TAG_START|ACTION.STORE_TOKEN_EXCLUDE|ACTION.STORE_STATE_BEFORE_COMMENT,this.TT[STATE.SIMPLE][getCharCode("{")]=STATE.WAIT_TEMPLATE_START,this.TT[STATE.SIMPLE][STATE.OTHERS]=STATE.SIMPLE,this.TT[STATE.SIMPLE][0]=STATE.END|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.WAIT_TEMPLATE_START][getCharCode("{")]=STATE.IN_TEMPLATE,this.TT[STATE.WAIT_TEMPLATE_START][STATE.OTHERS]=STATE.SIMPLE,this.TT[STATE.IN_TEMPLATE][getCharCode("}")]=STATE.WAIT_TEMPLATE_END,this.TT[STATE.IN_TEMPLATE][0]=STATE.ERROR,this.TT[STATE.IN_TEMPLATE][STATE.OTHERS]=STATE.IN_TEMPLATE,this.TT[STATE.WAIT_TEMPLATE_END][getCharCode("}")]=STATE.SIMPLE,this.TT[STATE.WAIT_TEMPLATE_END][STATE.OTHERS]=STATE.IN_TEMPLATE|ACTION.REFEED,this.TT[STATE.IN_TEMPLATE][getCharCode('"')]=STATE.IN_TEMPLATE_STRING,this.TT[STATE.IN_TEMPLATE][getCharCode("'")]=STATE.IN_TEMPLATE_STRING2,this.FillTT_template_string(STATE.IN_TEMPLATE_STRING,'"'),this.FillTT_template_string(STATE.IN_TEMPLATE_STRING2,"'"),this.FillTT(STATE.TAG_START,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.FillTT(STATE.TAG_START,STATE.IN_TAG_WORD,ACTION.STORE_TOKEN_EXCLUDE,T),this.TT[STATE.TAG_START][getCharCode("/")]=STATE.IN_TAG|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.TAG_START][getCharCode("!")]=STATE.IN_COMMENT_BEGIN1,this.TT[STATE.TAG_START][STATE.OTHERS]=STATE.ERROR,this.TT[STATE.IN_COMMENT_BEGIN1][getCharCode("-")]=STATE.IN_COMMENT_BEGIN2,this.TT[STATE.IN_COMMENT_BEGIN1][STATE.OTHERS]=STATE.ERROR,this.TT[STATE.IN_COMMENT_BEGIN2][getCharCode("-")]=STATE.IN_COMMENT,this.TT[STATE.IN_COMMENT_BEGIN2][STATE.OTHERS]=STATE.ERROR,this.TT[STATE.IN_COMMENT][getCharCode("-")]=STATE.WAIT_FOR_COMMENT_END1,this.TT[STATE.IN_COMMENT][STATE.OTHERS]=STATE.IN_COMMENT,this.TT[STATE.WAIT_FOR_COMMENT_END1][getCharCode("-")]=STATE.WAIT_FOR_COMMENT_END2,this.TT[STATE.WAIT_FOR_COMMENT_END1][STATE.OTHERS]=STATE.IN_COMMENT,this.TT[STATE.WAIT_FOR_COMMENT_END2][getCharCode(">")]=STATE.SIMPLE|ACTION.IGNORE|ACTION.GET_WHITECHARS_BEFORE,this.TT[STATE.WAIT_FOR_COMMENT_END2][getCharCode("-")]=STATE.WAIT_FOR_COMMENT_END2,this.TT[STATE.WAIT_FOR_COMMENT_END2][STATE.OTHERS]=STATE.IN_COMMENT,this.FillTT(STATE.IN_TAG_WORD,STATE.IN_TAG_WORD,ACTION.NOTHING,T),this.FillTT(STATE.IN_TAG_WORD,STATE.IN_TAG_WORD,ACTION.NOTHING,"0123456789"),this.FillTT(STATE.IN_TAG_WORD,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.TT[STATE.IN_TAG_WORD][getCharCode("=")]=STATE.TAG_EQ|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.IN_TAG_WORD][getCharCode('"')]=STATE.ERROR,this.TT[STATE.IN_TAG_WORD][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_EXCLUDE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.IN_TAG_WORD][getCharCode("/")]=STATE.WAIT_FOR_RIGHT_BRACKET|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.IN_TAG_WORD][STATE.OTHERS]=STATE.IN_TAG|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.IN_TAG_WORD][0]=STATE.ERROR,this.FillTT(STATE.TAG_EQ,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.FillTT(STATE.TAG_EQ,STATE.IN_STRING,ACTION.STORE_TOKEN_EXCLUDE,T),this.TT[STATE.TAG_EQ][getCharCode('"')]=STATE.IN_STRING|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.TAG_EQ][getCharCode("'")]=STATE.IN_STRING2|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.TAG_EQ][0]=STATE.ERROR,this.TT[STATE.TAG_EQ][STATE.OTHERS]=STATE.ERROR,this.FillTT(STATE.IN_TAG,STATE.IN_TAG,ACTION.IGNORE," \n\t\r"),this.FillTT(STATE.IN_TAG,STATE.IN_TAG_WORD,ACTION.NOTHING,T),this.FillTT(STATE.IN_TAG,STATE.ERROR,ACTION.NOTHING,"0123456789"),this.TT[STATE.IN_TAG][getCharCode("<")]=STATE.ERROR,this.TT[STATE.IN_TAG][getCharCode('"')]=STATE.IN_STRING,this.TT[STATE.IN_TAG][getCharCode("'")]=STATE.IN_STRING2,this.TT[STATE.IN_TAG][getCharCode("/")]=STATE.WAIT_FOR_RIGHT_BRACKET,this.TT[STATE.IN_TAG][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.IN_TAG][getCharCode("=")]=STATE.TAG_EQ,this.TT[STATE.IN_TAG][0]=STATE.ERROR,this.TT[STATE.IN_TAG][STATE.OTHERS]=STATE.ERROR,this.FillTT(STATE.WAIT_FOR_RIGHT_BRACKET,STATE.IN_TAG_WORD,ACTION.STORE_TOKEN_EXCLUDE,T),this.TT[STATE.WAIT_FOR_RIGHT_BRACKET][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.WAIT_FOR_RIGHT_BRACKET][STATE.OTHERS]=STATE.ERROR,this.FillTT_string(STATE.IN_STRING,'"'),this.FillTT_string(STATE.IN_STRING2,"'"),this.TT[STATE.TAG_START][getCharCode("w")]=STATE.WXS_BEGIN_STEP1;let E="wxs",_=STATE.WXS_BEGIN_STEP1;for(let T=1,S=_;T<E.length;T++)this.TT[S][getCharCode(E[T])]=_+T,this.TT[S][STATE.OTHERS]=STATE.IN_TAG_WORD|ACTION.REFEED|ACTION.STORE_TOKEN_FIRST,2===T&&(this.TT[S][getCharCode(E[T])]|=ACTION.SET_WXS_STATE),S=_+T;this.FillTT(STATE.WXS_BEGIN_STEP3,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.TT[STATE.WXS_BEGIN_STEP3][getCharCode(">")]=STATE.IN_WXS|ACTION.STORE_TOKEN_EXCLUDE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.WXS_BEGIN_STEP3][STATE.OTHERS]=STATE.IN_TAG_WORD|ACTION.REFEED|ACTION.STORE_TOKEN_FIRST|ACTION.SET_WXS_STATE,this.TT[STATE.IN_WXS][getCharCode("<")]=STATE.WXS_END_STEP1,this.TT[STATE.IN_WXS][STATE.OTHERS]=STATE.IN_WXS,E="</wxs",_=STATE.WXS_END_STEP1;for(let T=1,S=_;T<E.length;T++)this.TT[S][getCharCode(E[T])]=_+T,4===T&&(this.TT[S][getCharCode(E[T])]|=ACTION.WXS_BACK|ACTION.SET_WXS_STATE),this.TT[S][STATE.OTHERS]=STATE.IN_WXS|ACTION.REFEED,S=_+T;this.FillTT(STATE.WXS_END_STEP5,STATE.WXS_END_STEP5,ACTION.NOTHING," \n\t\r"),this.TT[STATE.WXS_END_STEP5][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.WXS_END_STEP5][STATE.OTHERS]=STATE.ERROR,this.TT[STATE.SIMPLE][getCharCode(" ")]=STATE.SIMPLE_SPACE_OR_TAB|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.SIMPLE][getCharCode("\t")]=STATE.SIMPLE_SPACE_OR_TAB|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.SIMPLE][getCharCode("\n")]=STATE.SIMPLE_LINE_BREAK_BEGIN1|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.SIMPLE_SPACE_OR_TAB][getCharCode(" ")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_SPACE_OR_TAB][getCharCode("\t")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_SPACE_OR_TAB][getCharCode("\n")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_SPACE_OR_TAB][getCharCode("<")]=STATE.SIMPLE|ACTION.STORE_ONE_SPACE|ACTION.REFEED|ACTION.STORE_STATE_BEFORE_COMMENT,this.TT[STATE.SIMPLE_SPACE_OR_TAB][STATE.OTHERS]=STATE.SIMPLE|ACTION.STORE_ONE_SPACE|ACTION.REFEED,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][getCharCode("\n")]=STATE.SIMPLE_LINE_BREAK_BEGIN2,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][getCharCode("\t")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][getCharCode(" ")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][getCharCode("<")]=STATE.SIMPLE|ACTION.REFEED|ACTION.STORE_STATE_BEFORE_COMMENT,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][STATE.OTHERS]=STATE.SIMPLE|ACTION.REFEED|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][getCharCode("\n")]=STATE.SIMPLE_LINE_BREAK_BEGIN2,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][getCharCode("\t")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][getCharCode(" ")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][getCharCode("<")]=STATE.SIMPLE|ACTION.STORE_ONE_LINE_BREAK|ACTION.REFEED|ACTION.STORE_STATE_BEFORE_COMMENT,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][STATE.OTHERS]=STATE.SIMPLE|ACTION.REFEED|ACTION.STORE_ONE_LINE_BREAK,this.TT[STATE.TAG_START][getCharCode("t")]=STATE.TEXT_BEGIN_STEP1,E="text",_=STATE.TEXT_BEGIN_STEP1;for(let T=1,S=_;T<E.length;T++)this.TT[S][getCharCode(E[T])]=_+T,3===T&&(this.TT[S][getCharCode(E[T])]|=ACTION.SET_TEXT_STATE),this.TT[S][STATE.OTHERS]=STATE.IN_TAG_WORD|ACTION.REFEED|ACTION.STORE_TOKEN_FIRST,S=_+T;this.FillTT(STATE.TEXT_BEGIN_STEP4,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.TT[STATE.TEXT_BEGIN_STEP4][getCharCode(">")]=STATE.IN_TEXT|ACTION.STORE_TOKEN_EXCLUDE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.TEXT_BEGIN_STEP4][STATE.OTHERS]=STATE.IN_TAG_WORD|ACTION.REFEED|ACTION.STORE_TOKEN_FIRST|ACTION.SET_TEXT_STATE,this.TT[STATE.IN_TEXT][getCharCode("<")]=STATE.TEXT_END_STEP1,this.TT[STATE.IN_TEXT][STATE.OTHERS]=STATE.IN_TEXT,E="</text",_=STATE.TEXT_END_STEP1;for(let T=1,S=_;T<E.length;T++)this.TT[S][getCharCode(E[T])]=_+T,5===T&&(this.TT[S][getCharCode(E[T])]|=ACTION.TEXT_BACK|ACTION.SET_TEXT_STATE),this.TT[S][STATE.OTHERS]=STATE.IN_TEXT|ACTION.REFEED,S=_+T;this.FillTT(STATE.TEXT_END_STEP6,STATE.TEXT_END_STEP6,ACTION.NOTHING," \n\t\r"),this.TT[STATE.TEXT_END_STEP6][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.TEXT_END_STEP6][STATE.OTHERS]=STATE.ERROR}}class Tokenizer{constructor(T,E){this.machine=new Machine(E,T),this.m_pSrc=T,this.path=E}generateTokens(T){this.machine.Reset();let E=0;if(0===this.m_pSrc.length)return E;for(let _=0;_<this.m_pSrc.length&&0==E;_++){let S=this.m_pSrc[_];E=this.machine.Feed(S,T)}return 0!==E||(E=this.machine.Feed("\0",T)),E}}function generateWXMLFromTokens(T){let E="";for(let _ of T){let T=_.value;_.type===TokenType.ATTR&&(T=" "+T),E+=T}return E}async function minifyWXML(T){const{code:E,filePath:_,setting:S={},root:t=""}=T,{minify:A,minifyWXML:N}=S,e=!!N,I=path_1.default.posix.join(t,_),s=Buffer.from(E);let O=tools_1.bufferToUtf8String(s);if(void 0===O)return{error:{code:config_1.FILE_NOT_UTF8,path:I,message:locales_1.default.config.FILE_NOT_UTF8.format(I)}};if(e&&O.length>0)try{let T=new Tokenizer(O.replace(/\r\n/g,"\n"),I),E=[];T.generateTokens(E);return O=generateWXMLFromTokens(E),{error:null,code:O.replace(/\r\n/g,"\n")}}catch(T){return log_1.default.error("minifywxml error @ "+I),log_1.default.error(T.msg),{error:{code:config_1.MINIFY_WXML_ERR,path:I,message:T.msg}}}return{error:null,code:O.replace(/\r\n/g,"\n")}}module.exports=minifyWXML;
|
|
1
|
+
"use strict";const tslib_1=require("tslib"),tools_1=require("../../../utils/tools"),path_1=(0,tslib_1.__importDefault)(require("path")),log_1=(0,tslib_1.__importDefault)(require("../../../utils/log")),config_1=require("../../../config"),locales_1=(0,tslib_1.__importDefault)(require("../../../utils/locales/locales"));function getCharCode(T){return T.charCodeAt(0)>=STATE.OTHERS?STATE.OTHERS:T.charCodeAt(0)}var TokenType,STATE,ACTION;!function(T){T[T.ATTR=0]="ATTR",T[T.STRING1=1]="STRING1",T[T.STRING2=2]="STRING2",T[T.OTHERS=3]="OTHERS"}(TokenType||(TokenType={})),function(T){T[T.ERROR=-1]="ERROR",T[T.NOT_SET=0]="NOT_SET",T[T.SIMPLE=1]="SIMPLE",T[T.TAG_START=2]="TAG_START",T[T.IN_TAG=3]="IN_TAG",T[T.IN_TAG_WORD=4]="IN_TAG_WORD",T[T.IN_STRING=5]="IN_STRING",T[T.IN_STRING_ESCAPE=6]="IN_STRING_ESCAPE",T[T.TAG_EQ=7]="TAG_EQ",T[T.IN_STRING2=9]="IN_STRING2",T[T.IN_STRING2_ESCAPE=10]="IN_STRING2_ESCAPE",T[T.IN_TEMPLATE_STRING=11]="IN_TEMPLATE_STRING",T[T.IN_TEMPLATE_STRING_ESCAPE=12]="IN_TEMPLATE_STRING_ESCAPE",T[T.IN_TEMPLATE_STRING2=13]="IN_TEMPLATE_STRING2",T[T.IN_TEMPLATE_STRING2_ESCAPE=14]="IN_TEMPLATE_STRING2_ESCAPE",T[T.WAIT_TEMPLATE_START=15]="WAIT_TEMPLATE_START",T[T.IN_TEMPLATE=16]="IN_TEMPLATE",T[T.WAIT_TEMPLATE_END=17]="WAIT_TEMPLATE_END",T[T.WAIT_FOR_RIGHT_BRACKET=18]="WAIT_FOR_RIGHT_BRACKET",T[T.IN_COMMENT=19]="IN_COMMENT",T[T.WAIT_FOR_COMMENT_END1=20]="WAIT_FOR_COMMENT_END1",T[T.WAIT_FOR_COMMENT_END2=21]="WAIT_FOR_COMMENT_END2",T[T.IN_COMMENT_BEGIN1=33]="IN_COMMENT_BEGIN1",T[T.IN_COMMENT_BEGIN2=34]="IN_COMMENT_BEGIN2",T[T.WXS_BEGIN_STEP1=22]="WXS_BEGIN_STEP1",T[T.WXS_BEGIN_STEP2=23]="WXS_BEGIN_STEP2",T[T.WXS_BEGIN_STEP3=24]="WXS_BEGIN_STEP3",T[T.WXS_BEGIN_STEP4=25]="WXS_BEGIN_STEP4",T[T.WXS_END_STEP1=26]="WXS_END_STEP1",T[T.WXS_END_STEP2=27]="WXS_END_STEP2",T[T.WXS_END_STEP3=28]="WXS_END_STEP3",T[T.WXS_END_STEP4=29]="WXS_END_STEP4",T[T.WXS_END_STEP5=30]="WXS_END_STEP5",T[T.IN_WXS=31]="IN_WXS",T[T.WXS_BEGIN_WAIT_FOR_RIGHT_BRACKET=32]="WXS_BEGIN_WAIT_FOR_RIGHT_BRACKET",T[T.SIMPLE_LINE_BREAK_BEGIN1=35]="SIMPLE_LINE_BREAK_BEGIN1",T[T.SIMPLE_LINE_BREAK_BEGIN2=36]="SIMPLE_LINE_BREAK_BEGIN2",T[T.SIMPLE_SPACE_OR_TAB=37]="SIMPLE_SPACE_OR_TAB",T[T.TEXT_BEGIN_STEP1=38]="TEXT_BEGIN_STEP1",T[T.TEXT_BEGIN_STEP2=39]="TEXT_BEGIN_STEP2",T[T.TEXT_BEGIN_STEP3=40]="TEXT_BEGIN_STEP3",T[T.TEXT_BEGIN_STEP4=41]="TEXT_BEGIN_STEP4",T[T.TEXT_BEGIN_STEP5=42]="TEXT_BEGIN_STEP5",T[T.TEXT_END_STEP1=43]="TEXT_END_STEP1",T[T.TEXT_END_STEP2=44]="TEXT_END_STEP2",T[T.TEXT_END_STEP3=45]="TEXT_END_STEP3",T[T.TEXT_END_STEP4=46]="TEXT_END_STEP4",T[T.TEXT_END_STEP5=47]="TEXT_END_STEP5",T[T.TEXT_END_STEP6=48]="TEXT_END_STEP6",T[T.IN_TEXT=49]="IN_TEXT",T[T.TEXT_BEGIN_WAIT_FOR_RIGHT_BRACKET=50]="TEXT_BEGIN_WAIT_FOR_RIGHT_BRACKET",T[T.END=99]="END",T[T.OTHERS=256]="OTHERS"}(STATE||(STATE={})),function(T){T[T.NOTHING=0]="NOTHING",T[T.DO_ACTION=65536]="DO_ACTION",T[T.STORE_TOKEN_EXCLUDE=131072]="STORE_TOKEN_EXCLUDE",T[T.STORE_TOKEN_INCLUDE=262144]="STORE_TOKEN_INCLUDE",T[T.IGNORE=524288]="IGNORE",T[T.REFEED=1048576]="REFEED",T[T.STORE_TOKEN_FIRST=2097152]="STORE_TOKEN_FIRST",T[T.STORE_ONE_SPACE=4194304]="STORE_ONE_SPACE",T[T.STORE_ONE_LINE_BREAK=8388608]="STORE_ONE_LINE_BREAK",T[T.GET_WHITECHARS_BEFORE=16777216]="GET_WHITECHARS_BEFORE",T[T.STORE_STATE_BEFORE_COMMENT=33554432]="STORE_STATE_BEFORE_COMMENT",T[T.SET_WXS_STATE=67108864]="SET_WXS_STATE",T[T.WXS_BACK=134217728]="WXS_BACK",T[T.SET_TEXT_STATE=268435456]="SET_TEXT_STATE",T[T.TEXT_BACK=536870912]="TEXT_BACK"}(ACTION||(ACTION={}));class Token{constructor(T,E){this.type=T,this.value=E}}class MachineState{constructor(){this.cur_pos=0,this.last_pos=0,this.line=1,this.col=1,this.last_line=this.line,this.last_col=1,this.state=STATE.SIMPLE}}class Machine{constructor(T,E){this.mState=new MachineState,this.TT=new Array(1024);for(let T=0;T<1024;T++){let E=new Array(257);this.TT[T]=E}this.InitTransitTable(),this.mPath=T,this.mSrc=E,this.stateBeforeComment=STATE.SIMPLE,this.wxsState=!1,this.textState=!1}Reset(){return this.mState.cur_pos=this.mState.last_pos=0,this.mState.line=1,this.mState.col=1,this.mState.last_line=this.mState.line,this.mState.last_col=1,this.mState.state=STATE.SIMPLE,0}Feed(T,E){let _,S,t,A,N;"\n"===T&&(this.mState.line++,this.mState.col=0);do{if(N=!1,void 0!==_&&_&ACTION.REFEED&&(N=!0),_=this.TT[this.mState.state][getCharCode(T)],_===STATE.NOT_SET&&(_=this.TT[this.mState.state][STATE.OTHERS]),_===STATE.NOT_SET)throw{msg:`BAD STATE MACHINE! AT INPUT ${this.mState.state} ${T}`};if(_<0)throw"\0"!==T?{msg:`${this.mState.line}:${this.mState.col}:unexpected character \`${T.replace("\n","\\n")}\``}:{msg:`${this.mState.line}:${this.mState.col}:unexpected end`};if(S=_,t=65535&_,A=this.mState.state,S&ACTION.STORE_STATE_BEFORE_COMMENT&&!N&&(this.stateBeforeComment=A),A===STATE.WAIT_FOR_RIGHT_BRACKET&&">"===T&&this.wxsState&&(this.wxsState=!1),A===STATE.WAIT_FOR_RIGHT_BRACKET&&">"===T&&this.textState&&(this.textState=!1),S&ACTION.SET_WXS_STATE&&(this.wxsState=!this.wxsState),S&ACTION.SET_TEXT_STATE&&(this.textState=!this.textState),">"===T&&t===STATE.SIMPLE&&this.wxsState&&(t=STATE.IN_WXS),">"===T&&t===STATE.SIMPLE&&this.textState&&(t=STATE.IN_TEXT),this.mState.state=t,S&ACTION.STORE_TOKEN_FIRST&&this.mState.cur_pos>this.mState.last_pos){let T=new Token(TokenType.OTHERS,this.mSrc.substring(this.mState.last_pos,this.mState.last_pos+1));E.push(T),this.mState.last_pos++,this.mState.last_col++}if(S&ACTION.STORE_ONE_LINE_BREAK){let T=new Token(TokenType.OTHERS,"\n");E.push(T),this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col,this.mState.last_line=this.mState.line}if(S&ACTION.STORE_ONE_SPACE){let T=new Token(TokenType.OTHERS," ");E.push(T),this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col,this.mState.last_line=this.mState.line}}while(_&ACTION.REFEED);if(S&ACTION.STORE_TOKEN_EXCLUDE){let T=this.mState.cur_pos,_=this.mState.last_pos;if(T>_){let S;S=A===STATE.IN_TAG_WORD&&_>0&&" \n\t\r".includes(this.mSrc[_-1])?new Token(TokenType.ATTR,this.mSrc.substring(_,T)):(this.wxsState&&STATE.IN_WXS,new Token(TokenType.OTHERS,this.mSrc.substring(_,T))),E.push(S),this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col,this.mState.last_line=this.mState.line}}if(S&ACTION.WXS_BACK){let T=new Token(TokenType.OTHERS,this.mSrc.substring(this.mState.last_pos,this.mState.cur_pos-4));E.push(T),this.mState.last_pos=this.mState.cur_pos-4,this.mState.last_col=this.mState.col-4,this.mState.last_line=this.mState.line}if(S&ACTION.TEXT_BACK){let T=new Token(TokenType.OTHERS,this.mSrc.substring(this.mState.last_pos,this.mState.cur_pos-5));E.push(T),this.mState.last_pos=this.mState.cur_pos-5,this.mState.last_col=this.mState.col-5,this.mState.last_line=this.mState.line}if(this.mState.cur_pos++,this.mState.col++,S&ACTION.STORE_TOKEN_INCLUDE){let T;T=A===STATE.IN_STRING?TokenType.STRING1:A===STATE.IN_STRING2?TokenType.STRING2:TokenType.OTHERS;let _=new Token(T,this.mSrc.substring(this.mState.last_pos,this.mState.cur_pos));E.push(_),this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col,this.mState.last_line=this.mState.line}return S&ACTION.IGNORE&&(this.mState.last_pos=this.mState.cur_pos,this.mState.last_col=this.mState.col),S&ACTION.GET_WHITECHARS_BEFORE&&(this.mState.state=this.stateBeforeComment,this.stateBeforeComment!==STATE.SIMPLE_LINE_BREAK_BEGIN2&&this.stateBeforeComment!==STATE.SIMPLE_SPACE_OR_TAB||E.pop(),this.stateBeforeComment=STATE.SIMPLE),0}FillTT(T,E,_,S){for(let t of S)this.TT[T][getCharCode(t)]=E|_}FillTT_template_string(T,E){let _=T+1;this.TT[T][getCharCode("\\")]=_,this.TT[_][STATE.OTHERS]=T,this.TT[T][getCharCode(E)]=STATE.IN_TEMPLATE,this.TT[T][0]=STATE.ERROR,this.TT[T][STATE.OTHERS]=T}FillTT_string(T,E){let _=T+1;this.TT[T][getCharCode("\\")]=_,this.TT[T][getCharCode("\n")]=STATE.ERROR,this.TT[_][STATE.OTHERS]=T,this.TT[_][getCharCode("\n")]=STATE.IN_TAG|ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE,this.TT[T][getCharCode(E)]=STATE.IN_TAG|ACTION.STORE_TOKEN_INCLUDE,this.TT[T][0]=STATE.ERROR,this.TT[T][STATE.OTHERS]=T}InitTransitTable(){for(let T=0;T<1024;T++)this.TT[T].fill(0);let T="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-:";this.TT[STATE.END][STATE.OTHERS]=STATE.END,this.TT[STATE.SIMPLE][getCharCode("<")]=STATE.TAG_START|ACTION.STORE_TOKEN_EXCLUDE|ACTION.STORE_STATE_BEFORE_COMMENT,this.TT[STATE.SIMPLE][getCharCode("{")]=STATE.WAIT_TEMPLATE_START,this.TT[STATE.SIMPLE][STATE.OTHERS]=STATE.SIMPLE,this.TT[STATE.SIMPLE][0]=STATE.END|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.WAIT_TEMPLATE_START][getCharCode("{")]=STATE.IN_TEMPLATE,this.TT[STATE.WAIT_TEMPLATE_START][STATE.OTHERS]=STATE.SIMPLE,this.TT[STATE.IN_TEMPLATE][getCharCode("}")]=STATE.WAIT_TEMPLATE_END,this.TT[STATE.IN_TEMPLATE][0]=STATE.ERROR,this.TT[STATE.IN_TEMPLATE][STATE.OTHERS]=STATE.IN_TEMPLATE,this.TT[STATE.WAIT_TEMPLATE_END][getCharCode("}")]=STATE.SIMPLE,this.TT[STATE.WAIT_TEMPLATE_END][STATE.OTHERS]=STATE.IN_TEMPLATE|ACTION.REFEED,this.TT[STATE.IN_TEMPLATE][getCharCode('"')]=STATE.IN_TEMPLATE_STRING,this.TT[STATE.IN_TEMPLATE][getCharCode("'")]=STATE.IN_TEMPLATE_STRING2,this.FillTT_template_string(STATE.IN_TEMPLATE_STRING,'"'),this.FillTT_template_string(STATE.IN_TEMPLATE_STRING2,"'"),this.FillTT(STATE.TAG_START,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.FillTT(STATE.TAG_START,STATE.IN_TAG_WORD,ACTION.STORE_TOKEN_EXCLUDE,T),this.TT[STATE.TAG_START][getCharCode("/")]=STATE.IN_TAG|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.TAG_START][getCharCode("!")]=STATE.IN_COMMENT_BEGIN1,this.TT[STATE.TAG_START][STATE.OTHERS]=STATE.ERROR,this.TT[STATE.IN_COMMENT_BEGIN1][getCharCode("-")]=STATE.IN_COMMENT_BEGIN2,this.TT[STATE.IN_COMMENT_BEGIN1][STATE.OTHERS]=STATE.ERROR,this.TT[STATE.IN_COMMENT_BEGIN2][getCharCode("-")]=STATE.IN_COMMENT,this.TT[STATE.IN_COMMENT_BEGIN2][STATE.OTHERS]=STATE.ERROR,this.TT[STATE.IN_COMMENT][getCharCode("-")]=STATE.WAIT_FOR_COMMENT_END1,this.TT[STATE.IN_COMMENT][STATE.OTHERS]=STATE.IN_COMMENT,this.TT[STATE.WAIT_FOR_COMMENT_END1][getCharCode("-")]=STATE.WAIT_FOR_COMMENT_END2,this.TT[STATE.WAIT_FOR_COMMENT_END1][STATE.OTHERS]=STATE.IN_COMMENT,this.TT[STATE.WAIT_FOR_COMMENT_END2][getCharCode(">")]=STATE.SIMPLE|ACTION.IGNORE|ACTION.GET_WHITECHARS_BEFORE,this.TT[STATE.WAIT_FOR_COMMENT_END2][getCharCode("-")]=STATE.WAIT_FOR_COMMENT_END2,this.TT[STATE.WAIT_FOR_COMMENT_END2][STATE.OTHERS]=STATE.IN_COMMENT,this.FillTT(STATE.IN_TAG_WORD,STATE.IN_TAG_WORD,ACTION.NOTHING,T),this.FillTT(STATE.IN_TAG_WORD,STATE.IN_TAG_WORD,ACTION.NOTHING,"0123456789"),this.FillTT(STATE.IN_TAG_WORD,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.TT[STATE.IN_TAG_WORD][getCharCode("=")]=STATE.TAG_EQ|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.IN_TAG_WORD][getCharCode('"')]=STATE.ERROR,this.TT[STATE.IN_TAG_WORD][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_EXCLUDE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.IN_TAG_WORD][getCharCode("/")]=STATE.WAIT_FOR_RIGHT_BRACKET|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.IN_TAG_WORD][STATE.OTHERS]=STATE.IN_TAG|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.IN_TAG_WORD][0]=STATE.ERROR,this.FillTT(STATE.TAG_EQ,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.FillTT(STATE.TAG_EQ,STATE.IN_STRING,ACTION.STORE_TOKEN_EXCLUDE,T),this.TT[STATE.TAG_EQ][getCharCode('"')]=STATE.IN_STRING|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.TAG_EQ][getCharCode("'")]=STATE.IN_STRING2|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.TAG_EQ][0]=STATE.ERROR,this.TT[STATE.TAG_EQ][STATE.OTHERS]=STATE.ERROR,this.FillTT(STATE.IN_TAG,STATE.IN_TAG,ACTION.IGNORE," \n\t\r"),this.FillTT(STATE.IN_TAG,STATE.IN_TAG_WORD,ACTION.NOTHING,T),this.FillTT(STATE.IN_TAG,STATE.ERROR,ACTION.NOTHING,"0123456789"),this.TT[STATE.IN_TAG][getCharCode("<")]=STATE.ERROR,this.TT[STATE.IN_TAG][getCharCode('"')]=STATE.IN_STRING,this.TT[STATE.IN_TAG][getCharCode("'")]=STATE.IN_STRING2,this.TT[STATE.IN_TAG][getCharCode("/")]=STATE.WAIT_FOR_RIGHT_BRACKET,this.TT[STATE.IN_TAG][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.IN_TAG][getCharCode("=")]=STATE.TAG_EQ,this.TT[STATE.IN_TAG][0]=STATE.ERROR,this.TT[STATE.IN_TAG][STATE.OTHERS]=STATE.ERROR,this.FillTT(STATE.WAIT_FOR_RIGHT_BRACKET,STATE.IN_TAG_WORD,ACTION.STORE_TOKEN_EXCLUDE,T),this.TT[STATE.WAIT_FOR_RIGHT_BRACKET][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.WAIT_FOR_RIGHT_BRACKET][STATE.OTHERS]=STATE.ERROR,this.FillTT_string(STATE.IN_STRING,'"'),this.FillTT_string(STATE.IN_STRING2,"'"),this.TT[STATE.TAG_START][getCharCode("w")]=STATE.WXS_BEGIN_STEP1;let E="wxs",_=STATE.WXS_BEGIN_STEP1;for(let T=1,S=_;T<E.length;T++)this.TT[S][getCharCode(E[T])]=_+T,this.TT[S][STATE.OTHERS]=STATE.IN_TAG_WORD|ACTION.REFEED|ACTION.STORE_TOKEN_FIRST,2===T&&(this.TT[S][getCharCode(E[T])]|=ACTION.SET_WXS_STATE),S=_+T;this.FillTT(STATE.WXS_BEGIN_STEP3,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.TT[STATE.WXS_BEGIN_STEP3][getCharCode(">")]=STATE.IN_WXS|ACTION.STORE_TOKEN_EXCLUDE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.WXS_BEGIN_STEP3][STATE.OTHERS]=STATE.IN_TAG_WORD|ACTION.REFEED|ACTION.STORE_TOKEN_FIRST|ACTION.SET_WXS_STATE,this.TT[STATE.IN_WXS][getCharCode("<")]=STATE.WXS_END_STEP1,this.TT[STATE.IN_WXS][STATE.OTHERS]=STATE.IN_WXS,E="</wxs",_=STATE.WXS_END_STEP1;for(let T=1,S=_;T<E.length;T++)this.TT[S][getCharCode(E[T])]=_+T,4===T&&(this.TT[S][getCharCode(E[T])]|=ACTION.WXS_BACK|ACTION.SET_WXS_STATE),this.TT[S][STATE.OTHERS]=STATE.IN_WXS|ACTION.REFEED,S=_+T;this.FillTT(STATE.WXS_END_STEP5,STATE.WXS_END_STEP5,ACTION.NOTHING," \n\t\r"),this.TT[STATE.WXS_END_STEP5][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.WXS_END_STEP5][STATE.OTHERS]=STATE.ERROR,this.TT[STATE.SIMPLE][getCharCode(" ")]=STATE.SIMPLE_SPACE_OR_TAB|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.SIMPLE][getCharCode("\t")]=STATE.SIMPLE_SPACE_OR_TAB|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.SIMPLE][getCharCode("\n")]=STATE.SIMPLE_LINE_BREAK_BEGIN1|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.SIMPLE_SPACE_OR_TAB][getCharCode(" ")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_SPACE_OR_TAB][getCharCode("\t")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_SPACE_OR_TAB][getCharCode("\n")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_SPACE_OR_TAB][getCharCode("<")]=STATE.SIMPLE|ACTION.STORE_ONE_SPACE|ACTION.REFEED|ACTION.STORE_STATE_BEFORE_COMMENT,this.TT[STATE.SIMPLE_SPACE_OR_TAB][STATE.OTHERS]=STATE.SIMPLE|ACTION.STORE_ONE_SPACE|ACTION.REFEED,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][getCharCode("\n")]=STATE.SIMPLE_LINE_BREAK_BEGIN2,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][getCharCode("\t")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][getCharCode(" ")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][getCharCode("<")]=STATE.SIMPLE|ACTION.REFEED|ACTION.STORE_STATE_BEFORE_COMMENT,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN1][STATE.OTHERS]=STATE.SIMPLE|ACTION.REFEED|ACTION.STORE_TOKEN_EXCLUDE,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][getCharCode("\n")]=STATE.SIMPLE_LINE_BREAK_BEGIN2,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][getCharCode("\t")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][getCharCode(" ")]=STATE.SIMPLE_SPACE_OR_TAB,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][getCharCode("<")]=STATE.SIMPLE|ACTION.STORE_ONE_LINE_BREAK|ACTION.REFEED|ACTION.STORE_STATE_BEFORE_COMMENT,this.TT[STATE.SIMPLE_LINE_BREAK_BEGIN2][STATE.OTHERS]=STATE.SIMPLE|ACTION.REFEED|ACTION.STORE_ONE_LINE_BREAK,this.TT[STATE.TAG_START][getCharCode("t")]=STATE.TEXT_BEGIN_STEP1,E="text",_=STATE.TEXT_BEGIN_STEP1;for(let T=1,S=_;T<E.length;T++)this.TT[S][getCharCode(E[T])]=_+T,3===T&&(this.TT[S][getCharCode(E[T])]|=ACTION.SET_TEXT_STATE),this.TT[S][STATE.OTHERS]=STATE.IN_TAG_WORD|ACTION.REFEED|ACTION.STORE_TOKEN_FIRST,S=_+T;this.FillTT(STATE.TEXT_BEGIN_STEP4,STATE.IN_TAG,ACTION.STORE_TOKEN_EXCLUDE|ACTION.IGNORE," \n\t\r"),this.TT[STATE.TEXT_BEGIN_STEP4][getCharCode(">")]=STATE.IN_TEXT|ACTION.STORE_TOKEN_EXCLUDE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.TEXT_BEGIN_STEP4][STATE.OTHERS]=STATE.IN_TAG_WORD|ACTION.REFEED|ACTION.STORE_TOKEN_FIRST|ACTION.SET_TEXT_STATE,this.TT[STATE.IN_TEXT][getCharCode("<")]=STATE.TEXT_END_STEP1,this.TT[STATE.IN_TEXT][STATE.OTHERS]=STATE.IN_TEXT,E="</text",_=STATE.TEXT_END_STEP1;for(let T=1,S=_;T<E.length;T++)this.TT[S][getCharCode(E[T])]=_+T,5===T&&(this.TT[S][getCharCode(E[T])]|=ACTION.TEXT_BACK|ACTION.SET_TEXT_STATE),this.TT[S][STATE.OTHERS]=STATE.IN_TEXT|ACTION.REFEED,S=_+T;this.FillTT(STATE.TEXT_END_STEP6,STATE.TEXT_END_STEP6,ACTION.NOTHING," \n\t\r"),this.TT[STATE.TEXT_END_STEP6][getCharCode(">")]=STATE.SIMPLE|ACTION.STORE_TOKEN_INCLUDE,this.TT[STATE.TEXT_END_STEP6][STATE.OTHERS]=STATE.ERROR}}class Tokenizer{constructor(T,E){this.machine=new Machine(E,T),this.m_pSrc=T,this.path=E}generateTokens(T){this.machine.Reset();let E=0;if(0===this.m_pSrc.length)return E;for(let _=0;_<this.m_pSrc.length&&0==E;_++){let S=this.m_pSrc[_];E=this.machine.Feed(S,T)}return 0!==E||(E=this.machine.Feed("\0",T)),E}}function generateWXMLFromTokens(T){let E="";for(let _ of T){let T=_.value;_.type===TokenType.ATTR&&(T=" "+T),E+=T}return E}async function minifyWXML(T){const{code:E,filePath:_,setting:S={},root:t=""}=T,{minify:A,minifyWXML:N}=S,e=!!N,I=path_1.default.posix.join(t,_),s=Buffer.from(E);let O=(0,tools_1.bufferToUtf8String)(s);if(void 0===O)return{error:{code:config_1.FILE_NOT_UTF8,path:I,message:locales_1.default.config.FILE_NOT_UTF8.format(I)}};if(e&&O.length>0)try{let T=new Tokenizer(O.replace(/\r\n/g,"\n"),I),E=[];T.generateTokens(E);return O=generateWXMLFromTokens(E),{error:null,code:O.replace(/\r\n/g,"\n")}}catch(T){return log_1.default.error("minifywxml error @ "+I),log_1.default.error(T.msg),{error:{code:config_1.MINIFY_WXML_ERR,path:I,message:T.msg}}}return{error:null,code:O.replace(/\r\n/g,"\n")}}module.exports=minifyWXML;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _a;process.env&&process.env.isDevtools&&require("../../utils/hackrequire/index"),Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");(null===(_a=process.env)||void 0===_a?void 0:_a.isDevtools)&&require("../../utils/hackrequire/index");const worker_threads_1=require("worker_threads"),index_1=tslib_1.__importDefault(require("./task/index")),config_1=require("./config"),logger_1=require("../utils/logger");worker_threads_1.isMainThread?module.exports=index_1.default:worker_threads_1.parentPort.on("message",e=>{const{command:r,data:o}=e;r===config_1.COMMAND.RUN_TASK&&(logger_1.logger.info("worker process task start",r,o.data.filePath),index_1.default(o.taskName,o.data).then(e=>{logger_1.logger.info("worker process task end",r,o.data.filePath),worker_threads_1.parentPort.postMessage({command:config_1.COMMAND.TASK_DONE,data:e})}).catch(e=>{worker_threads_1.parentPort.postMessage({command:config_1.COMMAND.TASK_DONE,data:{error:e.toString()}})}))});
|
|
1
|
+
var _a;process.env&&process.env.isDevtools&&require("../../utils/hackrequire/index"),Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");(null===(_a=process.env)||void 0===_a?void 0:_a.isDevtools)&&require("../../utils/hackrequire/index");const worker_threads_1=require("worker_threads"),index_1=(0,tslib_1.__importDefault)(require("./task/index")),config_1=require("./config"),logger_1=require("../utils/logger");worker_threads_1.isMainThread?module.exports=index_1.default:worker_threads_1.parentPort.on("message",e=>{const{command:r,data:o}=e;r===config_1.COMMAND.RUN_TASK&&(logger_1.logger.info("worker process task start",r,o.data.filePath),(0,index_1.default)(o.taskName,o.data).then(e=>{logger_1.logger.info("worker process task end",r,o.data.filePath),worker_threads_1.parentPort.postMessage({command:config_1.COMMAND.TASK_DONE,data:e})}).catch(e=>{worker_threads_1.parentPort.postMessage({command:config_1.COMMAND.TASK_DONE,data:{error:e.toString()}})}))});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getWorkerManager=exports.AbortEvent=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),os_1=tslib_1.__importDefault(require("os")),events_1=tslib_1.__importDefault(require("events")),log_1=tslib_1.__importDefault(require("../../utils/log")),config_1=require("./config"),call_func_1=require("./task/call_func"),child_process_1=require("child_process"),logger_1=require("../utils/logger"),env_1=require("../utils/env"),cpus=os_1.default.cpus().length,WORKER_PATH=path_1.default.posix.join(__dirname,"./worker.js"),FORK_PATH=path_1.default.posix.join(__dirname,"./fork.js"),MAX_TASK_TRY_TIME=2;let envIsDevtools=!1;function getCurrentScriptPath(){const e=path_1.default.posix.relative(process.cwd(),__filename);return process.cwd()===__dirname?`.${path_1.default.posix.resolve}${e}`:e}let Worker,workerManagerInstance,supportWorkerThread=!1;try{Worker=require("worker_threads").Worker,supportWorkerThread=!0}catch(e){supportWorkerThread=!1}exports.AbortEvent="WorkerTaskAborted";class WorkerInstance extends events_1.default{constructor(){super(),this.status=config_1.EWorkerStatus.free,this.threadId=-1,this._suicideTime=config_1.SUICIDE_TIME["miniprogram-ci"],this._postMessage=()=>{},envIsDevtools&&(this._suicideTime=config_1.SUICIDE_TIME.devtools);const e={NODE_PATH:path_1.default.posix.join(getCurrentScriptPath(),"../../../node_modules"),isDevtools:String(envIsDevtools)};supportWorkerThread?(logger_1.logger.info("create worker start"),this._instance=new Worker(WORKER_PATH,{env:Object.assign(Object.assign({},e),{cpprocessEnv:"workerthread"}),stdout:!0}),this.threadId=this._instance.threadId,this._postMessage=this._instance.postMessage.bind(this._instance)):(this._instance=child_process_1.fork(FORK_PATH,[""],{env:Object.assign(Object.assign({},e),{cpprocessEnv:"workerprocess"})}),this.threadId=this._instance.pid,this._postMessage=this._instance.send.bind(this._instance));this._instance.on("message",e=>{const{command:t,data:s}=e;t===config_1.COMMAND.TASK_DONE&&this.onTaskDone(s),t===config_1.COMMAND.SEND_LOG&&logger_1.logger.send(s.level,s.args),t===config_1.COMMAND.CALL_FUNC&&call_func_1.call.apply(null,[s.funcName,...s.args]).then(e=>{this._postMessage({command:config_1.COMMAND.CALL_FUNC_RESULT,data:{id:s.id,result:e}})}).catch(e=>{this._postMessage({command:config_1.COMMAND.CALL_FUNC_RESULT,data:{id:s.id,error:e.toString()}})})}),this._instance.on("exit",e=>{0!==e&&1!==e&&log_1.default.error(`worker thread: ${this.threadId}, status: ${this.status}, exit with code: ${e}`),this.emit("exit",{code:e,status:this.status,task:this._task,threadId:this.threadId})})}on(e,t){return super.on(e,t)}onTaskDone(e){var t;this.status=config_1.EWorkerStatus.free,(null===(t=this._task)||void 0===t?void 0:t.resolve)&&(this._task.onStatusUpdate(config_1.ETaskStatus.done),this._task.resolve(e)),this._task=void 0,this.emit("taskDone",this.threadId),env_1.summerProcess||this.setUpSuicideTimer()}setUpSuicideTimer(){this._suicideTimer=setTimeout(()=>{clearTimeout(this._suicideTimer),this.status===config_1.EWorkerStatus.free?(this.status=config_1.EWorkerStatus.dying,supportWorkerThread?this._instance.terminate():this._instance.kill("SIGTERM")):this._suicideTimer||this.setUpSuicideTimer()},this._suicideTime)}runTask(e){clearTimeout(this._suicideTimer),this.status=config_1.EWorkerStatus.busy,this._task=e,this._task.onStatusUpdate(config_1.ETaskStatus.progress),this._postMessage({command:config_1.COMMAND.RUN_TASK,data:{taskName:e.name,data:e.data}})}}class WorkerManager{constructor(e,t=!1){this._taskQueue=[],this._workerPool={},this._max_pool_size=4,this.onWorkerExit=e=>{const{code:t,status:s,task:r,threadId:i}=e;delete this._workerPool[i],s===config_1.EWorkerStatus.busy&&(r.retryTimes+=1,r.retryTimes<=2?(log_1.default.error(`worker thread: ${i} exit with code: ${t} when it is busy, retry ${r.retryTimes} times`),this._taskQueue.push(r)):r.reject(`worker thread exit with code: ${t} when it is busy`)),this._run()},this._actualWorkerPoolSize=1,this._doneThreadSet=new Set,this.onTaskDone=e=>{this._doneThreadSet.add(e),this._actualWorkerPoolSize=Math.min(howManyWorker(this._doneThreadSet.size),this._max_pool_size),this._run()},this._max_pool_size=e>8?8:e,envIsDevtools=t}runTask(e,t,s=(()=>{})){return new Promise((r,i)=>{const o={name:e,data:t,resolve:r,reject:i,retryTimes:0,onStatusUpdate:s};s(config_1.ETaskStatus.waiting),this._taskQueue.push(o),this._run()})}abort(e){const t=[],s=[];this._taskQueue.forEach(r=>{r.name!==e?s.push(r):t.push(r)}),t.forEach(e=>{e.reject(exports.AbortEvent)}),this._taskQueue=s}_run(){let e=this._taskQueue[0];for(;e;){const t=this.allocWorker();if(!t)return;this._taskQueue.shift(),t.runTask(e),e=this._taskQueue[0]}}allocWorker(){for(const e in this._workerPool){const t=this._workerPool[e];if(t.status===config_1.EWorkerStatus.free)return t}if(this.workerCount()<this._max_pool_size){const e=new WorkerInstance;return e.on("taskDone",this.onTaskDone),e.on("exit",this.onWorkerExit),this._workerPool[e.threadId]=e,e}return null}workerCount(){return Object.keys(this._workerPool).length}}function howManyWorker(e){switch(e){case 1:return 4;case 2:return 6;default:return 8}}const getWorkerManager=function(e=!1){if(!workerManagerInstance){let t=parseInt(process.env.COMPILE_THREADS||"0",10);(t<=0||t>cpus)&&(t=cpus),workerManagerInstance=new WorkerManager(t,e)}return workerManagerInstance};exports.getWorkerManager=getWorkerManager;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getWorkerManager=exports.AbortEvent=void 0;const tslib_1=require("tslib"),path_1=(0,tslib_1.__importDefault)(require("path")),os_1=(0,tslib_1.__importDefault)(require("os")),events_1=(0,tslib_1.__importDefault)(require("events")),log_1=(0,tslib_1.__importDefault)(require("../../utils/log")),config_1=require("./config"),call_func_1=require("./task/call_func"),child_process_1=require("child_process"),logger_1=require("../utils/logger"),env_1=require("../utils/env"),cpus=os_1.default.cpus().length,WORKER_PATH=path_1.default.posix.join(__dirname,"./worker.js"),FORK_PATH=path_1.default.posix.join(__dirname,"./fork.js"),MAX_TASK_TRY_TIME=2;let envIsDevtools=!1;function getCurrentScriptPath(){const e=path_1.default.posix.relative(process.cwd(),__filename);return process.cwd()===__dirname?`.${path_1.default.posix.resolve}${e}`:e}let Worker,workerManagerInstance,supportWorkerThread=!1;try{Worker=require("worker_threads").Worker,supportWorkerThread=!0}catch(e){supportWorkerThread=!1}exports.AbortEvent="WorkerTaskAborted";class WorkerInstance extends events_1.default{constructor(){super(),this.status=config_1.EWorkerStatus.free,this.threadId=-1,this._suicideTime=config_1.SUICIDE_TIME["miniprogram-ci"],this._postMessage=()=>{},envIsDevtools&&(this._suicideTime=config_1.SUICIDE_TIME.devtools);const e={NODE_PATH:path_1.default.posix.join(getCurrentScriptPath(),"../../../node_modules"),isDevtools:String(envIsDevtools)};supportWorkerThread?(logger_1.logger.info("create worker start"),this._instance=new Worker(WORKER_PATH,{env:Object.assign(Object.assign({},e),{cpprocessEnv:"workerthread"}),stdout:!0}),this.threadId=this._instance.threadId,this._postMessage=this._instance.postMessage.bind(this._instance)):(this._instance=(0,child_process_1.fork)(FORK_PATH,[""],{env:Object.assign(Object.assign({},e),{cpprocessEnv:"workerprocess"})}),this.threadId=this._instance.pid,this._postMessage=this._instance.send.bind(this._instance));this._instance.on("message",e=>{const{command:t,data:s}=e;t===config_1.COMMAND.TASK_DONE&&this.onTaskDone(s),t===config_1.COMMAND.SEND_LOG&&logger_1.logger.send(s.level,s.args),t===config_1.COMMAND.CALL_FUNC&&call_func_1.call.apply(null,[s.funcName,...s.args]).then(e=>{this._postMessage({command:config_1.COMMAND.CALL_FUNC_RESULT,data:{id:s.id,result:e}})}).catch(e=>{this._postMessage({command:config_1.COMMAND.CALL_FUNC_RESULT,data:{id:s.id,error:e.toString()}})})}),this._instance.on("exit",e=>{0!==e&&1!==e&&log_1.default.error(`worker thread: ${this.threadId}, status: ${this.status}, exit with code: ${e}`),this.emit("exit",{code:e,status:this.status,task:this._task,threadId:this.threadId})})}on(e,t){return super.on(e,t)}onTaskDone(e){var t;this.status=config_1.EWorkerStatus.free,(null===(t=this._task)||void 0===t?void 0:t.resolve)&&(this._task.onStatusUpdate(config_1.ETaskStatus.done),this._task.resolve(e)),this._task=void 0,this.emit("taskDone",this.threadId),env_1.summerProcess||this.setUpSuicideTimer()}setUpSuicideTimer(){this._suicideTimer=setTimeout(()=>{clearTimeout(this._suicideTimer),this.status===config_1.EWorkerStatus.free?(this.status=config_1.EWorkerStatus.dying,supportWorkerThread?this._instance.terminate():this._instance.kill("SIGTERM")):this._suicideTimer||this.setUpSuicideTimer()},this._suicideTime)}runTask(e){clearTimeout(this._suicideTimer),this.status=config_1.EWorkerStatus.busy,this._task=e,this._task.onStatusUpdate(config_1.ETaskStatus.progress),this._postMessage({command:config_1.COMMAND.RUN_TASK,data:{taskName:e.name,data:e.data}})}}class WorkerManager{constructor(e,t=!1){this._taskQueue=[],this._workerPool={},this._max_pool_size=4,this.onWorkerExit=e=>{const{code:t,status:s,task:r,threadId:i}=e;delete this._workerPool[i],s===config_1.EWorkerStatus.busy&&(r.retryTimes+=1,r.retryTimes<=2?(log_1.default.error(`worker thread: ${i} exit with code: ${t} when it is busy, retry ${r.retryTimes} times`),this._taskQueue.push(r)):r.reject(`worker thread exit with code: ${t} when it is busy`)),this._run()},this._actualWorkerPoolSize=1,this._doneThreadSet=new Set,this.onTaskDone=e=>{this._doneThreadSet.add(e),this._actualWorkerPoolSize=Math.min(howManyWorker(this._doneThreadSet.size),this._max_pool_size),this._run()},this._max_pool_size=e>8?8:e,envIsDevtools=t}runTask(e,t,s=(()=>{})){return new Promise((r,i)=>{const o={name:e,data:t,resolve:r,reject:i,retryTimes:0,onStatusUpdate:s};s(config_1.ETaskStatus.waiting),this._taskQueue.push(o),this._run()})}abort(e){const t=[],s=[];this._taskQueue.forEach(r=>{r.name!==e?s.push(r):t.push(r)}),t.forEach(e=>{e.reject(exports.AbortEvent)}),this._taskQueue=s}_run(){let e=this._taskQueue[0];for(;e;){const t=this.allocWorker();if(!t)return;this._taskQueue.shift(),t.runTask(e),e=this._taskQueue[0]}}allocWorker(){for(const e in this._workerPool){const t=this._workerPool[e];if(t.status===config_1.EWorkerStatus.free)return t}if(this.workerCount()<this._max_pool_size){const e=new WorkerInstance;return e.on("taskDone",this.onTaskDone),e.on("exit",this.onWorkerExit),this._workerPool[e.threadId]=e,e}return null}workerCount(){return Object.keys(this._workerPool).length}}function howManyWorker(e){switch(e){case 1:return 4;case 2:return 6;default:return 8}}const getWorkerManager=function(e=!1){if(!workerManagerInstance){let t=parseInt(process.env.COMPILE_THREADS||"0",10);(t<=0||t>cpus)&&(t=cpus),workerManagerInstance=new WorkerManager(t,e)}return workerManagerInstance};exports.getWorkerManager=getWorkerManager;
|
package/dist/core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.cleanCache=exports.mergeThemeJSONToPageJSON=exports.mergeThemeJSONToAppJSON=exports.schemaValidate=exports.getSiteMapJSON=exports.checkThemeJSON=exports.getPluginPageJSON=exports.getPluginJSON=exports.getGameJSON=exports.compile=exports.compileJS=exports.getPageJSON=exports.getAppJSON=exports.setLocale=exports.setFSAgent=exports.partialAnalyse=void 0;const tslib_1=require("tslib"),index_1=require("./core/compile/index");Object.defineProperty(exports,"compile",{enumerable:!0,get:function(){return index_1.compile}});const app_1=require("./core/json/app"),getPageJSON_1=require("./core/json/page/getPageJSON");Object.defineProperty(exports,"getPageJSON",{enumerable:!0,get:function(){return getPageJSON_1.getPageJSON}});const js_1=require("./core/compile/handler/js");Object.defineProperty(exports,"compileJS",{enumerable:!0,get:function(){return js_1.compileJS}});const plugin_1=require("./core/json/plugin/plugin");Object.defineProperty(exports,"getPluginJSON",{enumerable:!0,get:function(){return plugin_1.getDevPluginJSON}});const plugin_page_1=require("./core/json/plugin/plugin_page");Object.defineProperty(exports,"getPluginPageJSON",{enumerable:!0,get:function(){return plugin_page_1.getPluginPageJSON}});const cache_1=require("./utils/cache"),sitemap_1=require("./core/json/sitemap");Object.defineProperty(exports,"getSiteMapJSON",{enumerable:!0,get:function(){return sitemap_1.getSiteMapJSON}});const theme_1=require("./core/json/theme");Object.defineProperty(exports,"checkThemeJSON",{enumerable:!0,get:function(){return theme_1.checkThemeJSON}}),Object.defineProperty(exports,"mergeThemeJSONToAppJSON",{enumerable:!0,get:function(){return theme_1.mergeThemeJSONToAppJSON}}),Object.defineProperty(exports,"mergeThemeJSONToPageJSON",{enumerable:!0,get:function(){return theme_1.mergeThemeJSONToPageJSON}});const schemaValidate_1=require("./core/validate/schemaValidate");Object.defineProperty(exports,"schemaValidate",{enumerable:!0,get:function(){return schemaValidate_1.schemaValidate}});const reactiveCache_1=require("./core/json/reactiveCache"),fs_1=tslib_1.__importDefault(require("./utils/fs")),locales_1=tslib_1.__importDefault(require("./utils/locales/locales")),game_1=tslib_1.__importDefault(require("./core/json/game"));function setFSAgent(e){fs_1.default.setAgent(e)}async function getAppJSON(e){try{const t=reactiveCache_1.tryToGetReactiveProject(e);return await t.updateProject(),app_1.getAppJSON(e)}catch(e){throw console.error("getAppJSON error",e),e}}async function getGameJSON(e){try{const t=reactiveCache_1.tryToGetReactiveProject(e);return await t.updateProject(),game_1.default(e)}catch(e){throw console.error("getGameJSON error",e),e}}function cleanCache(){cache_1.cacheManager.clean()}exports.partialAnalyse=tslib_1.__importStar(require("./core/analyse/partial")),exports.setFSAgent=setFSAgent,exports.setLocale=locales_1.default.setLocale,exports.getAppJSON=getAppJSON,exports.getGameJSON=getGameJSON,exports.cleanCache=cleanCache;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.cleanCache=exports.mergeThemeJSONToPageJSON=exports.mergeThemeJSONToAppJSON=exports.schemaValidate=exports.getSiteMapJSON=exports.checkThemeJSON=exports.getPluginPageJSON=exports.getPluginJSON=exports.getGameJSON=exports.compile=exports.compileJS=exports.getPageJSON=exports.getAppJSON=exports.setLocale=exports.setFSAgent=exports.partialAnalyse=void 0;const tslib_1=require("tslib"),index_1=require("./core/compile/index");Object.defineProperty(exports,"compile",{enumerable:!0,get:function(){return index_1.compile}});const app_1=require("./core/json/app"),getPageJSON_1=require("./core/json/page/getPageJSON");Object.defineProperty(exports,"getPageJSON",{enumerable:!0,get:function(){return getPageJSON_1.getPageJSON}});const js_1=require("./core/compile/handler/js");Object.defineProperty(exports,"compileJS",{enumerable:!0,get:function(){return js_1.compileJS}});const plugin_1=require("./core/json/plugin/plugin");Object.defineProperty(exports,"getPluginJSON",{enumerable:!0,get:function(){return plugin_1.getDevPluginJSON}});const plugin_page_1=require("./core/json/plugin/plugin_page");Object.defineProperty(exports,"getPluginPageJSON",{enumerable:!0,get:function(){return plugin_page_1.getPluginPageJSON}});const cache_1=require("./utils/cache"),sitemap_1=require("./core/json/sitemap");Object.defineProperty(exports,"getSiteMapJSON",{enumerable:!0,get:function(){return sitemap_1.getSiteMapJSON}});const theme_1=require("./core/json/theme");Object.defineProperty(exports,"checkThemeJSON",{enumerable:!0,get:function(){return theme_1.checkThemeJSON}}),Object.defineProperty(exports,"mergeThemeJSONToAppJSON",{enumerable:!0,get:function(){return theme_1.mergeThemeJSONToAppJSON}}),Object.defineProperty(exports,"mergeThemeJSONToPageJSON",{enumerable:!0,get:function(){return theme_1.mergeThemeJSONToPageJSON}});const schemaValidate_1=require("./core/validate/schemaValidate");Object.defineProperty(exports,"schemaValidate",{enumerable:!0,get:function(){return schemaValidate_1.schemaValidate}});const reactiveCache_1=require("./core/json/reactiveCache"),fs_1=(0,tslib_1.__importDefault)(require("./utils/fs")),locales_1=(0,tslib_1.__importDefault)(require("./utils/locales/locales")),game_1=(0,tslib_1.__importDefault)(require("./core/json/game"));function setFSAgent(e){fs_1.default.setAgent(e)}async function getAppJSON(e){try{const t=(0,reactiveCache_1.tryToGetReactiveProject)(e);return await t.updateProject(),(0,app_1.getAppJSON)(e)}catch(e){throw console.error("getAppJSON error",e),e}}async function getGameJSON(e){try{const t=(0,reactiveCache_1.tryToGetReactiveProject)(e);return await t.updateProject(),(0,game_1.default)(e)}catch(e){throw console.error("getGameJSON error",e),e}}function cleanCache(){cache_1.cacheManager.clean()}exports.partialAnalyse=(0,tslib_1.__importStar)(require("./core/analyse/partial")),exports.setFSAgent=setFSAgent,exports.setLocale=locales_1.default.setLocale,exports.getAppJSON=getAppJSON,exports.getGameJSON=getGameJSON,exports.cleanCache=cleanCache;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.analyseCode=exports.getLatestVersion=exports.uploadJsServer=exports.cloud=exports.getDevSourceMap=exports.proxy=exports.packNpmManually=exports.packNpm=exports.getCompiledResult=exports.preview=exports.upload=exports.Project=void 0;const tslib_1=require("tslib"),project_1=require("./ci/project");Object.defineProperty(exports,"Project",{enumerable:!0,get:function(){return project_1.Project}});const upload_1=require("./ci/upload"),preview_1=require("./ci/preview"),getDevSourceMap_1=require("./ci/getDevSourceMap"),packnpm_1=require("./core/npm/packnpm");Object.defineProperty(exports,"packNpm",{enumerable:!0,get:function(){return packnpm_1.packNpm}}),Object.defineProperty(exports,"packNpmManually",{enumerable:!0,get:function(){return packnpm_1.packNpmManually}});const request_1=require("./utils/request");Object.defineProperty(exports,"proxy",{enumerable:!0,get:function(){return request_1.setCiProxy}});const uploadFunction_1=require("./cloud/uploadFunction"),createTimeTrigger_1=require("./cloud/createTimeTrigger"),uploadContainer_1=require("./cloud/uploadContainer"),uploadFile_1=require("./cloud/uploadFile"),report_1=require("./utils/report"),jsserver_1=require("./ci/jsserver");Object.defineProperty(exports,"uploadJsServer",{enumerable:!0,get:function(){return jsserver_1.uploadJsServer}});const code_analyse_1=require("./ci/code-analyse");Object.defineProperty(exports,"analyseCode",{enumerable:!0,get:function(){return code_analyse_1.analyseCode}});const getCompiledResult_1=require("./ci/getCompiledResult");Object.defineProperty(exports,"getCompiledResult",{enumerable:!0,get:function(){return getCompiledResult_1.getCompiledResult}});const getLatestVersion_1=require("./ci/getLatestVersion");Object.defineProperty(exports,"getLatestVersion",{enumerable:!0,get:function(){return getLatestVersion_1.getLatestVersion}}),exports.upload=report_1.wrapReport("upload",upload_1.upload),exports.preview=report_1.wrapReport("preview",preview_1.preview),exports.getDevSourceMap=report_1.wrapReport("getDevSourceMap",getDevSourceMap_1.getDevSourceMap),exports.cloud={uploadFunction:uploadFunction_1.uploadFunction,createTimeTrigger:createTimeTrigger_1.createTimeTrigger,uploadStaticStorage:e=>uploadFile_1.uploadFiles(e,"staticstorage"),uploadStorage:e=>uploadFile_1.uploadFiles(e,"storage"),uploadContainer:uploadContainer_1.uploadContainer},tslib_1.__exportStar(require("./core"),exports),tslib_1.__exportStar(require("./summer"),exports);
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.analyseCode=exports.getLatestVersion=exports.uploadJsServer=exports.cloud=exports.getDevSourceMap=exports.proxy=exports.packNpmManually=exports.packNpm=exports.getCompiledResult=exports.preview=exports.upload=exports.Project=void 0;const tslib_1=require("tslib"),project_1=require("./ci/project");Object.defineProperty(exports,"Project",{enumerable:!0,get:function(){return project_1.Project}});const upload_1=require("./ci/upload"),preview_1=require("./ci/preview"),getDevSourceMap_1=require("./ci/getDevSourceMap"),packnpm_1=require("./core/npm/packnpm");Object.defineProperty(exports,"packNpm",{enumerable:!0,get:function(){return packnpm_1.packNpm}}),Object.defineProperty(exports,"packNpmManually",{enumerable:!0,get:function(){return packnpm_1.packNpmManually}});const request_1=require("./utils/request");Object.defineProperty(exports,"proxy",{enumerable:!0,get:function(){return request_1.setCiProxy}});const uploadFunction_1=require("./cloud/uploadFunction"),createTimeTrigger_1=require("./cloud/createTimeTrigger"),uploadContainer_1=require("./cloud/uploadContainer"),uploadFile_1=require("./cloud/uploadFile"),report_1=require("./utils/report"),jsserver_1=require("./ci/jsserver");Object.defineProperty(exports,"uploadJsServer",{enumerable:!0,get:function(){return jsserver_1.uploadJsServer}});const code_analyse_1=require("./ci/code-analyse");Object.defineProperty(exports,"analyseCode",{enumerable:!0,get:function(){return code_analyse_1.analyseCode}});const getCompiledResult_1=require("./ci/getCompiledResult");Object.defineProperty(exports,"getCompiledResult",{enumerable:!0,get:function(){return getCompiledResult_1.getCompiledResult}});const getLatestVersion_1=require("./ci/getLatestVersion");Object.defineProperty(exports,"getLatestVersion",{enumerable:!0,get:function(){return getLatestVersion_1.getLatestVersion}}),exports.upload=(0,report_1.wrapReport)("upload",upload_1.upload),exports.preview=(0,report_1.wrapReport)("preview",preview_1.preview),exports.getDevSourceMap=(0,report_1.wrapReport)("getDevSourceMap",getDevSourceMap_1.getDevSourceMap),exports.cloud={uploadFunction:uploadFunction_1.uploadFunction,createTimeTrigger:createTimeTrigger_1.createTimeTrigger,uploadStaticStorage:e=>(0,uploadFile_1.uploadFiles)(e,"staticstorage"),uploadStorage:e=>(0,uploadFile_1.uploadFiles)(e,"storage"),uploadContainer:uploadContainer_1.uploadContainer},(0,tslib_1.__exportStar)(require("./core"),exports),(0,tslib_1.__exportStar)(require("./summer"),exports);
|
package/dist/manifest.json
CHANGED
package/dist/summer/devtool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SummerCompiler=exports.FullPkg=exports.MainPkg=void 0;const tslib_1=require("tslib"),child_process_1=require("child_process"),request_1=require("../utils/request"),path_1=tslib_1.__importDefault(require("path")),lodash_1=tslib_1.__importDefault(require("lodash")),recorder_1=require("./recorder"),tools_1=require("../utils/tools"),uglifyfilenames_1=require("../core/protect/uglifyfilenames"),error_1=require("./error"),miniprogram="miniprogram",plugin="plugin";function performanceMark(e,s){console.warn(`[summer-compiler] [${recorder_1.getPrintTime()}] [${Math.floor(performance.now())}ms elapsed] ${e}${s?" end":""}`)}exports.MainPkg="__APP__",exports.FullPkg="__FULL__";class SummerCompilerProcess{constructor(e,s){this.projectPath=e,this.cachePath=s,this.taskMap=new Map,this.taskId=0,this.initedPromise=new Promise((e,s)=>{this.initedResolve=e,this.initedReject=s})}async init(e,s,t){this.process=this.forkProcess();const r={type:"init",data:Object.assign({projectPath:this.projectPath,cachePath:this.cachePath,files:s,dirs:t},e)};performanceMark("process init"),this.sendProcessMessage(r),performanceMark("process init",!0),await this.initedPromise}destroy(){this.process.kill("SIGTERM")}sendProcessMessage(e){this.process.send(e)}forkProcess(){const e=path_1.default.posix.join(__dirname,"./entry_process.js"),s={stdio:["pipe","pipe","pipe","ipc"],cwd:this.projectPath,env:Object.assign(Object.assign({},process.env),{cpprocessEnv:"childprocess",summerProcess:"1"})};if(s.env.isDevtools=process.__nwjs&&"wechatwebdevtools"===nw.App.manifest.appname,s.env.isDevtools){let e=path_1.default.join(path_1.default.dirname(process.execPath),"node");"darwin"!==process.platform&&(e+=".exe"),s.execPath=e}performanceMark("fork process");const t=child_process_1.fork(e,["--expose-gc"],s);return t.stdout.setEncoding("utf8"),t.stdout.on("data",e=>{}),t.stderr.on("data",e=>{console.error("child process stderr: "+e)}),t.on("exit",e=>{console.error(`child process exit: code(${e})`),0!==e&&this.initedReject(new Error(`summer child process exit: code(${e})`))}),t.on("message",this.onChildProcessMessage.bind(this)),t.unref(),t}onChildProcessMessage(e){if("ready"===e.type)return performanceMark("process ready"),void this.initedResolve(!0);if("progress"===e.type){const s=this.taskMap.get(e.taskId);(null==s?void 0:s.progressUpdate)&&s.progressUpdate(e.id,e.status,e.message)}else if("response"===e.type){const{id:s,data:t,error:r}=e;if(r){const e=new error_1.SummerError(r);this.onResponse(s,void 0,e)}else this.onResponse(s,t,void 0)}}onResponse(e,s,t){const r=this.taskMap.get(e);this.taskMap.delete(e),r?t?r.reject(t):r.resolve(s):console.error(`child process task: ${e} not found`)}async sendEvent(e,s){await this.initedPromise,this.sendProcessMessage({type:"event",name:e,data:s})}async runTask(e,s,t){await this.initedPromise;return new Promise((r,i)=>{const o={name:e,data:s,resolve:r,reject:i,progressUpdate:t};this.taskId=this.taskId+1,this.taskMap.set(this.taskId,o),this.sendProcessMessage({type:"request",id:this.taskId,name:e,data:s})})}}class MessageHub{constructor(e){this.devtoolMessagehub=e,this.showing=new Set}showStatus(e,s){this.showing.add(e),this.devtoolMessagehub.showStatus(e,s)}hideStatus(e){this.showing.delete(e),this.devtoolMessagehub.hideStatus(e)}clear(){for(const e of this.showing.values())this.hideStatus(e);this.showing.clear()}}class SummerCompiler{constructor(e,s,t,r){this.projectPath=e,this.cachePath=s,this.options=t,this.devtoolMessagehub=r,this.isSummer=!0,this.codeCache=new Map,this.promiseCache=new Map,this.status=void 0,this.onProgressUpdate=(e,s,t)=>{"doing"===s?this.messageHub.showStatus(e,t):this.messageHub.hideStatus(e)},this.projectPath=tools_1.normalizePath(this.projectPath),performanceMark("create summer compiler"),this.messageHub=new MessageHub(r),this.process=new SummerCompilerProcess(this.projectPath,this.cachePath)}async init(e,s,t){performanceMark("init summer compiler"),await this.process.init(this.options,e,s),await this.loadStatus(),performanceMark("init summer compiler",!0)}async loadStatus(){var e;this.status=await(null===(e=this.process)||void 0===e?void 0:e.runTask("loadStatus"))}destroy(){this.process.destroy(),this.messageHub.clear()}async clearCache(){var e;await(null===(e=this.process)||void 0===e?void 0:e.runTask("clearCache")),this.codeCache.clear(),this.promiseCache.clear()}updateOptions(e){var s;lodash_1.default.isEqual(e,this.options)||(this.options=e,this.promiseCache.clear(),this.codeCache.clear(),null===(s=this.process)||void 0===s||s.sendEvent("updateOptions",e),this.loadStatus())}fileChange(e,s){if("change"!==e||s.endsWith(".json"))for(const e of this.promiseCache.keys())e.startsWith("getConf-")&&this.promiseCache.delete(e);this.invalidCodeCache(),this.process.sendEvent("fileChange",{type:e,targetPath:s})}invalidCodeCache(){for(const e of this.codeCache.values())e.isValid=!1}async getConf(e){const s="getConf-"+e;if(this.promiseCache.has(s))return console.log(s,"hit cache"),this.promiseCache.get(s);{console.log(s,"do request"),performanceMark("request get conf");const t={graphId:e},r=this.process.runTask("getConf",t,this.onProgressUpdate);return this.promiseCache.set(s,r),performanceMark("request get conf",!0),r}}async getCode(e,s){const t=`getCode-${e}${s?"-"+s.package:""}`;if(this.promiseCache.has(t))return console.log(t,"hit promise cache"),this.promiseCache.get(t);{const r=this.codeCache.get(t);if(null==r?void 0:r.isValid)return r.codeFiles;console.log(t,"do request");const i={};if(r){const e=r.codeFiles;for(const s of Object.keys(e)){const t=e[s];"error"in t||(i[s]=t.md5)}}const o={graphId:e,cacheMd5:i,package:null==s?void 0:s.package};performanceMark("request get code");const a=Date.now();console.time("[summer-compiler] runTask "+t),console.log(`[summer-compiler] [${recorder_1.getPrintTime()}] runTask ${t}`);const n=this.process.runTask("getCode",o,this.onProgressUpdate).then(e=>{var s;console.timeEnd("[summer-compiler] runTask "+t);const r=(null===(s=this.codeCache.get(t))||void 0===s?void 0:s.codeFiles)||{};for(const s of Object.keys(e)){const t=e[s];"error"in t||""!==t.md5?r[s]=t:delete r[s]}return this.codeCache.set(t,{isValid:!0,codeFiles:r}),r},e=>{throw e.code?console.error(e):console.error("Unexpected error when getCode",e),this.messageHub.clear(),e});return n.finally(()=>{performanceMark("request get code",!0),console.log(`[summer-compiler] [${recorder_1.getPrintTime()}] [cost ${Date.now()-a}ms] runTask ${t}`),this.promiseCache.delete(t)}),this.promiseCache.set(t,n),n}}async ready(){return this.process.initedPromise}async getAppJSON(e,s){return(await this.getConf(miniprogram)).app}async getSiteMapJSON(){return(await this.getConf(miniprogram)).sitemap}async getPageJSON(e,s){const t=await this.getConf(miniprogram),r=t.pages[s]||t.comps[s];if(!r)throw new Error("summer-compiler 收集json配置有遗漏, "+s);return r}async getAllPageAndComponentJSON(){const e=await this.getConf(miniprogram);return Object.keys(e.pages).concat(Object.keys(e.comps))}async getAllSortedJSFiles(){const e=await this.getConf(miniprogram),s=Object.keys(e.pages),t=Object.keys(e.comps),r=s.filter(e=>!t.includes(e)).map(e=>e+".js"),i=t.map(e=>e+".js"),o=await this.getCode(miniprogram,{package:exports.FullPkg}),a=Object.keys(o).filter(e=>e.endsWith(".js")&&!r.includes(e)&&!i.includes(e));return{jsPagesFiles:r,components:i,otherJsFiles:a}}async getWxmlAndWxsFiles(e){let s=await this.getCode(miniprogram,{package:e});if(e!==exports.MainPkg){const e=await this.getCode(miniprogram,{package:exports.MainPkg});s=Object.assign(Object.assign({},s),e)}const t=Object.keys(s).filter(e=>e.endsWith(".wxml")),r=Object.keys(s).filter(e=>e.endsWith(".wxs"));return{wxmlFiles:t,wxsFiles:r,content:t.concat(r).reduce((e,t)=>{const r=s[t];if("error"in r)throw r.error;return e[t]=r.code,e["./"+t]=r.code,e},{})}}async getWxssFiles(e){let s=await this.getCode(miniprogram,{package:e});if(e!==exports.MainPkg){const e=await this.getCode(miniprogram,{package:exports.MainPkg});s=Object.assign(Object.assign({},s),e)}const t=Object.keys(s).filter(e=>e.endsWith(".wxss"));return{wxssFiles:t,content:t.reduce((e,t)=>{const r=s[t];if("error"in r)throw r.error;return e[t]=r.code,e["./"+t]=r.code,e},{})}}getWxssMap(e,s){s=tools_1.normalizePath(s);for(const[t,r]of this.codeCache.entries())if(t.startsWith("getCode-"+e)){const e=r.codeFiles[s];if(e&&!("error"in e))return e.map}}async getMainPkgSortedJSFiles(){const e=await this.getConf(miniprogram),s=await this.getCode(miniprogram,{package:"__APP__"}),t=Object.keys(s).filter(e=>e.endsWith(".js")),r=[],i=[],o=[],a=[],n=[];let c=!1;const p={},h=s=>Object.keys(e.packages).find(e=>s.startsWith(e))||exports.MainPkg;e.app.functionalPages&&t.forEach(e=>{if(e.startsWith("functional-pages/")){const s=e.replace(/\.js$/,"");if(p[s])return;p[s]=!0,n.push(encodeURI(s))}}),e.app.workers&&t.forEach(s=>{if(s.startsWith(e.app.workers)){const e=s.replace(/\.js$/,"");if(p[e])return;p[e]=!0,a.push(e)}});Object.keys(e.comps).filter(e=>h(e)===exports.MainPkg).forEach(s=>{if((s.startsWith("miniprogram_npm/weui-miniprogram")||s.startsWith("weui-miniprogram"))&&e.app.useExtendedLib&&e.app.useExtendedLib.weui)return;if(p[s])return;p[s]=!0;const t=encodeURI(s);o.push(""+t)});Object.keys(e.pages).filter(e=>h(e)===exports.MainPkg).forEach(e=>{if(p[e])return;p[e]=!0;const s=encodeURI(e);r.push(""+s)}),t.forEach(e=>{const s=e.replace(/\.js$/,"");p[s]||(p[s]=!0,"app.js"!==e?i.push(""+encodeURI(s)):c=!0)});const l=[...i,...o,...r];return c&&l.push("app"),{hasAppJS:c,allFiles:l,pageFiles:r,componentFiles:o,workerFiles:a,functionalPageFiles:n,otherFiles:i}}async getSubPkgSortedJSFiles(e){const s=await this.getConf(miniprogram),t=await this.getCode(miniprogram,{package:e}),r=Object.keys(t).filter(e=>e.endsWith(".js")),i=[],o=[],a={},n=e=>Object.keys(s.packages).find(s=>e.startsWith(s))||exports.MainPkg;Object.keys(s.comps).filter(s=>n(s)===e).forEach(e=>{if((e.startsWith("miniprogram_npm/weui-miniprogram")||e.startsWith("weui-miniprogram"))&&s.app.useExtendedLib&&s.app.useExtendedLib.weui)return;if(a[e])return;a[e]=!0;const t=encodeURI(e);o.push(""+t)});Object.keys(s.pages).filter(s=>n(s)===e).forEach(e=>{if(a[e])return;a[e]=!0;const s=encodeURI(e);i.push(""+s)});const c=r.map(e=>""+encodeURI(e.replace(/\.js$/,"")));return{allFiles:c,pageFiles:i,componentFiles:o,otherFiles:c.filter(e=>!i.includes(e)&&o.includes(e))}}async compileJS(e,s){let t;if(s.root===e.miniprogramRoot){const e=await this.getConf(miniprogram),r=Object.keys(e.packages).find(e=>s.filePath.startsWith(e))||exports.MainPkg;t=(await this.getCode(miniprogram,{package:r,partialCompilePath:[]}))[s.filePath]}else{t=(await this.getCode(plugin))[s.filePath]}if(!t){const e=new Error(`summer-compiler miss ${s.root} js file, ${s.filePath}`);throw e.code="ENOENT",e}if("error"in t)throw t.error;return Object.assign({filePath:s.filePath,code:t.code,map:t.map},t.jsTag)}async compile(e,s){const t=await this.process.runTask("compile",{},(e,t,r)=>{s.onProgressUpdate({id:e,status:t,message:r})});for(const e of Object.keys(t))"object"==typeof t[e]&&"Buffer"===t[e].type&&(t[e]=Buffer.from(t[e].data));return t}async getPluginJSON(e,s=""){return(await this.getConf(plugin)).plugin}async getPluginPageJSON(e,s){const t=await this.getConf(plugin),r=t.pages[s]||t.comps[s];if(!r)throw new Error("summer-compiler 收集plugin json配置有遗漏, "+s);return r}async getPluginJSFiles(){const e=await this.getCode(plugin);return Object.keys(e).filter(e=>e.endsWith(".js"))}async getPluginComponents(){const e=await this.getConf(plugin),s=new Set(Object.keys(e.pages).concat(Object.keys(e.comps)));return Array.from(s)}async getPluginWxssFiles(){const e=await this.getCode(plugin),s=Object.keys(e).filter(e=>e.endsWith(".wxss"));return{wxssFiles:s,content:s.reduce((s,t)=>{const r=e[t];if("error"in r)throw r.error;return s[t]=r.code,s["./"+t]=r.code,s},{})}}async getPluginWxmlAndWxsFiles(){const e=await this.getCode(plugin),s=Object.keys(e).filter(e=>e.endsWith(".wxml")),t=Object.keys(e).filter(e=>e.endsWith(".wxs"));return{wxmlFiles:s,wxsFiles:t,content:s.concat(t).reduce((s,t)=>{const r=e[t];if("error"in r)throw r.error;return s[t]=r.code,s["./"+t]=r.code,s},{})}}async checkThemeJSON(e,s){return(await this.getConf(miniprogram)).theme}setProxy(e){request_1.setCiProxy(e)}setLocale(e){this.process.runTask("setLocale",e)}async uglifyFileNames(e,s,t){return await uglifyfilenames_1.uglifyFileNames(e,s,t)}async getLocalFileList(){return this.process.runTask("getLocalFileList",miniprogram)}async getPluginLocalFileList(){return this.process.runTask("getLocalFileList",plugin)}async packNpm(e){throw new Error("packNpm not implemented")}async packNpmManually(e){throw new Error("packNpmManually not implemented")}async getGameJSON(e){throw new Error("getGameJSON not implemented")}}exports.SummerCompiler=SummerCompiler;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SummerCompiler=exports.FullPkg=exports.MainPkg=void 0;const tslib_1=require("tslib"),child_process_1=require("child_process"),request_1=require("../utils/request"),path_1=(0,tslib_1.__importDefault)(require("path")),lodash_1=(0,tslib_1.__importDefault)(require("lodash")),recorder_1=require("./recorder"),tools_1=require("../utils/tools"),uglifyfilenames_1=require("../core/protect/uglifyfilenames"),error_1=require("./error"),miniprogram="miniprogram",plugin="plugin";function performanceMark(e,s){console.warn(`[summer-compiler] [${(0,recorder_1.getPrintTime)()}] [${Math.floor(performance.now())}ms elapsed] ${e}${s?" end":""}`)}exports.MainPkg="__APP__",exports.FullPkg="__FULL__";class SummerCompilerProcess{constructor(e,s){this.projectPath=e,this.cachePath=s,this.taskMap=new Map,this.taskId=0,this.initedPromise=new Promise((e,s)=>{this.initedResolve=e,this.initedReject=s})}async init(e,s,t){this.process=this.forkProcess();const r={type:"init",data:Object.assign({projectPath:this.projectPath,cachePath:this.cachePath,files:s,dirs:t},e)};performanceMark("process init"),this.sendProcessMessage(r),performanceMark("process init",!0),await this.initedPromise}destroy(){this.process.kill("SIGTERM")}sendProcessMessage(e){this.process.send(e)}forkProcess(){const e=path_1.default.posix.join(__dirname,"./entry_process.js"),s={stdio:["pipe","pipe","pipe","ipc"],cwd:this.projectPath,env:Object.assign(Object.assign({},process.env),{cpprocessEnv:"childprocess",summerProcess:"1"})};if(s.env.isDevtools=process.__nwjs&&"wechatwebdevtools"===nw.App.manifest.appname,s.env.isDevtools){let e=path_1.default.join(path_1.default.dirname(process.execPath),"node");"darwin"!==process.platform&&(e+=".exe"),s.execPath=e}performanceMark("fork process");const t=(0,child_process_1.fork)(e,["--expose-gc"],s);return t.stdout.setEncoding("utf8"),t.stdout.on("data",e=>{}),t.stderr.on("data",e=>{console.error("child process stderr: "+e)}),t.on("exit",e=>{console.error(`child process exit: code(${e})`),0!==e&&this.initedReject(new Error(`summer child process exit: code(${e})`))}),t.on("message",this.onChildProcessMessage.bind(this)),t.unref(),t}onChildProcessMessage(e){if("ready"===e.type)return performanceMark("process ready"),void this.initedResolve(!0);if("progress"===e.type){const s=this.taskMap.get(e.taskId);(null==s?void 0:s.progressUpdate)&&s.progressUpdate(e.id,e.status,e.message)}else if("response"===e.type){const{id:s,data:t,error:r}=e;if(r){const e=new error_1.SummerError(r);this.onResponse(s,void 0,e)}else this.onResponse(s,t,void 0)}}onResponse(e,s,t){const r=this.taskMap.get(e);this.taskMap.delete(e),r?t?r.reject(t):r.resolve(s):console.error(`child process task: ${e} not found`)}async sendEvent(e,s){await this.initedPromise,this.sendProcessMessage({type:"event",name:e,data:s})}async runTask(e,s,t){await this.initedPromise;return new Promise((r,i)=>{const o={name:e,data:s,resolve:r,reject:i,progressUpdate:t};this.taskId=this.taskId+1,this.taskMap.set(this.taskId,o),this.sendProcessMessage({type:"request",id:this.taskId,name:e,data:s})})}}class MessageHub{constructor(e){this.devtoolMessagehub=e,this.showing=new Set}showStatus(e,s){this.showing.add(e),this.devtoolMessagehub.showStatus(e,s)}hideStatus(e){this.showing.delete(e),this.devtoolMessagehub.hideStatus(e)}clear(){for(const e of this.showing.values())this.hideStatus(e);this.showing.clear()}}class SummerCompiler{constructor(e,s,t,r){this.projectPath=e,this.cachePath=s,this.options=t,this.devtoolMessagehub=r,this.isSummer=!0,this.codeCache=new Map,this.promiseCache=new Map,this.status=void 0,this.onProgressUpdate=(e,s,t)=>{"doing"===s?this.messageHub.showStatus(e,t):this.messageHub.hideStatus(e)},this.projectPath=(0,tools_1.normalizePath)(this.projectPath),performanceMark("create summer compiler"),this.messageHub=new MessageHub(r),this.process=new SummerCompilerProcess(this.projectPath,this.cachePath)}async init(e,s,t){performanceMark("init summer compiler"),await this.process.init(this.options,e,s),await this.loadStatus(),performanceMark("init summer compiler",!0)}async loadStatus(){var e;this.status=await(null===(e=this.process)||void 0===e?void 0:e.runTask("loadStatus"))}destroy(){this.process.destroy(),this.messageHub.clear()}async clearCache(){var e;await(null===(e=this.process)||void 0===e?void 0:e.runTask("clearCache")),this.codeCache.clear(),this.promiseCache.clear()}updateOptions(e){var s;lodash_1.default.isEqual(e,this.options)||(this.options=e,this.promiseCache.clear(),this.codeCache.clear(),null===(s=this.process)||void 0===s||s.sendEvent("updateOptions",e),this.loadStatus())}fileChange(e,s){if("change"!==e||s.endsWith(".json"))for(const e of this.promiseCache.keys())e.startsWith("getConf-")&&this.promiseCache.delete(e);this.invalidCodeCache(),this.process.sendEvent("fileChange",{type:e,targetPath:s})}invalidCodeCache(){for(const e of this.codeCache.values())e.isValid=!1}async getConf(e){const s="getConf-"+e;if(this.promiseCache.has(s))return console.log(s,"hit cache"),this.promiseCache.get(s);{console.log(s,"do request"),performanceMark("request get conf");const t={graphId:e},r=this.process.runTask("getConf",t,this.onProgressUpdate);return this.promiseCache.set(s,r),performanceMark("request get conf",!0),r}}async getCode(e,s){const t=`getCode-${e}${s?"-"+s.package:""}`;if(this.promiseCache.has(t))return console.log(t,"hit promise cache"),this.promiseCache.get(t);{const r=this.codeCache.get(t);if(null==r?void 0:r.isValid)return r.codeFiles;console.log(t,"do request");const i={};if(r){const e=r.codeFiles;for(const s of Object.keys(e)){const t=e[s];"error"in t||(i[s]=t.md5)}}const o={graphId:e,cacheMd5:i,package:null==s?void 0:s.package};performanceMark("request get code");const a=Date.now();console.time("[summer-compiler] runTask "+t),console.log(`[summer-compiler] [${(0,recorder_1.getPrintTime)()}] runTask ${t}`);const n=this.process.runTask("getCode",o,this.onProgressUpdate).then(e=>{var s;console.timeEnd("[summer-compiler] runTask "+t);const r=(null===(s=this.codeCache.get(t))||void 0===s?void 0:s.codeFiles)||{};for(const s of Object.keys(e)){const t=e[s];"error"in t||""!==t.md5?r[s]=t:delete r[s]}return this.codeCache.set(t,{isValid:!0,codeFiles:r}),r},e=>{throw e.code?console.error(e):console.error("Unexpected error when getCode",e),this.messageHub.clear(),e});return n.finally(()=>{performanceMark("request get code",!0),console.log(`[summer-compiler] [${(0,recorder_1.getPrintTime)()}] [cost ${Date.now()-a}ms] runTask ${t}`),this.promiseCache.delete(t)}),this.promiseCache.set(t,n),n}}async ready(){return this.process.initedPromise}async getAppJSON(e,s){return(await this.getConf(miniprogram)).app}async getSiteMapJSON(){return(await this.getConf(miniprogram)).sitemap}async getPageJSON(e,s){const t=await this.getConf(miniprogram),r=t.pages[s]||t.comps[s];if(!r)throw new Error("summer-compiler 收集json配置有遗漏, "+s);return r}async getAllPageAndComponentJSON(){const e=await this.getConf(miniprogram);return Object.keys(e.pages).concat(Object.keys(e.comps))}async getAllSortedJSFiles(){const e=await this.getConf(miniprogram),s=Object.keys(e.pages),t=Object.keys(e.comps),r=s.filter(e=>!t.includes(e)).map(e=>e+".js"),i=t.map(e=>e+".js"),o=await this.getCode(miniprogram,{package:exports.FullPkg}),a=Object.keys(o).filter(e=>e.endsWith(".js")&&"app.js"!==e&&!r.includes(e)&&!i.includes(e));return{jsPagesFiles:r,components:i,otherJsFiles:a}}async getWxmlAndWxsFiles(e){let s=await this.getCode(miniprogram,{package:e});if(e!==exports.MainPkg){const e=await this.getCode(miniprogram,{package:exports.MainPkg});s=Object.assign(Object.assign({},s),e)}const t=Object.keys(s).filter(e=>e.endsWith(".wxml")),r=Object.keys(s).filter(e=>e.endsWith(".wxs"));return{wxmlFiles:t,wxsFiles:r,content:t.concat(r).reduce((e,t)=>{const r=s[t];if("error"in r)throw r.error;return e[t]=r.code,e["./"+t]=r.code,e},{})}}async getWxssFiles(e){let s=await this.getCode(miniprogram,{package:e});if(e!==exports.MainPkg){const e=await this.getCode(miniprogram,{package:exports.MainPkg});s=Object.assign(Object.assign({},s),e)}const t=Object.keys(s).filter(e=>e.endsWith(".wxss"));return{wxssFiles:t,content:t.reduce((e,t)=>{const r=s[t];if("error"in r)throw r.error;return e[t]=r.code,e["./"+t]=r.code,e},{})}}getWxssMap(e,s){s=(0,tools_1.normalizePath)(s);for(const[t,r]of this.codeCache.entries())if(t.startsWith("getCode-"+e)){const e=r.codeFiles[s];if(e&&!("error"in e))return e.map}}async getMainPkgSortedJSFiles(){const e=await this.getConf(miniprogram),s=await this.getCode(miniprogram,{package:"__APP__"}),t=Object.keys(s).filter(e=>e.endsWith(".js")),r=[],i=[],o=[],a=[],n=[];let c=!1;const p={},h=s=>Object.keys(e.packages).find(e=>s.startsWith(e))||exports.MainPkg;e.app.functionalPages&&t.forEach(e=>{if(e.startsWith("functional-pages/")){const s=e.replace(/\.js$/,"");if(p[s])return;p[s]=!0,n.push(encodeURI(s))}}),e.app.workers&&t.forEach(s=>{if(s.startsWith(e.app.workers)){const e=s.replace(/\.js$/,"");if(p[e])return;p[e]=!0,a.push(e)}});Object.keys(e.comps).filter(e=>h(e)===exports.MainPkg).forEach(s=>{if((s.startsWith("miniprogram_npm/weui-miniprogram")||s.startsWith("weui-miniprogram"))&&e.app.useExtendedLib&&e.app.useExtendedLib.weui)return;if(p[s])return;p[s]=!0;const t=encodeURI(s);o.push(""+t)});Object.keys(e.pages).filter(e=>h(e)===exports.MainPkg).forEach(e=>{if(p[e])return;p[e]=!0;const s=encodeURI(e);r.push(""+s)}),t.forEach(e=>{const s=e.replace(/\.js$/,"");p[s]||(p[s]=!0,"app.js"!==e?i.push(""+encodeURI(s)):c=!0)});const l=[...i,...o,...r];return c&&l.push("app"),{hasAppJS:c,allFiles:l,pageFiles:r,componentFiles:o,workerFiles:a,functionalPageFiles:n,otherFiles:i}}async getSubPkgSortedJSFiles(e){const s=await this.getConf(miniprogram),t=await this.getCode(miniprogram,{package:e}),r=Object.keys(t).filter(e=>e.endsWith(".js")),i=[],o=[],a={},n=e=>Object.keys(s.packages).find(s=>e.startsWith(s))||exports.MainPkg;Object.keys(s.comps).filter(s=>n(s)===e).forEach(e=>{if((e.startsWith("miniprogram_npm/weui-miniprogram")||e.startsWith("weui-miniprogram"))&&s.app.useExtendedLib&&s.app.useExtendedLib.weui)return;if(a[e])return;a[e]=!0;const t=encodeURI(e);o.push(""+t)});Object.keys(s.pages).filter(s=>n(s)===e).forEach(e=>{if(a[e])return;a[e]=!0;const s=encodeURI(e);i.push(""+s)});const c=r.map(e=>""+encodeURI(e.replace(/\.js$/,"")));return{allFiles:c,pageFiles:i,componentFiles:o,otherFiles:c.filter(e=>!i.includes(e)&&o.includes(e))}}async compileJS(e,s){let t;if(s.root===e.miniprogramRoot){const e=await this.getConf(miniprogram),r=Object.keys(e.packages).find(e=>s.filePath.startsWith(e))||exports.MainPkg;t=(await this.getCode(miniprogram,{package:r,partialCompilePath:[]}))[s.filePath]}else{t=(await this.getCode(plugin))[s.filePath]}if(!t){const e=new Error(`summer-compiler miss ${s.root} js file, ${s.filePath}`);throw e.code="ENOENT",e}if("error"in t)throw t.error;return Object.assign({filePath:s.filePath,code:t.code,map:t.map},t.jsTag)}async compile(e,s){const t=await this.process.runTask("compile",{},(e,t,r)=>{s.onProgressUpdate({id:e,status:t,message:r})});for(const e of Object.keys(t))"object"==typeof t[e]&&"Buffer"===t[e].type&&(t[e]=Buffer.from(t[e].data));return t}async getPluginJSON(e,s=""){return(await this.getConf(plugin)).plugin}async getPluginPageJSON(e,s){const t=await this.getConf(plugin),r=t.pages[s]||t.comps[s];if(!r)throw new Error("summer-compiler 收集plugin json配置有遗漏, "+s);return r}async getPluginJSFiles(){const e=await this.getCode(plugin);return Object.keys(e).filter(e=>e.endsWith(".js"))}async getPluginComponents(){const e=await this.getConf(plugin),s=new Set(Object.keys(e.pages).concat(Object.keys(e.comps)));return Array.from(s)}async getPluginWxssFiles(){const e=await this.getCode(plugin),s=Object.keys(e).filter(e=>e.endsWith(".wxss"));return{wxssFiles:s,content:s.reduce((s,t)=>{const r=e[t];if("error"in r)throw r.error;return s[t]=r.code,s["./"+t]=r.code,s},{})}}async getPluginWxmlAndWxsFiles(){const e=await this.getCode(plugin),s=Object.keys(e).filter(e=>e.endsWith(".wxml")),t=Object.keys(e).filter(e=>e.endsWith(".wxs"));return{wxmlFiles:s,wxsFiles:t,content:s.concat(t).reduce((s,t)=>{const r=e[t];if("error"in r)throw r.error;return s[t]=r.code,s["./"+t]=r.code,s},{})}}async checkThemeJSON(e,s){return(await this.getConf(miniprogram)).theme}setProxy(e){(0,request_1.setCiProxy)(e)}setLocale(e){this.process.runTask("setLocale",e)}async uglifyFileNames(e,s,t){return await(0,uglifyfilenames_1.uglifyFileNames)(e,s,t)}async getLocalFileList(){return this.process.runTask("getLocalFileList",miniprogram)}async getPluginLocalFileList(){return this.process.runTask("getLocalFileList",plugin)}async packNpm(e){throw new Error("packNpm not implemented")}async packNpmManually(e){throw new Error("packNpmManually not implemented")}async getGameJSON(e){throw new Error("getGameJSON not implemented")}}exports.SummerCompiler=SummerCompiler;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _a;process.env&&process.env.isDevtools&&require("../utils/hackrequire/index"),Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");(null===(_a=process.env)||void 0===_a?void 0:_a.isDevtools)&&require("../utils/hackrequire/index");const project_1=require("./project"),summer_1=require("./summer"),core_1=require("../core"),recorder_1=require("./recorder");let summerCompiler,project;process.on("message",async e=>{if("object"==typeof e)if("init"===e.type){if(summerCompiler)return void console.error("summer compiler has been inited");{const r=e.data,{projectPath:s,cachePath:o,files:t,dirs:i}=r,c=tslib_1.__rest(r,["projectPath","cachePath","files","dirs"]);project=new project_1.Project(s,t,i,c),summerCompiler=new summer_1.SummerCompiler(project,o,c),process.send({type:"ready"})}}else{if(summerCompiler||console.error("summer compiler not inited yet"),"event"===e.type)if("fileChange"===e.name){const{type:r,targetPath:s}=e.data;project.onFileChange(r,s)}else if("updateOptions"===e.name){const r=e.data;project.updateOptions(r),summerCompiler.updateOptions(r)}if("request"===e.type){const{id:r,name:s,data:o}=e,t=r,i=new recorder_1.Recorder((e,r,s)=>{process.send({type:"progress",id:e,taskId:t,status:r,message:s})});try{let e;if("getCode"===s){const{graphId:r,cacheMd5:s,package:t}=o,c=`getCode-${r}${t?"-"+t:""}`,a=await i.run("!"+c,()=>summerCompiler.getCode(o,i));for(const e of Object.keys(s)){const r=a[e];r?"error"in r||r.md5!==s[e]||delete a[e]:a[e]={path:e,md5:"",code:""}}e=a}else if("getConf"===s)e=await summerCompiler.getConf(o,i);else if("getLocalFileList"===s)e=await summerCompiler.getLocalFileList(o);else if("compile"===s)e=await summerCompiler.compile(o,i);else if("compileSingleCode"===s)e=await summerCompiler.compileSingleCode(o,i);else if("setLocale"===s)core_1.setLocale(o);else if("clearCache"===s)summerCompiler.clearCache();else{if("loadStatus"!==s)throw new Error("unknown command "+s);e=summerCompiler.getStatus()}process.send({type:"response",id:r,data:e})}catch(e){process.send({type:"response",id:r,data:null,error:{code:e.code||-1,message:e.message,stack:e.stack,path:e.path||""}})}}}else console.error("child process unrecognized message "+e)}),process.on("disconnect",()=>{try{process.exit(0)}catch(e){process.kill(process.pid,"SIGTERM")}}),process.on("uncaughtException",e=>{console.log(e)});
|
|
1
|
+
var _a;process.env&&process.env.isDevtools&&require("../utils/hackrequire/index"),Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib");(null===(_a=process.env)||void 0===_a?void 0:_a.isDevtools)&&require("../utils/hackrequire/index");const project_1=require("./project"),summer_1=require("./summer"),core_1=require("../core"),recorder_1=require("./recorder");let summerCompiler,project;process.on("message",async e=>{if("object"==typeof e)if("init"===e.type){if(summerCompiler)return void console.error("summer compiler has been inited");{const r=e.data,{projectPath:s,cachePath:o,files:t,dirs:i}=r,c=(0,tslib_1.__rest)(r,["projectPath","cachePath","files","dirs"]);project=new project_1.Project(s,t,i,c),summerCompiler=new summer_1.SummerCompiler(project,o,c),process.send({type:"ready"})}}else{if(summerCompiler||console.error("summer compiler not inited yet"),"event"===e.type)if("fileChange"===e.name){const{type:r,targetPath:s}=e.data;project.onFileChange(r,s)}else if("updateOptions"===e.name){const r=e.data;project.updateOptions(r),summerCompiler.updateOptions(r)}if("request"===e.type){const{id:r,name:s,data:o}=e,t=r,i=new recorder_1.Recorder((e,r,s)=>{process.send({type:"progress",id:e,taskId:t,status:r,message:s})});try{let e;if("getCode"===s){const{graphId:r,cacheMd5:s,package:t}=o,c=`getCode-${r}${t?"-"+t:""}`,a=await i.run("!"+c,()=>summerCompiler.getCode(o,i));for(const e of Object.keys(s)){const r=a[e];r?"error"in r||r.md5!==s[e]||delete a[e]:a[e]={path:e,md5:"",code:""}}e=a}else if("getConf"===s)e=await summerCompiler.getConf(o,i);else if("getLocalFileList"===s)e=await summerCompiler.getLocalFileList(o);else if("compile"===s)e=await summerCompiler.compile(o,i);else if("compileSingleCode"===s)e=await summerCompiler.compileSingleCode(o,i);else if("setLocale"===s)(0,core_1.setLocale)(o);else if("clearCache"===s)summerCompiler.clearCache();else{if("loadStatus"!==s)throw new Error("unknown command "+s);e=summerCompiler.getStatus()}process.send({type:"response",id:r,data:e})}catch(e){process.send({type:"response",id:r,data:null,error:{code:e.code||-1,message:e.message,stack:e.stack,path:e.path||""}})}}}else console.error("child process unrecognized message "+e)}),process.on("disconnect",()=>{try{process.exit(0)}catch(e){process.kill(process.pid,"SIGTERM")}}),process.on("uncaughtException",e=>{console.log(e)});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AppConf=exports.resolvePath=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),core_1=require("../../core"),common_1=require("../../core/json/common"),locales_1=tslib_1.__importDefault(require("../../utils/locales/locales"));function resolvePath(t,o){const e=path_1.default.posix.dirname(t);let s=null;return s=o.startsWith("/")?o.replace(/^\//,""):path_1.default.posix.join(e,o),s}exports.resolvePath=resolvePath;class AppConf{constructor(t,o){this.graph=o,this.packages=new Map,this.pages=new Map,this.comps=new Map,this.onFileChange=(t,o)=>{},this.proxyProject=t.proxyProject,this.proxyProject.addResolver(o.resolver)}destroy(){this.proxyProject.removeResolver(this.graph.resolver)}async build(t){this.resetState(),await this.loadApp(t)}async resetState(){this.app=void 0,this.packages.clear(),this.pages.clear(),this.comps.clear(),this.sitemap=void 0,this.theme=void 0}async loadApp(t){const o=await t.run(locales_1.default.config.SUMMER_COMPILE.format("app.json"),()=>core_1.getAppJSON(this.proxyProject));this.app=o;const e=new Set;for(const t of o.pages)e.add(t);const s=o.subPackages||[];for(const t of s){const o=t.root;this.packages.set(o,t);for(const s of t.pages)e.add(path_1.default.posix.join(o,s))}await t.run(locales_1.default.config.SUMMER_COMPILE_PAGE_JSON.format(e.size),async()=>{var t;for(const[t]of e.entries())await this.loadPage(t);for(const t of Object.values(o.usingComponents||{})){const o=resolvePath("app.json",t);await this.loadComp(o,"app.json")}if(null===(t=o.tabBar)||void 0===t?void 0:t.custom){const t=resolvePath("app.json","custom-tab-bar/index");await this.loadComp(t,"app.json")}}),o.themeLocation&&await t.run(locales_1.default.config.SUMMER_COMPILE.format(o.themeLocation),()=>this.loadTheme(o.themeLocation));const a=o.sitemapLocation||"sitemap.json";await t.run(locales_1.default.config.SUMMER_COMPILE.format(a),()=>this.loadSitemap(a))}async loadPage(t){if(t.startsWith("plugin://"))return;const o=await
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AppConf=exports.resolvePath=void 0;const tslib_1=require("tslib"),path_1=(0,tslib_1.__importDefault)(require("path")),core_1=require("../../core"),common_1=require("../../core/json/common"),locales_1=(0,tslib_1.__importDefault)(require("../../utils/locales/locales"));function resolvePath(t,o){const e=path_1.default.posix.dirname(t);let s=null;return s=o.startsWith("/")?o.replace(/^\//,""):path_1.default.posix.join(e,o),s}exports.resolvePath=resolvePath;class AppConf{constructor(t,o){this.graph=o,this.packages=new Map,this.pages=new Map,this.comps=new Map,this.onFileChange=(t,o)=>{},this.proxyProject=t.proxyProject,this.proxyProject.addResolver(o.resolver)}destroy(){this.proxyProject.removeResolver(this.graph.resolver)}async build(t){this.resetState(),await this.loadApp(t)}async resetState(){this.app=void 0,this.packages.clear(),this.pages.clear(),this.comps.clear(),this.sitemap=void 0,this.theme=void 0}async loadApp(t){const o=await t.run(locales_1.default.config.SUMMER_COMPILE.format("app.json"),()=>(0,core_1.getAppJSON)(this.proxyProject));this.app=o;const e=new Set;for(const t of o.pages)e.add(t);const s=o.subPackages||[];for(const t of s){const o=t.root;this.packages.set(o,t);for(const s of t.pages)e.add(path_1.default.posix.join(o,s))}await t.run(locales_1.default.config.SUMMER_COMPILE_PAGE_JSON.format(e.size),async()=>{var t;for(const[t]of e.entries())await this.loadPage(t);for(const t of Object.values(o.usingComponents||{})){const o=resolvePath("app.json",t);await this.loadComp(o,"app.json")}if(null===(t=o.tabBar)||void 0===t?void 0:t.custom){const t=resolvePath("app.json","custom-tab-bar/index");await this.loadComp(t,"app.json")}}),o.themeLocation&&await t.run(locales_1.default.config.SUMMER_COMPILE.format(o.themeLocation),()=>this.loadTheme(o.themeLocation));const a=o.sitemapLocation||"sitemap.json";await t.run(locales_1.default.config.SUMMER_COMPILE.format(a),()=>this.loadSitemap(a))}async loadPage(t){if(t.startsWith("plugin://"))return;const o=await(0,core_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.graph.root,pagePath:t});this.pages.set(t,o);for(const e of Object.values(o.usingComponents||{})){if(e.startsWith("plugin://"))return;const o=resolvePath(t,e);await this.loadComp(o,t)}}async loadComp(t,o){if(await this.isExtendedLibComp(t,o))return;if(this.comps.has(t))return;const e=await(0,core_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.graph.root,pagePath:t});this.comps.set(t,e);for(const o of Object.values(e.usingComponents||{})){if(o.startsWith("plugin://"))return;const e=resolvePath(t,o);await this.loadComp(e,t)}}async loadSitemap(t){const o=await(0,core_1.getSiteMapJSON)(this.proxyProject);this.sitemap=o}async loadTheme(t){const o=await(0,core_1.checkThemeJSON)(this.proxyProject,{themeLocation:t});this.theme=o}async isExtendedLibComp(t,o){if(t.startsWith("miniprogram_npm/")){const e=(0,common_1.getUseExtendLib)(this.proxyProject,o);if(e.length>0){const o=e.map(t=>"miniprogram_npm/"+t);for(const e of o)if(t.startsWith(e))return!0}}return!1}}exports.AppConf=AppConf;
|