@empjs/cli 4.0.0-alpha.3 → 4.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/346.js +3 -3
- package/dist/script/static.d.ts +18 -0
- package/dist/server/static/createStaticServer.d.ts +2 -0
- package/dist/server/static/types.d.ts +31 -0
- package/dist/static.js +87 -0
- package/dist/types/env.d.ts +12 -1
- package/package.json +3 -3
package/dist/346.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e from"node:module";let t=e.createRequire(import.meta.url);import s,{rspack as i}from"@rspack/core";import{program as o}from"commander";import r from"node:process";import n from"node:fs/promises";import a,{dirname as l}from"node:path";import p,{promisify as h}from"node:util";import c from"node:fs";import{createJiti as m}from"jiti";import u from"path";import*as g from"chalk";import{ip as
|
|
1
|
+
import e from"node:module";let t=e.createRequire(import.meta.url);import s,{rspack as i}from"@rspack/core";import{program as o}from"commander";import r from"node:process";import n from"node:fs/promises";import a,{dirname as l}from"node:path";import p,{promisify as h}from"node:util";import c from"node:fs";import{createJiti as m}from"jiti";import u from"path";import*as g from"chalk";import{ip as d}from"address";import{gateway4sync as f}from"default-gateway";import y from"fs-extra";import v from"@empjs/chain";import{glob as C}from"glob";import b from"html-webpack-plugin";import w from"fs";import{TsCheckerRspackPlugin as O}from"ts-checker-rspack-plugin";import P from"net";import k from"os";import j from"url";import{exec as S}from"node:child_process";import{fileURLToPath as x}from"node:url";var E,$={},N={};function D(e){var t=N[e];if(void 0!==t)return t.exports;var s=N[e]={exports:{}};return $[e](s,s.exports,D),s.exports}D.m=$,D.d=(e,t,s)=>{var i=(t,s)=>{for(var i in t)D.o(t,i)&&!D.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,[s]:t[i]})};i(t,"get"),i(s,"value")},D.add=function(e){Object.assign(D.m,e)};var A=D;D.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),D.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},E={346:0,410:0},D.C=e=>{var t,s,i=e.__rspack_esm_ids,o=e.__webpack_modules__,r=e.__rspack_esm_runtime,n=0;for(t in o)D.o(o,t)&&(D.m[t]=o[t]);for(r&&r(D);n<i.length;n++)s=i[n],D.o(E,s)&&E[s]&&E[s][0](),E[i[n]]=0},D.add({"@rsdoctor/rspack-plugin"(e){e.exports=t("@rsdoctor/rspack-plugin")}});var _={};D.r(_),D.d(_,{chalk:()=>W,color:()=>ea,glob:()=>C,logger:()=>ep,utils:()=>R});var R={};D.r(R),D.d(R,{clearConsole:()=>ev,deepAssign:()=>eC,ensureArray:()=>eb,getLanIp:()=>ef,getPkgVersion:()=>ey,importJsVm:()=>ek,jsonFilter:()=>ew,timeFormat:()=>eP,vCompare:()=>eO});var T=JSON.parse('{"rE":"4.0.0-beta.0"}');function M(e,t={}){let s=e.indexOf("=");if(s<=0)throw Error(`--env-vars 参数必须使用 key=value 格式,当前值为 "${e}"`);let i=e.slice(0,s).trim(),o=e.slice(s+1);if(!i)throw Error(`--env-vars 的 key 不能为空,当前值为 "${e}"`);return t[i]=o,t}function L(e={}){return{...e,clearLog:function(e,t=!0){if(void 0===e)return t;if("boolean"==typeof e)return e;if("string"!=typeof e)return!!e;let s=e.trim().toLowerCase();if(["false","0","no","off"].includes(s))return!1;if(["true","1","yes","on"].includes(s))return!0;throw Error(`布尔参数值无效,当前值为 "${e}"`)}(e.clearLog,!0)}}function U(e){return e.option("-ev, --env-vars <key=value>","定义一个环境变量,可重复传入,例如 -ev API_URL=https://example.com",M,{})}function F(e){return U(e.option("-e, --env <env>","部署环境 dev、test、prod").option("-rd, --doctor","开启 rsdoctor,可通过 debug.rsdoctor 操作").option("-t, --ts","生成类型文件,默认 false").option("-pr, --profile","统计模块消耗").option("-cl, --clearLog <clearLog>","清空日志,默认 true"))}function J(e,t,s){e.command(t,{hidden:!0}).description(s).action(()=>{console.error(`emp ${t} 在 @empjs/cli v4 alpha 中尚未实现。`),process.exitCode=1})}async function H(){o.version(T.rE,"-v, --version").usage("<command> [options]"),o.helpOption("-h, --help","显示帮助"),F(o.command("dev").description("Dev 模式")).option("-H, --hot","是否使用热更新,默认启动").option("-o, --open","是否打开调试页面 默认不打开").action(async e=>{let{default:t}=await import("./dev.js");await t.setup("dev",L(e))}),F(o.command("build").description("Build 模式")).option("-a, --analyze","生成分析报告,默认 false").option("-w, --watch","watch 模式").option("-sv, --serve","watch 模式下启动 serve").action(async e=>{let{default:t}=await import("./build.js");await t.setup("build",L(e))}),U(o.command("serve").description("Server 模式").option("-cl, --clearLog <clearLog>","清空日志,默认 true").option("-e, --env <env>","部署环境 dev、test、prod")).action(async e=>{let{default:t}=await import("./serve.js");await t.setup("serve",L(e))}),o.command("static [root]").description("Static file server for local CDN and dist debugging").option("--host <host>","服务 host,默认 0.0.0.0").option("-p, --port <port>","服务端口,默认随机可用端口").option("--cors","启用 Access-Control-Allow-Origin: *").option("--spa [entry]","启用 SPA fallback,默认 index.html").option("--index <files...>","目录 index 候选文件,按顺序匹配").option("--https","使用 EMP 默认证书启动 HTTPS").option("--cert <cert>","HTTPS cert 文件路径").option("--key <key>","HTTPS key 文件路径").option("--headers <headers...>","追加响应头,格式 key=value").option("--compression <mode>","压缩模式,默认 cloudflare;可设 none 关闭").option("-o, --open","打开浏览器").option("--json","输出 JSON").action(async(e,t)=>{let{runStaticCommand:s}=await import("./static.js");await s(e,t)}),o.command("create <intent>").description("创建 EMP 新项目").option("--dir <dir>","目标目录,默认 emp-app").option("--dry-run","只输出将要生成的文件,不写入磁盘").option("--skip-install","跳过依赖安装").option("--skip-dev","跳过自动启动").option("--skip-verify","跳过自动验证").option("--json","输出 JSON 结果").action(async(e,t)=>{let{runCreateCommand:s}=await import("./create.js");await s(e,t)}),J(o,"dts","拉取 remote 项目的 d.ts"),J(o,"init","初始化 emp 项目"),o.parse(r.argv)}var I=l(x(import.meta.url)),B=x(import.meta.url);let z=function(e){let t=a.resolve(e);for(;;){let e=a.join(t,"package.json");if(c.existsSync(e))try{if("@empjs/cli"===JSON.parse(c.readFileSync(e,"utf8")).name)return t}catch{}let s=a.dirname(t);if(s===t)break;t=s}return a.resolve(I,B).replace(`${a.sep}dist${a.sep}index.js`,"")}(I),V=e=>"function"==typeof e&&"function"==typeof e.hex,W=(e=>{let t=e.default;if(V(t))return t;if(t&&"object"==typeof t){let e=t.default;if(V(e))return e}return e})(g),G=W.hex("#1abc9c"),q=W.hex("#16a085"),K=W.hex("#2ecc71"),Q=W.hex("#27ae60"),X=W.hex("#e74c3c"),Y=W.hex("#c0392b"),Z=W.hex("#f1c40f"),ee=W.hex("#f39c12"),et=W.hex("#3498db"),es=W.hex("#2980b9"),ei=W.hex("#ecf0f1"),eo=W.hex("#fd79a8"),er=W.hex("#e84393"),en=W.hex("#7f8c8d"),ea={lightGreen:G,green:q,lightCyan:K,cyan:Q,lightRed:X,red:Y,yellow:Z,orange:ee,lightBlue:et,blue:es,white:ei,lightMagenta:eo,magenta:er,gray:en};class el{brandName="";fullName="";logLevel="info";isLogTime=!1;setup({brandName:e,logLevel:t,fullName:s}){this.brandName=` [${e}] `,this.fullName=` ${s} `,this.fullName=ea.green.bold(this.fullName),t&&(this.logLevel=t)}time=(...e)=>this.isLogTime&&console.time(...e);timeEnd=(...e)=>this.isLogTime&&console.timeEnd(...e);debug=(...e)=>["debug"].includes(this.logLevel)&&console.log(...e);info=(...e)=>["debug","info"].includes(this.logLevel)&&console.log(...e);warn=(...e)=>["debug","info","warn"].includes(this.logLevel)&&console.warn(...e);error=(...e)=>["debug","info","warn","error"].includes(this.logLevel)&&console.error(...e);blue=e=>{console.log(`${ea.lightBlue(this.brandName)}${ea.blue(` ${e} `)}
|
|
2
2
|
`)};cyan=e=>{console.log(`${ea.lightCyan(this.brandName)}${ea.cyan(` ${e} `)}
|
|
3
3
|
`)};magenta=e=>{console.log(`${ea.lightMagenta(this.brandName)}${ea.magenta(` ${e} `)}
|
|
4
4
|
`)};green=e=>{console.log(`${ea.lightGreen(this.brandName)}${ea.green(` ${e} `)}
|
|
@@ -6,5 +6,5 @@ import e from"node:module";let t=e.createRequire(import.meta.url);import s,{rspa
|
|
|
6
6
|
`)};red=e=>{console.log(`${ea.lightRed(this.brandName)}${ea.red(` ${e} `)}
|
|
7
7
|
`)};sysError=e=>{console.log(`${ea.lightRed(" System Error Tips ")}${ea.red(` ${e} `)}
|
|
8
8
|
`)};link=e=>ea.blue(e);title=e=>{console.log(`${this.fullName}${ea.yellow.underline(`${e}`)}
|
|
9
|
-
`)}}let ep=new el;var eh=S(import.meta.url);let ec=["emp-config.ts","emp-config.js","emp.config.ts","emp.config.js","emp-config.mjs","emp-config.cjs","emp-config.mts","emp-config.cts","emp.config.mjs","emp.config.cjs","emp.config.mts","emp.config.cts"],em=(e=eG.root)=>ec.map(t=>u.resolve(e,t)),eu=m(eh,{interopDefault:!0,fsCache:!0,moduleCache:!0,cacheVersion:M.rE}),eg=async()=>{let e="store.getEmpConfigPath";ep.time(e);try{let e=em(eG.root),t=await Promise.all(e.map(e=>c.promises.access(e).then(()=>!0,()=>!1)));return e.find((e,s)=>t[s])}finally{ep.timeEnd(e)}},ef=async()=>{let e=u.join(eG.root,"tsconfig.json");return await c.promises.access(e).then(()=>!0,()=>!1)||(e=void 0),e},ed=()=>{let e="127.0.0.1";try{let{int:t}=d();return f(t||"")||e}catch(t){return e}},ey=e=>{try{let{version:t}=y.readJSONSync(e);return t}catch(e){return}};function ev(){process.stdout.write("win32"===process.platform?"\x1b[2J\x1b[0f":"\x1b[2J\x1b[3J\x1b[H")}function eC(e,...t){for(let s of t)for(let t in s){let i=s[t],o=e[t];if(Object(i)==i&&Object(o)===o){e[t]=eC(o,i);continue}e[t]=s[t]}return e}let eb=e=>Array.isArray(e)?e:[e],ew=(e={},t=[])=>Object.keys(e).filter(e=>!t.includes(e)).reduce((t,s)=>(t[s]=e[s],t),{}),eO=(e="",t="")=>{let s=e.replace("^","").split("."),i=t.replace("^","").split("."),o=Math.max(s.length,i.length),r=0;for(let e=0;e<o;e++){let t=s.length>e?s[e]:0,o=isNaN(Number(t))?t.charCodeAt():Number(t),n=i.length>e?i[e]:0,a=isNaN(Number(n))?n.charCodeAt():Number(n);if(o<a){r=-1;break}if(o>a){r=1;break}}return r},eP=e=>{let t;if((e/=1e3)<1)return`${1e3*e} ms`;if(e<10){let t,s=e>=.01?2:3;return`${t=e.toFixed(s),W.bold(t)} s`}if(e<60){let t;return`${t=e.toFixed(1),W.bold(t)} s`}let s=e/60;return`${t=s.toFixed(2),W.bold(t)} m`},ek=e=>`data:text/javascript,${e}`,ej={rule:{mjs:"mjs",typescript:"typescript",javascript:"javascript",sourceMap:"sourceMapLoader",inline:"inline",raw:"raw",svg:"svg",image:"image",font:"fonts",svga:"svga",sass:"sass",less:"less",css:"css"},use:{swc:"swc",sourceMap:"sourceMapLoader",sass:"sassLoader",less:"lessLoader"},plugin:{tsCheckerRspackPlugin:"TsCheckerRspackPlugin",bundleAnalyzer:"bundleAnalyzerPlugin",define:"definePlugin",copy:"copyRspackPlugin",progress:"progressPlugin",html:{prefix:"html-plugin-"},rsdoctor:"rsdoctor",sourceMapDevTool:"sourceMapDevTool"},minimizer:{minJs:"minJs",minCss:"minCss"}};class ex{op={};constructor(e={}){this.op=e}async afterGetEmpOptions(){this.op.afterGetEmpOptions&&await this.op.afterGetEmpOptions()}async beforePlugin(){this.op.beforePlugin&&await this.op.beforePlugin()}async afterPlugin(){this.op.afterPlugin&&await this.op.afterPlugin()}async beforeModule(){this.op.beforeModule&&await this.op.beforeModule()}async afterModule(){this.op.afterModule&&await this.op.afterModule()}async beforeEmpPlugin(){this.op.beforeEmpPlugin&&await this.op.beforeEmpPlugin()}async afterEmpPlugin(){this.op.afterEmpPlugin&&await this.op.afterEmpPlugin()}async beforeBuild(){this.op.beforeBuild&&await this.op.beforeBuild()}async afterBuild(){this.op.afterBuild&&await this.op.afterBuild(),this.op.afterBulid&&await this.op.afterBulid()}async afterBulid(){await this.afterBuild()}async beforeDevServe(){this.op.beforeDevServe&&await this.op.beforeDevServe()}async afterDevServe(){this.op.afterDevServe&&await this.op.afterDevServe()}async beforeServe(){this.op.beforeServe&&await this.op.beforeServe()}async afterServe(){this.op.afterServe&&await this.op.afterServe()}}let eS=new class{store;appSrc="src";appEntry="";base="";target=[];assign(e,t){return eC(e,t=t||{})}get isESM(){return 1!==["es3","es5"].indexOf(this.store.empConfig.build.target)&&this.store.empConfig.build.useESM}lifeCycle;async setup(e){this.store=e,await this.syncEmpOptions(),await this.setupEmpOptions(),this.lifeCycle=new ex(this.store.empOptions.lifeCycle),await this.lifeCycle.afterGetEmpOptions(),this.store.empOptions.target?(this.target=this.store.empOptions.target,Array.isArray(this.target)&&!this.target.includes(this.build.target)&&this.target.push(this.build.target)):this.target=["web",this.build.target];let{appSrc:t,base:s,appEntry:i}=this.store.empOptions;t&&(this.appSrc=t),s&&(this.base=s),i&&(this.appEntry=i)}async setupEmpOptions(){await this.store.server.setupOnEmpOptionSync()}async chain(){this.store.empOptions.chain&&await this.store.empOptions.chain(this.store.chain)}async plugins(){let e=[];this.store.empOptions.plugins&&Array.isArray(this.store.empOptions.plugins)&&this.store.empOptions.plugins.length>0&&(this.store.empOptions.plugins.map(t=>{e.push(t.rsConfig(this.store))}),await Promise.all(e))}get debug(){let e=!1;return this.store.cliOptions.doctor&&(e={}),this.assign({loggerLevel:"info",clearLog:!0,progress:!0,showRsconfig:!1,showPerformance:!1,rsdoctor:e,infrastructureLogging:{appendOnly:!0,level:"warn"},newTreeshaking:this.store.empConfig.isESM,devShowAllLog:!1,showScriptDebug:!1,cssChunkingPlugin:!0,nativeWatcher:!0,warnRuleAsWarning:!0},this.store.empOptions.debug)}get build(){let e=this.store.empOptions.build?.staticDir?`${this.store.empOptions.build?.staticDir}/`:"",t={js:this.store.isDev?"cheap-module-source-map":"source-map",css:!1};return this.store.empOptions.build?.sourcemap===!0&&(t.css=!0,t.js=this.store.isDev?"cheap-module-source-map":"source-map"),this.store.empOptions.build?.devtool&&(t.js=this.store.empOptions.build?.devtool),this.assign({outDir:"dist",staticDir:e,assetsDir:"assets",publicDir:"public",chunkIds:this.store.isDev?"named":"deterministic",moduleIds:this.store.isDev?"named":"deterministic",sourcemap:t,minify:!this.store.isDev,minOptions:{},cssminOptions:{},incremental:"advance-silent",lazyCompilation:this.store.isDev,target:"es5",useESM:!1,rspack:{},polyfill:{mode:void 0,entryCdn:void 0,splitChunks:!1,include:[],coreJsFeatures:"stable",externalHelpers:!1,browserslist:this.store.browserslistOptions.default},swcConfig:{},devtool:this.store.isDev?"cheap-module-source-map":"source-map"},{...this.store.empOptions.build,staticDir:e})}get html(){let e=this.store.empOptions.html?.template?{}:{charset:{charset:"utf-8"},"http-equiv":{"http-equiv":"X-UA-Compatible",content:"IE=edge"},viewport:{name:"viewport",content:"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"},keywords:{keywords:""},description:{description:""}};return this.assign({lang:"zh-CN",title:"EMP",inject:"body",minify:!this.store.isDev,scriptLoading:this.isESM?"module":"defer",meta:e,cache:!1!==this.cache,tags:[]},this.store.empOptions.html)}get entries(){return this.store.empOptions.entries?this.store.empOptions.entries:{}}get server(){let e={host:"0.0.0.0",port:8e3,open:"darwin"===process.platform,hot:!0,watchFiles:["src/**/*.html"],static:[{directory:this.store.publicDir,watch:this.store.isDev}],allowedHosts:["all"],historyApiFallback:!0,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"X-Requested-With, content-type, Authorization"}};this.store.empOptions.server?.http2&&(this.store.server.httpsType="h2",delete this.store.empOptions.server.http2);let t=this.assign(e,this.store.empOptions.server),s="0.0.0.0"===t.host||"::"===t.host,{server:i}=this.store;if(this.store.isDev&&s&&i?.ip){let e=t.client??={};if(!e.webSocketURL){let s=i.isHttps?"wss":"ws",o=t.port??i.port??8e3;e.webSocketURL=`${s}://${i.ip}:${o}/ws`}}return t}get css(){return this.assign({sass:{mode:"modern",warnRuleAsWarning:this.store.empConfig.debug.warnRuleAsWarning},less:{lessOptions:{javascriptEnabled:!0,math:"always"}},prifixName:""},this.store.empOptions.css)}get output(){let e=(this.store.isDev,".[contenthash:8]"),t=this.store.isDev?"":".[contenthash:8]",{assetsDir:s,staticDir:i}=this.store.empConfig.build,o={publicPath:this.store.empConfig.base?this.store.empConfig.base:"auto",crossOriginLoading:"anonymous",filename:`${i}js/[name]${e}.js`,cssFilename:`${i}css/[name]${t}.css`,cssChunkFilename:`${i}css/[name]${t}.css`,assetModuleFilename:`${i}${s}/[name]${e}[ext][query]`,path:this.store.outDir,clean:!this.store.isDev,uniqueName:this.store.uniqueName},r=this.assign(o,this.store.empOptions.output);if(this.store.empConfig.isESM){let e=r.library&&"object"==typeof r.library&&!Array.isArray(r.library)?r.library:{};r.module=!0,r.library=this.assign({type:"modern-module",preserveModules:this.store.resolve(this.store.empConfig.appSrc)},e)}return r}get define(){let e={mode:this.store.mode,env:this.store.cliOptions.env};return this.store.empOptions.define&&(e={...e,...this.store.empOptions.define}),this.setDefine(e)}get tsCheckerRspackPlugin(){let e={};return!!this.store.empOptions.tsCheckerRspackPlugin&&("object"==typeof this.store.empOptions.tsCheckerRspackPlugin&&(e=this.store.empOptions.tsCheckerRspackPlugin),this.assign({},e))}setDefine(e){let t=this.store.empOptions.defineFix?this.store.empOptions.defineFix:this.isESM?"esm":"cjs",s={};return Object.keys(e).map(i=>{"all"===t?(s[`import.meta.env.${i}`]=JSON.stringify(e[i]),s[`process.env.${i}`]=JSON.stringify(e[i])):"esm"===t?s[`import.meta.env.${i}`]=JSON.stringify(e[i]):"cjs"===t?s[`process.env.${i}`]=JSON.stringify(e[i]):"none"===t&&(s[`${i}`]=JSON.stringify(e[i]))}),s}get externals(){return this.assign({},this.store.empOptions.externals)}get resolve(){return eC({alias:{src:this.store.resolve("src"),"@":this.store.resolve("src")},extensions:["...",".js",".jsx",".mjs",".ts",".tsx",".css",".less",".scss",".sass",".json",".wasm",".vue",".svg",".svga"]},this.store.empOptions.resolve)}async syncEmpOptions(){let e="store.jiti.loadConfig.empConfig";ep.time(e);try{if(!this.store.rootPaths.empConfig){this.store.empOptions={};return}let{default:e}=await eu(this.store.rootPaths.empConfig);"function"==typeof e?this.store.empOptions=await e(this.store):this.store.empOptions=e||{}}finally{ep.timeEnd(e)}}get moduleTransformRule(){let{moduleTransform:e}=this.store.empOptions,t=this.assign({defaultExclude:!1},e),s={and:[],not:[]};return!0===t.defaultExclude&&s.and.push(/(node_modules|bower_components)/),t?.exclude&&(s.and=s.and.concat(t.exclude)),e?.include&&(s.not=t.include),s}get cacheDir(){return this.store.empOptions.cacheDir?this.store.empOptions.cacheDir:"node_modules/.emp-cache"}get cache(){return!1!==this.store.empOptions.cache&&(this.store.empOptions.cache?this.store.empOptions.cache:"persistent")}get ignoreWarnings(){return this.store.empOptions.ignoreWarnings?this.store.empOptions.ignoreWarnings:[/Conflicting order/]}get autoPages(){let e;return this.store.empOptions.autoPages&&(e="boolean"==typeof this.store.empOptions.autoPages?{}:this.store.empOptions.autoPages,e=this.assign({path:"pages"},e)),e}showLogTitle(e){this.store.empOptions.showLogTitle?this.store.empOptions.showLogTitle(e):ep.title(`${e.cliAction}`)}},e$=new class{store;async setup(e){this.store=e;let t=[this.common(),this.stats(),this.devServer(),this.optimization(),this.checkTsconfig()];await Promise.all(t)}get cache(){let e;if(!1===this.store.empConfig.cache)return!1;let t={type:"persistent"===this.store.empConfig.cache?"persistent":"memory",buildDependencies:(e=[eh],eG.rootPaths.pkg&&e.push(eG.rootPaths.pkg),eG.rootPaths.empConfig&&e.push(eG.rootPaths.empConfig),eG.rootPaths.tsConfig&&e.push(eG.rootPaths.tsConfig),e),version:this.store.empConfig.server.port?`${this.store.empPkg.version}_${this.store.empConfig.server.port}`:this.store.empPkg.version};return"object"==typeof this.store.empConfig.cache&&(t=this.store.deepAssign(t,this.store.empConfig.cache)),t}get name(){let e=this.store.empConfig.server.port?`_${this.store.empConfig.server.port}`:"";return this.store.pkg.name+e}async common(){this.store.merge({name:this.name,node:{global:!0},experiments:{nativeWatcher:this.store.empConfig.debug.nativeWatcher,asyncWebAssembly:!0,...this.store.empConfig.build.rspack.experiments},incremental:this.store.empConfig.build.incremental,lazyCompilation:this.store.empConfig.build.lazyCompilation,target:this.store.empConfig.target,infrastructureLogging:this.store.empConfig.debug.infrastructureLogging,context:this.store.root,mode:this.store.mode,cache:this.cache,devtool:this.store.empConfig.build.sourcemap.js,output:{...this.store.empConfig.output,bundlerInfo:{force:!1},module:this.store.empConfig.output.module||this.store.empConfig.isESM},resolve:this.store.empConfig.resolve,externals:this.store.empConfig.externals,ignoreWarnings:this.store.empConfig.ignoreWarnings,watchOptions:{ignored:["**/node_modules/**","**/@mf-types/**"]}})}async checkTsconfig(){let e=this.store.resolve("tsconfig.json");if(await y.exists(e)){let t={};this.store.isOldRspack?t.tsConfigPath=e:t.tsConfig=e,this.store.merge({resolve:t})}}async stats(){this.store.merge({stats:{colors:!0,all:!1,assets:!1,chunks:!1,timings:!0,version:!0}})}async devServer(){this.store.merge({devServer:this.store.empConfig.server})}async optimization(){let e={moduleIds:this.store.empConfig.build.moduleIds,chunkIds:this.store.empConfig.build.chunkIds,minimize:this.store.empConfig.build.minify,splitChunks:this.store.deepAssign({chunks:"async",cacheGroups:{}},this.store.empConfig.build.rspack.splitChunks)};"entry"===this.store.empConfig.build.polyfill.mode&&this.store.empConfig.build.polyfill.splitChunks&&!this.store.empConfig.build.polyfill.entryCdn&&(e.splitChunks.cacheGroups.coreJs={test:/[\\/]node_modules[\\/](core-js)[\\/]/,name:"coreJs",chunks:"all",enforce:!0}),this.store.chain.merge({optimization:e})}},eE=new class{store;async setup(e){this.store=e;let t=[this.sass(),this.less(),this.css()];await Promise.all(t)}async sass(){let{rule:e,use:s}=this.store.chainName,i={},{sass:o}=this.store.empConfig.css;"modern"===o.mode&&(i.implementation=o.implementation?o.implementation:t.resolve("sass-embedded"),i.api="modern-compiler",i.sourceMap=this.store.empConfig.build.sourcemap.css,o.sassOptions&&(i.sassOptions=o.sassOptions)),void 0!==o.additionalData&&(i.additionalData=o.additionalData),void 0!==o.warnRuleAsWarning&&(i.warnRuleAsWarning=o.warnRuleAsWarning),void 0!==o.webpackImporter&&(i.webpackImporter=o.webpackImporter),this.store.chain.merge({module:{rule:{[e.sass]:{test:/\.(sass|scss)$/,use:{[s.sass]:{loader:t.resolve("sass-loader"),options:i}},type:"css/auto"}}}})}async less(){let{rule:e,use:s}=this.store.chainName,{lessOptions:i}=this.store.empConfig.css.less,o={loader:t.resolve("less-loader"),options:{lessOptions:i}};this.store.chain.merge({module:{rule:{[e.less]:{test:/\.less$/,use:{[s.less]:o},type:"css/auto"}}}})}async css(){let{rule:e}=this.store.chainName;this.store.chain.merge({module:{rule:{[e.css]:{test:/\.css$/,use:{},type:"css/auto"}}}})}};class eN{apply(e){let{webpack:t}=e;eG.empConfig.build.polyfill.entryCdn||new t.EntryPlugin(e.context,ek(`import 'core-js/${eG.empConfig.build.polyfill.coreJsFeatures}'`),{name:void 0}).apply(e)}}class eD{PluginName="HtmlEmpInjectPlugin";chunk="";files=[];constructor(e,t="",s=""){this.PluginName=`${this.PluginName}-${t}`,this.files=e,this.chunk=s}apply(e){e.hooks.compilation.tap(this.PluginName,e=>{b.getHooks(e).alterAssetTagGroups.tapPromise(this.PluginName,async e=>(this.chunk&&!e.plugin.userOptions.chunks?.includes(this.chunk)||this.files.map(t=>{let{pos:s,...i}=t;("body"===s?e.bodyTags:e.headTags).push({attributes:{},voidTag:!1,meta:{plugin:void 0},tagName:"script",...i})}),e))})}}let eA=new class{store;entriesConfig={};async setup(e){this.store=e,await this.init(),this.toConfig()}setHtmlConfig(e,t){return e.template=this.setTemplate(e.template),e.favicon=this.setFavicion(e.favicon),e.chunks=t,e.filename=`${t[0]}.html`,this.store.empConfig.base&&(e.publicPath=this.store.empConfig.base),this.prepareAndSetAsset(e),e}prepareAndSetAsset(e){let t=e.chunks?e.chunks[0]:void 0;this.store.injectTags(e.tags,t?`injectTags-${t}`:"injectTags",t),delete e.tags}injectPolyfill(){if(!this.store.empConfig.build.polyfill.entryCdn)return;let e=[{attributes:{src:this.store.empConfig.build.polyfill.entryCdn},tagName:"script",pos:"head"}];this.store.injectTags(e,"injectEMPPolyfill")}setChunk(e){return e.replace(a.extname(e),"").replace(`${this.store.empConfig.appSrc}${a.sep}`,"")}setTemplate(e){return e?this.store.resolve(e):this.store.empResolve(a.join("template","index.html"))}setFavicion(e){if(""!==e)return e?this.store.resolve(e):this.store.empResolve(a.join("template","favicon.ico"))}setEntryItem(e,t,s){s=s||this.store.resolve(a.join(this.store.empConfig.appSrc,e));let i=this.setChunk(e),o=[s];this.entriesConfig[i]={entry:{[i]:o},html:this.setHtmlConfig(t,[i])},this.store.entries[i]=o}setRspackHtmlPlugin(e,t){this.store.chain.plugin(`${this.store.chainName.plugin.html.prefix}${t}`).use(b,[e])}setRspackEntry(e){this.store.merge({entry:e})}async init(){this.injectPolyfill(),this.store.empConfig.autoPages?await this.setAutoPage():(await this.setDefaultEntry(),this.setEntryByConfig())}async setAutoPage(){ep.time("setAutoPage");let e=this.store.empConfig.autoPages?.path||"pages",t=a.join(this.store.appSrc,e),s=a.join(t,"**","*.{ts,tsx,jsx,js}"),i=await C([s],{windowsPathsNoEscape:!0});(i=i.map(e=>e.replace(`${t}${a.sep}`,""))).map(e=>{let s=this.store.empConfig.entries[e]||{};this.setEntryItem(e,{...this.store.empConfig.html,...s},a.join(t,e))}),ep.timeEnd("setAutoPage")}async setDefaultEntry(){let e="store.empConfig.setDefaultEntry";ep.time(e);let t=a.join(this.store.appSrc,this.store.empConfig.appEntry?this.store.empConfig.appEntry:"index.{ts,tsx,jsx,js}"),s=await C([t],{windowsPathsNoEscape:!0});if(s[0]){let e=a.join(this.store.empConfig.appSrc,Object.keys(this.store.empConfig.entries).length>0&&this.store.empConfig.appEntry?this.store.empConfig.appEntry:"index");this.setEntryItem(e,this.store.empConfig.html,s[0])}ep.timeEnd(e)}setEntryByConfig(){if(Object.keys(this.store.empConfig.entries).length>0)for(let[e,t]of Object.entries(this.store.empConfig.entries))this.setEntryItem(e,{...this.store.empConfig.html,...t})}toConfig(){for(let[e,t]of Object.entries(this.entriesConfig))this.setRspackHtmlPlugin(t.html,e),this.setRspackEntry(t.entry)}},e_=new class{store;swcJsOptions={};swcTsOptions={};coreJs={version:"3",alias:"",path:""};async setup(e){this.store=e,this.swcInitOptions(),await this.run()}async run(){let e=[this.jsDataUrl(),this.files(),this.scripts(),this.rspackGenerator(),this.rspackParser()];await this.store.empConfig.lifeCycle.beforeModule(),await Promise.all(e),await this.store.empConfig.lifeCycle.afterModule()}rspackGenerator(){let e=this.store.empConfig.css?.prifixName?`${this.store.empConfig.css?.prifixName}-`:"",t=this.store.isDev?`${e}[id]-[local]-[hash:base64:8]`:`${e}[local]-[hash:5]`;this.store.chain.merge({module:{generator:{"css/auto":{exportsConvention:"as-is",exportsOnly:!1,localIdentName:t,esModule:!0},css:{exportsOnly:!1,esModule:!0},"css/module":{exportsConvention:"as-is",exportsOnly:!1,localIdentName:t,esModule:!0},json:{JSONParse:!0}}}})}rspackParser(){let e=this.store.empConfig.build.rspack.parser,t={namedExports:!1,...e?.css};this.store.chain.merge({module:{parser:{javascript:{dynamicImportMode:"lazy",dynamicImportPrefetch:!1,dynamicImportPreload:!1,url:!0,importMeta:!0,...e?.javascript},css:t,"css/auto":t,"css/module":t}}})}get isPolyfill(){return!!this.store.empConfig.build.polyfill.mode}swcParser(e){switch(e){case"js":return{syntax:"ecmascript",jsx:!0,decorators:!0,decoratorsBeforeExport:!1};case"ts":return{syntax:"typescript",decorators:!0,tsx:!0,dynamicImport:!0}}}swcJsc(e){let{target:t,polyfill:s}=this.store.empConfig.build,{externalHelpers:i}=s;return{parser:this.swcParser(e),transform:{},target:t,externalHelpers:i,preserveAllComments:!0}}get swcCoreVersion(){let[e,t]=this.coreJs.version.split(".");return`${e}.${t}`}swcOptions(e){let t=this.store.empConfig.build.rspack.swc,s={jsc:eC(this.swcJsc(e),{...this.store.empConfig.build.swcConfig}),isModule:"unknown"};return t?.detectSyntax!==void 0&&(s.detectSyntax=t.detectSyntax,"auto"===t.detectSyntax&&delete s.jsc.parser),t?.transformImport&&(s.transformImport=t.transformImport),this.isPolyfill&&(delete s.jsc.target,s.env={coreJs:this.swcCoreVersion,targets:this.store.empConfig.build.polyfill.browserslist},this.store.empConfig.isESM||(s.env.mode=this.store.empConfig.build.polyfill.mode),"usage"===this.store.empConfig.build.polyfill.mode&&(s.env.shippedProposals=!0,s.env.include=this.store.empConfig.build.polyfill.include)),s}swcInitOptions(){let{externalHelpers:e}=this.store.empConfig.build.polyfill;e&&this.store.chain.resolve.alias.set("@swc/helpers",a.dirname(t.resolve("@swc/helpers/package.json"))),this.coreJs.path=t.resolve("core-js/package.json");let s=ey(this.coreJs.path);s&&(this.coreJs.version=s),this.coreJs.alias=a.dirname(this.coreJs.path),this.store.empConfig.build.polyfill.mode&&(this.store.chain.resolve.alias.set("core-js",this.coreJs.alias),this.store.chain.module.rule("javascript").exclude.add(/core-js/),this.store.chain.module.rule("typescript").exclude.add(/core-js/)),this.swcTsOptions=this.swcOptions("ts"),this.swcJsOptions=this.swcOptions("js")}jsDataUrl(){this.store.chain.module.rule("jsDataUrl").merge({mimetype:{or:["text/javascript","application/javascript"]}}).resolve.set("fullySpecified",!1).end().use("swcJsParser").loader("builtin:swc-loader").options(this.swcJsOptions)}async scripts(){let e=[],{rule:t,use:s}=this.store.chainName;this.store.chain.merge({module:{parser:{javascript:{exportsPresence:"error",importExportsPresence:"error"}},rule:{[t.mjs]:{test:/\.m?js/,resolve:{fullySpecified:!1}},[t.typescript]:{test:/\.(ts|tsx)$/,exclude:e,use:{[s.swc]:{loader:"builtin:swc-loader",options:this.swcTsOptions}}},[t.javascript]:{test:/\.((m|c)?js|jsx)$/,exclude:e,use:{[s.swc]:{loader:"builtin:swc-loader",options:this.swcJsOptions}}}}}})}async files(){let{rule:e}=this.store.chainName;this.store.chain.merge({module:{rule:{[e.svg]:{test:/\.svg$/,type:"asset/resource"}}}}),this.store.chain.merge({module:{rule:{[e.inline]:{resourceQuery:/inline/,type:"asset/inline"}}}}),this.store.chain.merge({module:{rule:{[e.raw]:{resourceQuery:/raw/,type:"asset/source"}}}}),this.store.chain.merge({module:{rule:{[e.image]:{test:/\.(png|jpe?g|gif|webp|ico)$/i,type:"asset/resource"},[e.font]:{test:/\.(|otf|ttf|eot|woff|woff2)$/i,type:"asset/resource"},[e.svga]:{test:/\.(svga)$/i,type:"asset/resource"}}}})}},eR=new class{store;async setup(e){this.store=e,this.beforeLifeCycle(),await this.store.empConfig.lifeCycle.beforePlugin(),await this.define(),await this.anylayze(),await this.progress(),await this.copy(),this.minify(),this.redoctor(),this.sourceMapDevToolPlugin(),this.tsCheckerRspackPlugin(),this.cssChunkingPlugin(),await this.store.empConfig.lifeCycle.afterPlugin()}beforeLifeCycle(){let{store:e}=this;"entry"===e.empConfig.build.polyfill.mode&&e.chain.plugin("empPolyfill").use(eN)}async anylayze(){if(!this.store.cliOptions.analyze)return;let{default:{BundleAnalyzerPlugin:e}}=await import("webpack-bundle-analyzer");this.store.chain.plugin(this.store.chainName.plugin.bundleAnalyzer).use(e,[{analyzerPort:this.store.empConfig.server.port,defaultSizes:"gzip",analyzerHost:this.store.getLanIp()||"127.0.0.1"}])}tsCheckerRspackPlugin(){if(!1===this.store.empConfig.tsCheckerRspackPlugin)return!1;this.store.chain.plugin(this.store.chainName.plugin.tsCheckerRspackPlugin).use(O,[this.store.empConfig.tsCheckerRspackPlugin])}async define(){this.store.chain.plugin(this.store.chainName.plugin.define).use(s.DefinePlugin,[this.store.empConfig.define])}async copy(){let e=this.store.resolve("public");w.existsSync(e)&&w.readdirSync(e).length>0&&this.store.chain.plugin(this.store.chainName.plugin.copy).use(s.CopyRspackPlugin,[{patterns:[{from:e,to:this.store.resolve(this.store.empConfig.build.outDir),noErrorOnMissing:!0,globOptions:{ignore:["**/.DS_Store"]}}]}])}async progress(){if("development"===this.store.mode)return;let e={};this.store.isOldRspack||(e={template:"{bar:25.green/white}{spinner:.green}{percent}% {wide_msg:.dim}",tick:void 0,progressChars:"▩▩"}),this.store.chain.plugin(this.store.chainName.plugin.progress).use(s.ProgressPlugin,[e])}minify(){this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minJs).use(s.SwcJsMinimizerRspackPlugin,[this.store.empConfig.build.minOptions]);let{SwcCssMinimizerRspackPlugin:e,LightningCssMinimizerRspackPlugin:t}=s;e?this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minCss).use(e,[this.store.empConfig.build.cssminOptions]):t&&this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minCss).use(t,[this.store.empConfig.build.cssminOptions])}redoctor(){if(!this.store.empConfig.debug.rsdoctor)return;let{RsdoctorRspackPlugin:e}=D("@rsdoctor/rspack-plugin"),t={};"object"==typeof this.store.empConfig.debug.rsdoctor&&(t=this.store.empConfig.debug.rsdoctor),this.store.chain.plugin(this.store.chainName.plugin.rsdoctor).use(e,[t])}sourceMapDevToolPlugin(){"object"==typeof this.store.empConfig.build.sourcemap&&this.store.empConfig.build.sourcemap?.devToolPluginOptions&&this.store.chain.plugin(this.store.chainName.plugin.sourceMapDevTool).use(s.SourceMapDevToolPlugin,[this.store.empConfig.build.sourcemap.devToolPluginOptions])}circularDependency(){this.store.chain.plugin("circularDependency").use(s.CircularDependencyRspackPlugin,[{}])}cssChunkingPlugin(){let e=!0===this.store.empConfig.debug.cssChunkingPlugin?{}:this.store.empConfig.debug.cssChunkingPlugin;e&&this.store.chain.plugin("CssChunkingPlugin").use(s.experiments.CssChunkingPlugin,[e])}},eM=new class{store;async setup(e){this.store=e;let t=[e$.setup(this.store),e_.setup(this.store),eR.setup(this.store),eA.setup(this.store),eE.setup(this.store)];await Promise.all(t),await this.store.empConfig.lifeCycle.beforeEmpPlugin(),await this.store.empConfig.plugins(),await this.store.empConfig.lifeCycle.afterEmpPlugin(),await this.store.empConfig.chain()}},eT=(e,t)=>new Promise((s,i)=>{let o=P.createServer();o.unref(),o.on("error",i),o.listen(e,t,()=>{let{port:e}=o.address();o.close(()=>{s(e)})})}),eL=async(e,t)=>{let s=new Set(["EADDRNOTAVAIL","EINVAL"]);for(let i of t)try{await eT(e,i)}catch(e){if(!s.has(e.code))throw e}return e};async function eU(e,t){let s;if(443!==e&&(e<1024||e>65535))throw Error("Port number must lie between 1024 and 65535");let i=e,o=(()=>{let e=k.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let s of Object.values(e))if(s)for(let e of s)t.add(e.address);return t})();s=t&&!o.has(t)?new Set([t]):o;let r=new Set(["EADDRINUSE","EACCES"]);for(;i<=65535;)try{return await eL(i,s)}catch(e){if(!r.has(e.code))throw e;i+=1}throw Error("No available ports found")}class eF{imf={protocol:"",port:8e3,pathname:"/"};host="0.0.0.0";urls={lanUrlForConfig:"",lanUrlForTerminal:en("unavailable"),localUrlForTerminal:"",localUrlForBrowser:""};setup(e){e.host&&(this.host=e.host),e.protocol&&(this.imf.protocol=e.protocol),e.pathname&&(this.imf.pathname=e.pathname),e.port&&(this.imf.port=e.port),this.setupUrls()}setupUrls(){let e,{host:t}=this;if("0.0.0.0"===t||"::"===t){e="localhost";try{this.urls.lanUrlForConfig=this.getLanIp(),this.urls.lanUrlForConfig&&(/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(this.urls.lanUrlForConfig)?this.urls.lanUrlForTerminal=this.prettyPrintUrl(this.urls.lanUrlForConfig):this.urls.lanUrlForConfig="")}catch(e){}}else e=t,this.urls.lanUrlForConfig=t,this.urls.lanUrlForTerminal=this.prettyPrintUrl(this.urls.lanUrlForConfig);this.urls.localUrlForTerminal=this.prettyPrintUrl(e),this.urls.localUrlForBrowser=this.formatUrl(e)}getLanIp=ed;formatUrl(e){let{protocol:t,port:s,pathname:i}=this.imf;return j.format({protocol:t,hostname:e,port:s,pathname:i})}prettyPrintUrl(e){let{protocol:t,port:s,pathname:i}=this.imf;return j.format({protocol:t,hostname:e,port:W.bold(s),pathname:i})}}let eJ=new eF,eI=h(x),eB=["Google Chrome Canary","Google Chrome Dev","Google Chrome Beta","Google Chrome","Microsoft Edge","Brave Browser","Vivaldi","Chromium"],eH=async()=>{let e=process.env.BROWSER;if(!e||!eB.includes(e)){let{stdout:t}=await eI("ps cax");e=eB.find(e=>t.includes(e))}return e},ez=async e=>{if("darwin"===process.platform)try{let t=await eH();if(t){let s=`osascript openChrome.applescript "${encodeURI(e)}" "${t}"`;return await eI(s,{cwd:eG.resource.dir}),!0}}catch(e){ep.debug(e)}try{let{default:t}=await import("open");return await t(e),!0}catch(e){return ep.error("Failed to open start URL."),ep.error(e),!1}};class eV{ip=ed();host=this.ip;isAutoDevBase=!1;isHttps=!1;httpsType="default";protocol="http";port=8e3;store;publicPath="/";publicHasHttp=!1;isOpenBrower=!1;url="";urls={localUrlForBrowser:"",localUrlForTerminal:"",lanUrlForTerminal:"",lanUrlForConfig:""};constructor(e){this.store=e}async setupOnEmpOptionSync(){"build"!==this.store.cliAction&&(this.port=await eU(this.port),this.setHttps(),await this.setAutoDevBase())}get config(){return{}}async setupOnStore(){if("build"===this.store.cliAction)return;let{store:e}=this;this.publicPath=e.rsConfig.output?.publicPath==="auto"?"/":e.rsConfig.output?.publicPath||"/",this.isOpenBrower=!!e.empConfig.server.open,this.protocol=this.isHttps?"https":"http",this.host=e.empConfig.server.host?e.empConfig.server.host:this.ip,e.empConfig.server.port&&e.empConfig.server.port!==this.port&&(this.port=await eU(e.empConfig.server.port)),eJ.setup(this),this.publicPath&&(this.publicPath.indexOf("http://")>-1||this.publicPath.indexOf("https://")>-1)?(this.url=this.publicPath,this.publicHasHttp=!0,this.urls.localUrlForTerminal=eJ.prettyPrintUrl("localhost")):(this.urls=eJ.urls,this.url=this.urls.localUrlForBrowser)}startOpen(){let{urls:e}=this;this.publicHasHttp?(ep.info(`${q("➜")} Local: ${ep.link(e.localUrlForTerminal)}`),ep.info(`${q("➜")} Network: ${ep.link(this.publicPath)}`)):(ep.info(`${q("➜")} Local: ${ep.link(e.localUrlForTerminal)}`),ep.info(`${q("➜")} Network: ${ep.link(e.lanUrlForTerminal)}
|
|
10
|
-
`)),this.isOpenBrower&&ez(this.url)}async getcert(){let{store:e}=this,t=this.store.rsConfig.devServer||{server:{type:"http"}};if("object"==typeof t.server&&"https"===t.server.type&&t.server.options&&t.server.options.key&&t.server.options.cert)return t.server.options;let[s,i]=await Promise.all([n.readFile(e.resource.key),n.readFile(e.resource.cert)]);return{key:s,cert:i}}setHttps(){let{store:e}=this,{server:t,https:s}=e.empOptions.server||{};this.isHttps="https"===t||"object"==typeof t&&"https"===t.type||!0===s}async setAutoDevBase(){let{store:e}=this;if(this.isAutoDevBase=!!e.empOptions.autoDevBase&&"development"===e.mode&&!this.isHttpBase,!this.isAutoDevBase)return;this.protocol=this.isHttps?"https":"http",e.empOptions.server?.port&&(this.port=e.empOptions.server.port),this.port=await eU(this.port);let t=`${this.isHttps?"wss":"ws"}://${this.host}:${this.port}/ws`;e.empOptions.base=`${this.protocol}://${this.host}:${this.port}/`,e.empOptions.server=e.deepAssign({port:this.port,client:{webSocketURL:t}},e.empOptions.server)}get isHttpBase(){let e=this.store.empOptions.base||"";return e.indexOf("http://")>-1||e.indexOf("https://")>-1}}class eW{rspack=i;rspackVersion=i.rspackVersion;isOldRspack=-1===eO(this.rspackVersion,"1.0.0");empPkg={dependencies:{},devDependencies:{},version:"2.0.0",name:""};pkg={dependencies:{},devDependencies:{},version:"0.0.0",name:""};root=process.cwd();empRoot=z;empSource=a.resolve(this.empRoot,"dist");resolve=e=>a.isAbsolute(e)?e:a.resolve(this.root,e);empResolve=e=>a.resolve(this.empRoot,e);appSrc="";outDir="";publicDir="";resource={dir:"",key:"",cert:""};chainName=ej;server=new eV(this);cacheDir="";mode="development";cliMode="dev";isDev=!0;chain;rsConfig;empOptions={};empConfig;entries={};debug;cliAction;cliOptions={};rootPaths={empConfig:void 0,tsConfig:void 0,pkg:void 0};beforeSetup;afterSetup;async setup(e,t){this.cliAction=e||this.cliAction,this.cliOptions=t||this.cliOptions;let s="store.setup";ep.time(s),this.beforeSetup&&await this.beforeSetup();let[i,o]=await Promise.all([eg(),
|
|
9
|
+
`)}}let ep=new el;var eh=x(import.meta.url);let ec=["emp-config.ts","emp-config.js","emp.config.ts","emp.config.js","emp-config.mjs","emp-config.cjs","emp-config.mts","emp-config.cts","emp.config.mjs","emp.config.cjs","emp.config.mts","emp.config.cts"],em=(e=eG.root)=>ec.map(t=>u.resolve(e,t)),eu=m(eh,{interopDefault:!0,fsCache:!0,moduleCache:!0,cacheVersion:T.rE}),eg=async()=>{let e="store.getEmpConfigPath";ep.time(e);try{let e=em(eG.root),t=await Promise.all(e.map(e=>c.promises.access(e).then(()=>!0,()=>!1)));return e.find((e,s)=>t[s])}finally{ep.timeEnd(e)}},ed=async()=>{let e=u.join(eG.root,"tsconfig.json");return await c.promises.access(e).then(()=>!0,()=>!1)||(e=void 0),e},ef=()=>{let e="127.0.0.1";try{let{int:t}=f();return d(t||"")||e}catch(t){return e}},ey=e=>{try{let{version:t}=y.readJSONSync(e);return t}catch(e){return}};function ev(){process.stdout.write("win32"===process.platform?"\x1b[2J\x1b[0f":"\x1b[2J\x1b[3J\x1b[H")}function eC(e,...t){for(let s of t)for(let t in s){let i=s[t],o=e[t];if(Object(i)==i&&Object(o)===o){e[t]=eC(o,i);continue}e[t]=s[t]}return e}let eb=e=>Array.isArray(e)?e:[e],ew=(e={},t=[])=>Object.keys(e).filter(e=>!t.includes(e)).reduce((t,s)=>(t[s]=e[s],t),{}),eO=(e="",t="")=>{let s=e.replace("^","").split("."),i=t.replace("^","").split("."),o=Math.max(s.length,i.length),r=0;for(let e=0;e<o;e++){let t=s.length>e?s[e]:0,o=isNaN(Number(t))?t.charCodeAt():Number(t),n=i.length>e?i[e]:0,a=isNaN(Number(n))?n.charCodeAt():Number(n);if(o<a){r=-1;break}if(o>a){r=1;break}}return r},eP=e=>{let t;if((e/=1e3)<1)return`${1e3*e} ms`;if(e<10){let t,s=e>=.01?2:3;return`${t=e.toFixed(s),W.bold(t)} s`}if(e<60){let t;return`${t=e.toFixed(1),W.bold(t)} s`}let s=e/60;return`${t=s.toFixed(2),W.bold(t)} m`},ek=e=>`data:text/javascript,${e}`,ej={rule:{mjs:"mjs",typescript:"typescript",javascript:"javascript",sourceMap:"sourceMapLoader",inline:"inline",raw:"raw",svg:"svg",image:"image",font:"fonts",svga:"svga",sass:"sass",less:"less",css:"css"},use:{swc:"swc",sourceMap:"sourceMapLoader",sass:"sassLoader",less:"lessLoader"},plugin:{tsCheckerRspackPlugin:"TsCheckerRspackPlugin",bundleAnalyzer:"bundleAnalyzerPlugin",define:"definePlugin",copy:"copyRspackPlugin",progress:"progressPlugin",html:{prefix:"html-plugin-"},rsdoctor:"rsdoctor",sourceMapDevTool:"sourceMapDevTool"},minimizer:{minJs:"minJs",minCss:"minCss"}};class eS{op={};constructor(e={}){this.op=e}async afterGetEmpOptions(){this.op.afterGetEmpOptions&&await this.op.afterGetEmpOptions()}async beforePlugin(){this.op.beforePlugin&&await this.op.beforePlugin()}async afterPlugin(){this.op.afterPlugin&&await this.op.afterPlugin()}async beforeModule(){this.op.beforeModule&&await this.op.beforeModule()}async afterModule(){this.op.afterModule&&await this.op.afterModule()}async beforeEmpPlugin(){this.op.beforeEmpPlugin&&await this.op.beforeEmpPlugin()}async afterEmpPlugin(){this.op.afterEmpPlugin&&await this.op.afterEmpPlugin()}async beforeBuild(){this.op.beforeBuild&&await this.op.beforeBuild()}async afterBuild(){this.op.afterBuild&&await this.op.afterBuild(),this.op.afterBulid&&await this.op.afterBulid()}async afterBulid(){await this.afterBuild()}async beforeDevServe(){this.op.beforeDevServe&&await this.op.beforeDevServe()}async afterDevServe(){this.op.afterDevServe&&await this.op.afterDevServe()}async beforeServe(){this.op.beforeServe&&await this.op.beforeServe()}async afterServe(){this.op.afterServe&&await this.op.afterServe()}}let ex=new class{store;appSrc="src";appEntry="";base="";target=[];assign(e,t){return eC(e,t=t||{})}get isESM(){return 1!==["es3","es5"].indexOf(this.store.empConfig.build.target)&&this.store.empConfig.build.useESM}lifeCycle;async setup(e){this.store=e,await this.syncEmpOptions(),await this.setupEmpOptions(),this.lifeCycle=new eS(this.store.empOptions.lifeCycle),await this.lifeCycle.afterGetEmpOptions(),this.store.empOptions.target?(this.target=this.store.empOptions.target,Array.isArray(this.target)&&!this.target.includes(this.build.target)&&this.target.push(this.build.target)):this.target=["web",this.build.target];let{appSrc:t,base:s,appEntry:i}=this.store.empOptions;t&&(this.appSrc=t),s&&(this.base=s),i&&(this.appEntry=i)}async setupEmpOptions(){await this.store.server.setupOnEmpOptionSync()}async chain(){this.store.empOptions.chain&&await this.store.empOptions.chain(this.store.chain)}async plugins(){let e=[];this.store.empOptions.plugins&&Array.isArray(this.store.empOptions.plugins)&&this.store.empOptions.plugins.length>0&&(this.store.empOptions.plugins.map(t=>{e.push(t.rsConfig(this.store))}),await Promise.all(e))}get debug(){let e=!1;return this.store.cliOptions.doctor&&(e={}),this.assign({loggerLevel:"info",clearLog:!0,progress:!0,showRsconfig:!1,showPerformance:!1,rsdoctor:e,infrastructureLogging:{appendOnly:!0,level:"warn"},newTreeshaking:this.store.empConfig.isESM,devShowAllLog:!1,showScriptDebug:!1,cssChunkingPlugin:!0,nativeWatcher:!0,warnRuleAsWarning:!0},this.store.empOptions.debug)}get build(){let e=this.store.empOptions.build?.staticDir?`${this.store.empOptions.build?.staticDir}/`:"",t={js:this.store.isDev?"cheap-module-source-map":"source-map",css:!1};return this.store.empOptions.build?.sourcemap===!0&&(t.css=!0,t.js=this.store.isDev?"cheap-module-source-map":"source-map"),this.store.empOptions.build?.devtool&&(t.js=this.store.empOptions.build?.devtool),this.assign({outDir:"dist",staticDir:e,assetsDir:"assets",publicDir:"public",chunkIds:this.store.isDev?"named":"deterministic",moduleIds:this.store.isDev?"named":"deterministic",sourcemap:t,minify:!this.store.isDev,minOptions:{},cssminOptions:{},incremental:"advance-silent",lazyCompilation:this.store.isDev,target:"es5",useESM:!1,rspack:{},polyfill:{mode:void 0,entryCdn:void 0,splitChunks:!1,include:[],coreJsFeatures:"stable",externalHelpers:!1,browserslist:this.store.browserslistOptions.default},swcConfig:{},devtool:this.store.isDev?"cheap-module-source-map":"source-map"},{...this.store.empOptions.build,staticDir:e})}get html(){let e=this.store.empOptions.html?.template?{}:{charset:{charset:"utf-8"},"http-equiv":{"http-equiv":"X-UA-Compatible",content:"IE=edge"},viewport:{name:"viewport",content:"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"},keywords:{keywords:""},description:{description:""}};return this.assign({lang:"zh-CN",title:"EMP",inject:"body",minify:!this.store.isDev,scriptLoading:this.isESM?"module":"defer",meta:e,cache:!1!==this.cache,tags:[]},this.store.empOptions.html)}get entries(){return this.store.empOptions.entries?this.store.empOptions.entries:{}}get server(){let e={host:"0.0.0.0",port:8e3,open:"darwin"===process.platform,hot:!0,watchFiles:["src/**/*.html"],static:[{directory:this.store.publicDir,watch:this.store.isDev}],allowedHosts:["all"],historyApiFallback:!0,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"X-Requested-With, content-type, Authorization"}};this.store.empOptions.server?.http2&&(this.store.server.httpsType="h2",delete this.store.empOptions.server.http2);let t=this.assign(e,this.store.empOptions.server),s="0.0.0.0"===t.host||"::"===t.host,{server:i}=this.store;if(this.store.isDev&&s&&i?.ip){let e=t.client??={};if(!e.webSocketURL){let s=i.isHttps?"wss":"ws",o=t.port??i.port??8e3;e.webSocketURL=`${s}://${i.ip}:${o}/ws`}}return t}get css(){return this.assign({sass:{mode:"modern",warnRuleAsWarning:this.store.empConfig.debug.warnRuleAsWarning},less:{lessOptions:{javascriptEnabled:!0,math:"always"}},prifixName:""},this.store.empOptions.css)}get output(){let e=(this.store.isDev,".[contenthash:8]"),t=this.store.isDev?"":".[contenthash:8]",{assetsDir:s,staticDir:i}=this.store.empConfig.build,o={publicPath:this.store.empConfig.base?this.store.empConfig.base:"auto",crossOriginLoading:"anonymous",filename:`${i}js/[name]${e}.js`,cssFilename:`${i}css/[name]${t}.css`,cssChunkFilename:`${i}css/[name]${t}.css`,assetModuleFilename:`${i}${s}/[name]${e}[ext][query]`,path:this.store.outDir,clean:!this.store.isDev,uniqueName:this.store.uniqueName},r=this.assign(o,this.store.empOptions.output);if(this.store.empConfig.isESM){let e=r.library&&"object"==typeof r.library&&!Array.isArray(r.library)?r.library:{};r.module=!0,r.library=this.assign({type:"modern-module",preserveModules:this.store.resolve(this.store.empConfig.appSrc)},e)}return r}get define(){let e={mode:this.store.mode,env:this.store.cliOptions.env};return this.store.empOptions.define&&(e={...e,...this.store.empOptions.define}),this.setDefine(e)}get tsCheckerRspackPlugin(){let e={};return!!this.store.empOptions.tsCheckerRspackPlugin&&("object"==typeof this.store.empOptions.tsCheckerRspackPlugin&&(e=this.store.empOptions.tsCheckerRspackPlugin),this.assign({},e))}setDefine(e){let t=this.store.empOptions.defineFix?this.store.empOptions.defineFix:this.isESM?"esm":"cjs",s={};return Object.keys(e).map(i=>{"all"===t?(s[`import.meta.env.${i}`]=JSON.stringify(e[i]),s[`process.env.${i}`]=JSON.stringify(e[i])):"esm"===t?s[`import.meta.env.${i}`]=JSON.stringify(e[i]):"cjs"===t?s[`process.env.${i}`]=JSON.stringify(e[i]):"none"===t&&(s[`${i}`]=JSON.stringify(e[i]))}),s}get externals(){return this.assign({},this.store.empOptions.externals)}get resolve(){return eC({alias:{src:this.store.resolve("src"),"@":this.store.resolve("src")},extensions:["...",".js",".jsx",".mjs",".ts",".tsx",".css",".less",".scss",".sass",".json",".wasm",".vue",".svg",".svga"]},this.store.empOptions.resolve)}async syncEmpOptions(){let e="store.jiti.loadConfig.empConfig";ep.time(e);try{if(!this.store.rootPaths.empConfig){this.store.empOptions={};return}let{default:e}=await eu(this.store.rootPaths.empConfig);"function"==typeof e?this.store.empOptions=await e(this.store):this.store.empOptions=e||{}}finally{ep.timeEnd(e)}}get moduleTransformRule(){let{moduleTransform:e}=this.store.empOptions,t=this.assign({defaultExclude:!1},e),s={and:[],not:[]};return!0===t.defaultExclude&&s.and.push(/(node_modules|bower_components)/),t?.exclude&&(s.and=s.and.concat(t.exclude)),e?.include&&(s.not=t.include),s}get cacheDir(){return this.store.empOptions.cacheDir?this.store.empOptions.cacheDir:"node_modules/.emp-cache"}get cache(){return!1!==this.store.empOptions.cache&&(this.store.empOptions.cache?this.store.empOptions.cache:"persistent")}get ignoreWarnings(){return this.store.empOptions.ignoreWarnings?this.store.empOptions.ignoreWarnings:[/Conflicting order/]}get autoPages(){let e;return this.store.empOptions.autoPages&&(e="boolean"==typeof this.store.empOptions.autoPages?{}:this.store.empOptions.autoPages,e=this.assign({path:"pages"},e)),e}showLogTitle(e){this.store.empOptions.showLogTitle?this.store.empOptions.showLogTitle(e):ep.title(`${e.cliAction}`)}},eE=new class{store;async setup(e){this.store=e;let t=[this.common(),this.stats(),this.devServer(),this.optimization(),this.checkTsconfig()];await Promise.all(t)}get cache(){let e;if(!1===this.store.empConfig.cache)return!1;let t={type:"persistent"===this.store.empConfig.cache?"persistent":"memory",buildDependencies:(e=[eh],eG.rootPaths.pkg&&e.push(eG.rootPaths.pkg),eG.rootPaths.empConfig&&e.push(eG.rootPaths.empConfig),eG.rootPaths.tsConfig&&e.push(eG.rootPaths.tsConfig),e),version:this.store.empConfig.server.port?`${this.store.empPkg.version}_${this.store.empConfig.server.port}`:this.store.empPkg.version};return"object"==typeof this.store.empConfig.cache&&(t=this.store.deepAssign(t,this.store.empConfig.cache)),t}get name(){let e=this.store.empConfig.server.port?`_${this.store.empConfig.server.port}`:"";return this.store.pkg.name+e}async common(){this.store.merge({name:this.name,node:{global:!0},experiments:{nativeWatcher:this.store.empConfig.debug.nativeWatcher,asyncWebAssembly:!0,...this.store.empConfig.build.rspack.experiments},incremental:this.store.empConfig.build.incremental,lazyCompilation:this.store.empConfig.build.lazyCompilation,target:this.store.empConfig.target,infrastructureLogging:this.store.empConfig.debug.infrastructureLogging,context:this.store.root,mode:this.store.mode,cache:this.cache,devtool:this.store.empConfig.build.sourcemap.js,output:{...this.store.empConfig.output,bundlerInfo:{force:!1},module:this.store.empConfig.output.module||this.store.empConfig.isESM},resolve:this.store.empConfig.resolve,externals:this.store.empConfig.externals,ignoreWarnings:this.store.empConfig.ignoreWarnings,watchOptions:{ignored:["**/node_modules/**","**/@mf-types/**"]}})}async checkTsconfig(){let e=this.store.resolve("tsconfig.json");if(await y.exists(e)){let t={};this.store.isOldRspack?t.tsConfigPath=e:t.tsConfig=e,this.store.merge({resolve:t})}}async stats(){this.store.merge({stats:{colors:!0,all:!1,assets:!1,chunks:!1,timings:!0,version:!0}})}async devServer(){this.store.merge({devServer:this.store.empConfig.server})}async optimization(){let e={moduleIds:this.store.empConfig.build.moduleIds,chunkIds:this.store.empConfig.build.chunkIds,minimize:this.store.empConfig.build.minify,splitChunks:this.store.deepAssign({chunks:"async",cacheGroups:{}},this.store.empConfig.build.rspack.splitChunks)};"entry"===this.store.empConfig.build.polyfill.mode&&this.store.empConfig.build.polyfill.splitChunks&&!this.store.empConfig.build.polyfill.entryCdn&&(e.splitChunks.cacheGroups.coreJs={test:/[\\/]node_modules[\\/](core-js)[\\/]/,name:"coreJs",chunks:"all",enforce:!0}),this.store.chain.merge({optimization:e})}},e$=new class{store;async setup(e){this.store=e;let t=[this.sass(),this.less(),this.css()];await Promise.all(t)}async sass(){let{rule:e,use:s}=this.store.chainName,i={},{sass:o}=this.store.empConfig.css;"modern"===o.mode&&(i.implementation=o.implementation?o.implementation:t.resolve("sass-embedded"),i.api="modern-compiler",i.sourceMap=this.store.empConfig.build.sourcemap.css,o.sassOptions&&(i.sassOptions=o.sassOptions)),void 0!==o.additionalData&&(i.additionalData=o.additionalData),void 0!==o.warnRuleAsWarning&&(i.warnRuleAsWarning=o.warnRuleAsWarning),void 0!==o.webpackImporter&&(i.webpackImporter=o.webpackImporter),this.store.chain.merge({module:{rule:{[e.sass]:{test:/\.(sass|scss)$/,use:{[s.sass]:{loader:t.resolve("sass-loader"),options:i}},type:"css/auto"}}}})}async less(){let{rule:e,use:s}=this.store.chainName,{lessOptions:i}=this.store.empConfig.css.less,o={loader:t.resolve("less-loader"),options:{lessOptions:i}};this.store.chain.merge({module:{rule:{[e.less]:{test:/\.less$/,use:{[s.less]:o},type:"css/auto"}}}})}async css(){let{rule:e}=this.store.chainName;this.store.chain.merge({module:{rule:{[e.css]:{test:/\.css$/,use:{},type:"css/auto"}}}})}};class eN{apply(e){let{webpack:t}=e;eG.empConfig.build.polyfill.entryCdn||new t.EntryPlugin(e.context,ek(`import 'core-js/${eG.empConfig.build.polyfill.coreJsFeatures}'`),{name:void 0}).apply(e)}}class eD{PluginName="HtmlEmpInjectPlugin";chunk="";files=[];constructor(e,t="",s=""){this.PluginName=`${this.PluginName}-${t}`,this.files=e,this.chunk=s}apply(e){e.hooks.compilation.tap(this.PluginName,e=>{b.getHooks(e).alterAssetTagGroups.tapPromise(this.PluginName,async e=>(this.chunk&&!e.plugin.userOptions.chunks?.includes(this.chunk)||this.files.map(t=>{let{pos:s,...i}=t;("body"===s?e.bodyTags:e.headTags).push({attributes:{},voidTag:!1,meta:{plugin:void 0},tagName:"script",...i})}),e))})}}let eA=new class{store;entriesConfig={};async setup(e){this.store=e,await this.init(),this.toConfig()}setHtmlConfig(e,t){return e.template=this.setTemplate(e.template),e.favicon=this.setFavicion(e.favicon),e.chunks=t,e.filename=`${t[0]}.html`,this.store.empConfig.base&&(e.publicPath=this.store.empConfig.base),this.prepareAndSetAsset(e),e}prepareAndSetAsset(e){let t=e.chunks?e.chunks[0]:void 0;this.store.injectTags(e.tags,t?`injectTags-${t}`:"injectTags",t),delete e.tags}injectPolyfill(){if(!this.store.empConfig.build.polyfill.entryCdn)return;let e=[{attributes:{src:this.store.empConfig.build.polyfill.entryCdn},tagName:"script",pos:"head"}];this.store.injectTags(e,"injectEMPPolyfill")}setChunk(e){return e.replace(a.extname(e),"").replace(`${this.store.empConfig.appSrc}${a.sep}`,"")}setTemplate(e){return e?this.store.resolve(e):this.store.empResolve(a.join("template","index.html"))}setFavicion(e){if(""!==e)return e?this.store.resolve(e):this.store.empResolve(a.join("template","favicon.ico"))}setEntryItem(e,t,s){s=s||this.store.resolve(a.join(this.store.empConfig.appSrc,e));let i=this.setChunk(e),o=[s];this.entriesConfig[i]={entry:{[i]:o},html:this.setHtmlConfig(t,[i])},this.store.entries[i]=o}setRspackHtmlPlugin(e,t){this.store.chain.plugin(`${this.store.chainName.plugin.html.prefix}${t}`).use(b,[e])}setRspackEntry(e){this.store.merge({entry:e})}async init(){this.injectPolyfill(),this.store.empConfig.autoPages?await this.setAutoPage():(await this.setDefaultEntry(),this.setEntryByConfig())}async setAutoPage(){ep.time("setAutoPage");let e=this.store.empConfig.autoPages?.path||"pages",t=a.join(this.store.appSrc,e),s=a.join(t,"**","*.{ts,tsx,jsx,js}"),i=await C([s],{windowsPathsNoEscape:!0});(i=i.map(e=>e.replace(`${t}${a.sep}`,""))).map(e=>{let s=this.store.empConfig.entries[e]||{};this.setEntryItem(e,{...this.store.empConfig.html,...s},a.join(t,e))}),ep.timeEnd("setAutoPage")}async setDefaultEntry(){let e="store.empConfig.setDefaultEntry";ep.time(e);let t=a.join(this.store.appSrc,this.store.empConfig.appEntry?this.store.empConfig.appEntry:"index.{ts,tsx,jsx,js}"),s=await C([t],{windowsPathsNoEscape:!0});if(s[0]){let e=a.join(this.store.empConfig.appSrc,Object.keys(this.store.empConfig.entries).length>0&&this.store.empConfig.appEntry?this.store.empConfig.appEntry:"index");this.setEntryItem(e,this.store.empConfig.html,s[0])}ep.timeEnd(e)}setEntryByConfig(){if(Object.keys(this.store.empConfig.entries).length>0)for(let[e,t]of Object.entries(this.store.empConfig.entries))this.setEntryItem(e,{...this.store.empConfig.html,...t})}toConfig(){for(let[e,t]of Object.entries(this.entriesConfig))this.setRspackHtmlPlugin(t.html,e),this.setRspackEntry(t.entry)}},e_=new class{store;swcJsOptions={};swcTsOptions={};coreJs={version:"3",alias:"",path:""};async setup(e){this.store=e,this.swcInitOptions(),await this.run()}async run(){let e=[this.jsDataUrl(),this.files(),this.scripts(),this.rspackGenerator(),this.rspackParser()];await this.store.empConfig.lifeCycle.beforeModule(),await Promise.all(e),await this.store.empConfig.lifeCycle.afterModule()}rspackGenerator(){let e=this.store.empConfig.css?.prifixName?`${this.store.empConfig.css?.prifixName}-`:"",t=this.store.isDev?`${e}[id]-[local]-[hash:base64:8]`:`${e}[local]-[hash:5]`;this.store.chain.merge({module:{generator:{"css/auto":{exportsConvention:"as-is",exportsOnly:!1,localIdentName:t,esModule:!0},css:{exportsOnly:!1,esModule:!0},"css/module":{exportsConvention:"as-is",exportsOnly:!1,localIdentName:t,esModule:!0},json:{JSONParse:!0}}}})}rspackParser(){let e=this.store.empConfig.build.rspack.parser,t={namedExports:!1,...e?.css};this.store.chain.merge({module:{parser:{javascript:{dynamicImportMode:"lazy",dynamicImportPrefetch:!1,dynamicImportPreload:!1,url:!0,importMeta:!0,...e?.javascript},css:t,"css/auto":t,"css/module":t}}})}get isPolyfill(){return!!this.store.empConfig.build.polyfill.mode}swcParser(e){switch(e){case"js":return{syntax:"ecmascript",jsx:!0,decorators:!0,decoratorsBeforeExport:!1};case"ts":return{syntax:"typescript",decorators:!0,tsx:!0,dynamicImport:!0}}}swcJsc(e){let{target:t,polyfill:s}=this.store.empConfig.build,{externalHelpers:i}=s;return{parser:this.swcParser(e),transform:{},target:t,externalHelpers:i,preserveAllComments:!0}}get swcCoreVersion(){let[e,t]=this.coreJs.version.split(".");return`${e}.${t}`}swcOptions(e){let t=this.store.empConfig.build.rspack.swc,s={jsc:eC(this.swcJsc(e),{...this.store.empConfig.build.swcConfig}),isModule:"unknown"};return t?.detectSyntax!==void 0&&(s.detectSyntax=t.detectSyntax,"auto"===t.detectSyntax&&delete s.jsc.parser),t?.transformImport&&(s.transformImport=t.transformImport),this.isPolyfill&&(delete s.jsc.target,s.env={coreJs:this.swcCoreVersion,targets:this.store.empConfig.build.polyfill.browserslist},this.store.empConfig.isESM||(s.env.mode=this.store.empConfig.build.polyfill.mode),"usage"===this.store.empConfig.build.polyfill.mode&&(s.env.shippedProposals=!0,s.env.include=this.store.empConfig.build.polyfill.include)),s}swcInitOptions(){let{externalHelpers:e}=this.store.empConfig.build.polyfill;e&&this.store.chain.resolve.alias.set("@swc/helpers",a.dirname(t.resolve("@swc/helpers/package.json"))),this.coreJs.path=t.resolve("core-js/package.json");let s=ey(this.coreJs.path);s&&(this.coreJs.version=s),this.coreJs.alias=a.dirname(this.coreJs.path),this.store.empConfig.build.polyfill.mode&&(this.store.chain.resolve.alias.set("core-js",this.coreJs.alias),this.store.chain.module.rule("javascript").exclude.add(/core-js/),this.store.chain.module.rule("typescript").exclude.add(/core-js/)),this.swcTsOptions=this.swcOptions("ts"),this.swcJsOptions=this.swcOptions("js")}jsDataUrl(){this.store.chain.module.rule("jsDataUrl").merge({mimetype:{or:["text/javascript","application/javascript"]}}).resolve.set("fullySpecified",!1).end().use("swcJsParser").loader("builtin:swc-loader").options(this.swcJsOptions)}async scripts(){let e=[],{rule:t,use:s}=this.store.chainName;this.store.chain.merge({module:{parser:{javascript:{exportsPresence:"error",importExportsPresence:"error"}},rule:{[t.mjs]:{test:/\.m?js/,resolve:{fullySpecified:!1}},[t.typescript]:{test:/\.(ts|tsx)$/,exclude:e,use:{[s.swc]:{loader:"builtin:swc-loader",options:this.swcTsOptions}}},[t.javascript]:{test:/\.((m|c)?js|jsx)$/,exclude:e,use:{[s.swc]:{loader:"builtin:swc-loader",options:this.swcJsOptions}}}}}})}async files(){let{rule:e}=this.store.chainName;this.store.chain.merge({module:{rule:{[e.svg]:{test:/\.svg$/,type:"asset/resource"}}}}),this.store.chain.merge({module:{rule:{[e.inline]:{resourceQuery:/inline/,type:"asset/inline"}}}}),this.store.chain.merge({module:{rule:{[e.raw]:{resourceQuery:/raw/,type:"asset/source"}}}}),this.store.chain.merge({module:{rule:{[e.image]:{test:/\.(png|jpe?g|gif|webp|ico)$/i,type:"asset/resource"},[e.font]:{test:/\.(|otf|ttf|eot|woff|woff2)$/i,type:"asset/resource"},[e.svga]:{test:/\.(svga)$/i,type:"asset/resource"}}}})}},eR=new class{store;async setup(e){this.store=e,this.beforeLifeCycle(),await this.store.empConfig.lifeCycle.beforePlugin(),await this.define(),await this.anylayze(),await this.progress(),await this.copy(),this.minify(),this.redoctor(),this.sourceMapDevToolPlugin(),this.tsCheckerRspackPlugin(),this.cssChunkingPlugin(),await this.store.empConfig.lifeCycle.afterPlugin()}beforeLifeCycle(){let{store:e}=this;"entry"===e.empConfig.build.polyfill.mode&&e.chain.plugin("empPolyfill").use(eN)}async anylayze(){if(!this.store.cliOptions.analyze)return;let{default:{BundleAnalyzerPlugin:e}}=await import("webpack-bundle-analyzer");this.store.chain.plugin(this.store.chainName.plugin.bundleAnalyzer).use(e,[{analyzerPort:this.store.empConfig.server.port,defaultSizes:"gzip",analyzerHost:this.store.getLanIp()||"127.0.0.1"}])}tsCheckerRspackPlugin(){if(!1===this.store.empConfig.tsCheckerRspackPlugin)return!1;this.store.chain.plugin(this.store.chainName.plugin.tsCheckerRspackPlugin).use(O,[this.store.empConfig.tsCheckerRspackPlugin])}async define(){this.store.chain.plugin(this.store.chainName.plugin.define).use(s.DefinePlugin,[this.store.empConfig.define])}async copy(){let e=this.store.resolve("public");w.existsSync(e)&&w.readdirSync(e).length>0&&this.store.chain.plugin(this.store.chainName.plugin.copy).use(s.CopyRspackPlugin,[{patterns:[{from:e,to:this.store.resolve(this.store.empConfig.build.outDir),noErrorOnMissing:!0,globOptions:{ignore:["**/.DS_Store"]}}]}])}async progress(){if("development"===this.store.mode)return;let e={};this.store.isOldRspack||(e={template:"{bar:25.green/white}{spinner:.green}{percent}% {wide_msg:.dim}",tick:void 0,progressChars:"▩▩"}),this.store.chain.plugin(this.store.chainName.plugin.progress).use(s.ProgressPlugin,[e])}minify(){this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minJs).use(s.SwcJsMinimizerRspackPlugin,[this.store.empConfig.build.minOptions]);let{SwcCssMinimizerRspackPlugin:e,LightningCssMinimizerRspackPlugin:t}=s;e?this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minCss).use(e,[this.store.empConfig.build.cssminOptions]):t&&this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minCss).use(t,[this.store.empConfig.build.cssminOptions])}redoctor(){if(!this.store.empConfig.debug.rsdoctor)return;let{RsdoctorRspackPlugin:e}=D("@rsdoctor/rspack-plugin"),t={};"object"==typeof this.store.empConfig.debug.rsdoctor&&(t=this.store.empConfig.debug.rsdoctor),this.store.chain.plugin(this.store.chainName.plugin.rsdoctor).use(e,[t])}sourceMapDevToolPlugin(){"object"==typeof this.store.empConfig.build.sourcemap&&this.store.empConfig.build.sourcemap?.devToolPluginOptions&&this.store.chain.plugin(this.store.chainName.plugin.sourceMapDevTool).use(s.SourceMapDevToolPlugin,[this.store.empConfig.build.sourcemap.devToolPluginOptions])}circularDependency(){this.store.chain.plugin("circularDependency").use(s.CircularDependencyRspackPlugin,[{}])}cssChunkingPlugin(){let e=!0===this.store.empConfig.debug.cssChunkingPlugin?{}:this.store.empConfig.debug.cssChunkingPlugin;e&&this.store.chain.plugin("CssChunkingPlugin").use(s.experiments.CssChunkingPlugin,[e])}},eT=new class{store;async setup(e){this.store=e;let t=[eE.setup(this.store),e_.setup(this.store),eR.setup(this.store),eA.setup(this.store),e$.setup(this.store)];await Promise.all(t),await this.store.empConfig.lifeCycle.beforeEmpPlugin(),await this.store.empConfig.plugins(),await this.store.empConfig.lifeCycle.afterEmpPlugin(),await this.store.empConfig.chain()}},eM=(e,t)=>new Promise((s,i)=>{let o=P.createServer();o.unref(),o.on("error",i),o.listen(e,t,()=>{let{port:e}=o.address();o.close(()=>{s(e)})})}),eL=async(e,t)=>{let s=new Set(["EADDRNOTAVAIL","EINVAL"]);for(let i of t)try{await eM(e,i)}catch(e){if(!s.has(e.code))throw e}return e};async function eU(e,t){let s;if(443!==e&&(e<1024||e>65535))throw Error("Port number must lie between 1024 and 65535");let i=e,o=(()=>{let e=k.networkInterfaces(),t=new Set([void 0,"0.0.0.0"]);for(let s of Object.values(e))if(s)for(let e of s)t.add(e.address);return t})();s=t&&!o.has(t)?new Set([t]):o;let r=new Set(["EADDRINUSE","EACCES"]);for(;i<=65535;)try{return await eL(i,s)}catch(e){if(!r.has(e.code))throw e;i+=1}throw Error("No available ports found")}class eF{imf={protocol:"",port:8e3,pathname:"/"};host="0.0.0.0";urls={lanUrlForConfig:"",lanUrlForTerminal:en("unavailable"),localUrlForTerminal:"",localUrlForBrowser:""};setup(e){e.host&&(this.host=e.host),e.protocol&&(this.imf.protocol=e.protocol),e.pathname&&(this.imf.pathname=e.pathname),e.port&&(this.imf.port=e.port),this.setupUrls()}setupUrls(){let e,{host:t}=this;if("0.0.0.0"===t||"::"===t){e="localhost";try{this.urls.lanUrlForConfig=this.getLanIp(),this.urls.lanUrlForConfig&&(/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(this.urls.lanUrlForConfig)?this.urls.lanUrlForTerminal=this.prettyPrintUrl(this.urls.lanUrlForConfig):this.urls.lanUrlForConfig="")}catch(e){}}else e=t,this.urls.lanUrlForConfig=t,this.urls.lanUrlForTerminal=this.prettyPrintUrl(this.urls.lanUrlForConfig);this.urls.localUrlForTerminal=this.prettyPrintUrl(e),this.urls.localUrlForBrowser=this.formatUrl(e)}getLanIp=ef;formatUrl(e){let{protocol:t,port:s,pathname:i}=this.imf;return j.format({protocol:t,hostname:e,port:s,pathname:i})}prettyPrintUrl(e){let{protocol:t,port:s,pathname:i}=this.imf;return j.format({protocol:t,hostname:e,port:W.bold(s),pathname:i})}}let eJ=new eF,eH=h(S),eI=["Google Chrome Canary","Google Chrome Dev","Google Chrome Beta","Google Chrome","Microsoft Edge","Brave Browser","Vivaldi","Chromium"],eB=async()=>{let e=process.env.BROWSER;if(!e||!eI.includes(e)){let{stdout:t}=await eH("ps cax");e=eI.find(e=>t.includes(e))}return e},ez=async e=>{if("darwin"===process.platform)try{let t=await eB();if(t){let s=`osascript openChrome.applescript "${encodeURI(e)}" "${t}"`;return await eH(s,{cwd:eG.resource.dir}),!0}}catch(e){ep.debug(e)}try{let{default:t}=await import("open");return await t(e),!0}catch(e){return ep.error("Failed to open start URL."),ep.error(e),!1}};class eV{ip=ef();host=this.ip;isAutoDevBase=!1;isHttps=!1;httpsType="default";protocol="http";port=8e3;store;publicPath="/";publicHasHttp=!1;isOpenBrower=!1;url="";urls={localUrlForBrowser:"",localUrlForTerminal:"",lanUrlForTerminal:"",lanUrlForConfig:""};constructor(e){this.store=e}async setupOnEmpOptionSync(){"build"!==this.store.cliAction&&(this.port=await eU(this.port),this.setHttps(),await this.setAutoDevBase())}get config(){return{}}async setupOnStore(){if("build"===this.store.cliAction)return;let{store:e}=this;this.publicPath=e.rsConfig.output?.publicPath==="auto"?"/":e.rsConfig.output?.publicPath||"/",this.isOpenBrower=!!e.empConfig.server.open,this.protocol=this.isHttps?"https":"http",this.host=e.empConfig.server.host?e.empConfig.server.host:this.ip,e.empConfig.server.port&&e.empConfig.server.port!==this.port&&(this.port=await eU(e.empConfig.server.port)),eJ.setup(this),this.publicPath&&(this.publicPath.indexOf("http://")>-1||this.publicPath.indexOf("https://")>-1)?(this.url=this.publicPath,this.publicHasHttp=!0,this.urls.localUrlForTerminal=eJ.prettyPrintUrl("localhost")):(this.urls=eJ.urls,this.url=this.urls.localUrlForBrowser)}startOpen(){let{urls:e}=this;this.publicHasHttp?(ep.info(`${q("➜")} Local: ${ep.link(e.localUrlForTerminal)}`),ep.info(`${q("➜")} Network: ${ep.link(this.publicPath)}`)):(ep.info(`${q("➜")} Local: ${ep.link(e.localUrlForTerminal)}`),ep.info(`${q("➜")} Network: ${ep.link(e.lanUrlForTerminal)}
|
|
10
|
+
`)),this.isOpenBrower&&ez(this.url)}async getcert(){let{store:e}=this,t=this.store.rsConfig.devServer||{server:{type:"http"}};if("object"==typeof t.server&&"https"===t.server.type&&t.server.options&&t.server.options.key&&t.server.options.cert)return t.server.options;let[s,i]=await Promise.all([n.readFile(e.resource.key),n.readFile(e.resource.cert)]);return{key:s,cert:i}}setHttps(){let{store:e}=this,{server:t,https:s}=e.empOptions.server||{};this.isHttps="https"===t||"object"==typeof t&&"https"===t.type||!0===s}async setAutoDevBase(){let{store:e}=this;if(this.isAutoDevBase=!!e.empOptions.autoDevBase&&"development"===e.mode&&!this.isHttpBase,!this.isAutoDevBase)return;this.protocol=this.isHttps?"https":"http",e.empOptions.server?.port&&(this.port=e.empOptions.server.port),this.port=await eU(this.port);let t=`${this.isHttps?"wss":"ws"}://${this.host}:${this.port}/ws`;e.empOptions.base=`${this.protocol}://${this.host}:${this.port}/`,e.empOptions.server=e.deepAssign({port:this.port,client:{webSocketURL:t}},e.empOptions.server)}get isHttpBase(){let e=this.store.empOptions.base||"";return e.indexOf("http://")>-1||e.indexOf("https://")>-1}}class eW{rspack=i;rspackVersion=i.rspackVersion;isOldRspack=-1===eO(this.rspackVersion,"1.0.0");empPkg={dependencies:{},devDependencies:{},version:"2.0.0",name:""};pkg={dependencies:{},devDependencies:{},version:"0.0.0",name:""};root=process.cwd();empRoot=z;empSource=a.resolve(this.empRoot,"dist");resolve=e=>a.isAbsolute(e)?e:a.resolve(this.root,e);empResolve=e=>a.resolve(this.empRoot,e);appSrc="";outDir="";publicDir="";resource={dir:"",key:"",cert:""};chainName=ej;server=new eV(this);cacheDir="";mode="development";cliMode="dev";isDev=!0;chain;rsConfig;empOptions={};empConfig;entries={};debug;cliAction;cliOptions={};rootPaths={empConfig:void 0,tsConfig:void 0,pkg:void 0};beforeSetup;afterSetup;async setup(e,t){this.cliAction=e||this.cliAction,this.cliOptions=t||this.cliOptions;let s="store.setup";ep.time(s),this.beforeSetup&&await this.beforeSetup();let[i,o]=await Promise.all([eg(),ed()]);this.rootPaths.empConfig=i,this.rootPaths.tsConfig=o,this.rootPaths.pkg=this.resolve("package.json"),await this.initVars(this.cliAction,this.cliOptions),this.empConfig=ex,await this.empConfig.setup(this),this.debug={...this.empConfig.debug},this.initPaths(),this.chain=new v,await eT.setup(this),this.setLogger(),this.toConfig(),this.logConfig(),await this.server.setupOnStore(),this.afterSetup&&await this.afterSetup(),ep.timeEnd(s),this.debug.clearLog&&ev()}async initVars(e,s){this.cliAction=e,this.cliOptions=s||{},this.cliMode="prod",this.mode="dev"===e?"development":"production",this.isDev="development"===this.mode,process.env.NODE_ENV="dev"===e?"development":"production";let i=t(this.empResolve("package.json")),o=t(this.resolve("package.json"));this.empPkg={...this.empPkg,...i},this.pkg={...this.pkg,...o},this.resource.dir=a.join(this.empRoot,"resource"),this.resource.cert=a.join(this.resource.dir,"emp.cert"),this.resource.key=a.join(this.resource.dir,"emp.key")}initPaths(){this.appSrc=this.resolve(this.empConfig.appSrc),this.outDir=this.resolve(this.empConfig.build.outDir),this.publicDir=this.resolve(this.empConfig.build.publicDir),this.cacheDir=this.resolve(this.empConfig.cacheDir)}loggerExtensionName="";setLoggerExtensionName(e){this.loggerExtensionName=e}setLogger(){let e="dev"===this.cliMode?"debug":"info";this.debug.loggerLevel&&(e=this.debug.loggerLevel),ep.setup({fullName:`EMP⚡${this.empPkg.version}${"dev"===this.cliMode?".DEV":""}${this.loggerExtensionName?" "+this.loggerExtensionName:""}`,brandName:"EMP",logLevel:e})}merge(e){this.chain.merge(e)}toConfig(){this.rsConfig=this.chain.toConfig()}logConfig(){if(this.debug.showRsconfig)if("string"==typeof this.debug.showRsconfig){let e=a.join(this.root,this.debug.showRsconfig);n.writeFile(e,JSON.stringify(this.rsConfig,null,2))}else{this.debug.clearLog=!1;let e={colors:!0,depth:null},t="object"==typeof this.debug.showRsconfig?eC(e,this.debug.showRsconfig):e;console.log(ep.link("[Compile Config]")),console.log(p.inspect(this.rsConfig,t))}}get browserslistOptions(){return{default:["chrome >= 87","edge >= 88","firefox >= 78","safari >= 14"],h5:["iOS >= 9","Android >= 4.4","last 2 versions","> 0.2%","not dead"],node:["node >= 16"]}}get uniqueName(){return this.encodeVarName(this.pkg.name)}encodeVarName(e){return e.replaceAll("/","_").replaceAll("@","_").replaceAll("-","_")}vCompare=eO;deepAssign=eC;getLanIp=ef;injectTags(e=[],t="",s=""){this.chain.plugin(`${eD}-${t}`).use(eD,[e,t,s])}}let eG=new eW;function eq(e){return e}export{A as __webpack_require__,el as Logger,es as blue,W as chalk,ea as color,eC as deepAssign,eq as defineConfig,o as program,em as getEmpConfigCandidatePaths,ef as getLanIp,eU as getPorts,en as gray,q as green,_ as empHelper,ez as helper_openBrowser,ep as logger,er as magenta,Y as red,i as rspack,H as runScript,eG as store,eP as timeFormat,ei as white,Z as yellow};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { StaticServeOptions } from '../server/static/types';
|
|
2
|
+
export type StaticCommandOptions = {
|
|
3
|
+
root?: string;
|
|
4
|
+
host?: string;
|
|
5
|
+
port?: string | number;
|
|
6
|
+
cors?: boolean;
|
|
7
|
+
spa?: boolean | string;
|
|
8
|
+
https?: boolean;
|
|
9
|
+
cert?: string;
|
|
10
|
+
key?: string;
|
|
11
|
+
headers?: string[];
|
|
12
|
+
index?: string[];
|
|
13
|
+
open?: boolean;
|
|
14
|
+
json?: boolean;
|
|
15
|
+
compression?: string | boolean;
|
|
16
|
+
};
|
|
17
|
+
export declare function normalizeStaticOptions(root: string | undefined, options: StaticCommandOptions): StaticServeOptions;
|
|
18
|
+
export declare function runStaticCommand(root: string | undefined, options: StaticCommandOptions): Promise<void>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Server as HttpServer } from 'node:http';
|
|
2
|
+
import type { Server as HttpsServer } from 'node:https';
|
|
3
|
+
export type StaticHeaderMap = Record<string, string>;
|
|
4
|
+
export type StaticCompressionMode = 'cloudflare' | false;
|
|
5
|
+
export type StaticServeOptions = {
|
|
6
|
+
root: string;
|
|
7
|
+
host?: string;
|
|
8
|
+
port?: number;
|
|
9
|
+
cors?: boolean;
|
|
10
|
+
spa?: boolean | string;
|
|
11
|
+
index?: string[];
|
|
12
|
+
https?: boolean;
|
|
13
|
+
cert?: string;
|
|
14
|
+
key?: string;
|
|
15
|
+
headers?: StaticHeaderMap;
|
|
16
|
+
compression?: StaticCompressionMode;
|
|
17
|
+
};
|
|
18
|
+
export type StaticServeUrls = {
|
|
19
|
+
localUrlForBrowser: string;
|
|
20
|
+
localUrlForTerminal: string;
|
|
21
|
+
lanUrlForTerminal: string;
|
|
22
|
+
};
|
|
23
|
+
export type StaticServerHandle = {
|
|
24
|
+
server: HttpServer | HttpsServer;
|
|
25
|
+
root: string;
|
|
26
|
+
host: string;
|
|
27
|
+
port: number;
|
|
28
|
+
protocol: 'http' | 'https';
|
|
29
|
+
urls: StaticServeUrls;
|
|
30
|
+
close: () => Promise<void>;
|
|
31
|
+
};
|
package/dist/static.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import"node:module";import t,{existsSync as e,statSync as o}from"node:fs";import a from"node:fs/promises";import i from"node:http";import r from"node:https";import s from"node:path";import{parse as n}from"node:url";import{brotliCompressSync as c,constants as p,gzipSync as l}from"node:zlib";import d from"connect";import m from"cors";import{helper_openBrowser as f,getLanIp as h}from"./346.js";let u=["index.html"],g={".br":"application/octet-stream",".css":"text/css; charset=utf-8",".eot":"application/vnd.ms-fontobject",".html":"text/html; charset=utf-8",".ico":"image/x-icon",".js":"application/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".otf":"font/otf",".svg":"image/svg+xml",".ttf":"font/ttf",".ts":"text/plain; charset=utf-8",".tsx":"text/plain; charset=utf-8",".txt":"text/plain; charset=utf-8",".wasm":"application/wasm",".woff":"font/woff",".woff2":"font/woff2"},x=new Set(["application/javascript","application/json","application/manifest+json","application/wasm","image/svg+xml","font/otf","font/ttf","font/woff","text/css","text/html","text/javascript","text/plain"]);function b(e){let o=s.dirname(new URL(import.meta.url).pathname),a=[s.resolve(o,"../../../resource",e),s.resolve(o,"../../../../resource",e)].find(e=>t.existsSync(e));if(!a)throw Error(`EMP static HTTPS resource is missing: ${e}`);return a}async function y(t){let e=t.key?s.resolve(process.cwd(),t.key):b("emp.key"),o=t.cert?s.resolve(process.cwd(),t.cert):b("emp.cert"),[i,r]=await Promise.all([a.readFile(e),a.readFile(o)]);return{key:i,cert:r}}function w(t,e){return e.startsWith(t+s.sep)||e===t}function v(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function k(t,e){let o,i=(o=s.relative(t,e))?`/${o.split(s.sep).map(encodeURIComponent).join("/")}/`:"/",r=await a.readdir(e,{withFileTypes:!0}),n=await Promise.all(r.sort((t,e)=>t.isDirectory()!==e.isDirectory()?t.isDirectory()?-1:1:t.name.localeCompare(e.name)).map(async t=>{var o;let r=s.join(e,t.name),n=await a.stat(r),c=`${t.name}${t.isDirectory()?"/":""}`,p=`${i}${encodeURIComponent(t.name)}${t.isDirectory()?"/":""}`,l=(o=t.name,t.isDirectory()?"DIR":s.extname(o).slice(1).toUpperCase()||"FILE"),d=t.isDirectory()?"emp-static-kind-dir":`emp-static-kind-${l.toLowerCase().replace(/[^a-z0-9-]/g,"-")}`,m=t.isDirectory()?"Directory":l,f=t.isDirectory()?"-":function(t){if(t<1024)return`${t} B`;let e=["KB","MB","GB"],o=t/1024,a=e.shift()??"KB";for(;o>=1024&&e.length>0;)o/=1024,a=e.shift()??a;return`${o.toFixed(o>=10?0:1)} ${a}`}(n.size),h=n.mtime.toISOString().replace("T"," ").slice(0,19);return`<a class="emp-static-card" href="${p}">
|
|
2
|
+
<span class="${t.isDirectory()?"emp-static-folder-card":"emp-static-file-card"} ${d}">
|
|
3
|
+
<span class="emp-static-icon">${t.isDirectory()?`<svg class="emp-static-svg" viewBox="0 0 44 36" fill="none" aria-hidden="true">
|
|
4
|
+
<path d="M4.5 10.5h13l3.4 4.6h18.6v14.4a3 3 0 0 1-3 3h-32a3 3 0 0 1-3-3v-16a3 3 0 0 1 3-3Z" fill="currentColor" opacity=".16"/>
|
|
5
|
+
<path d="M4.5 8.5h12.2l3.4 4.5h19.4v16.5a3 3 0 0 1-3 3h-32a3 3 0 0 1-3-3v-18a3 3 0 0 1 3-3Z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/>
|
|
6
|
+
</svg>`:`<svg class="emp-static-svg" viewBox="0 0 36 44" fill="none" aria-hidden="true">
|
|
7
|
+
<path d="M8.5 3.5h13.8L31.5 13v23.5a4 4 0 0 1-4 4h-19a4 4 0 0 1-4-4v-29a4 4 0 0 1 4-4Z" fill="currentColor" opacity=".08"/>
|
|
8
|
+
<path d="M22 3.8V12a2 2 0 0 0 2 2h7.4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
9
|
+
<path d="M8.5 3.5h13.8L31.5 13v23.5a4 4 0 0 1-4 4h-19a4 4 0 0 1-4-4v-29a4 4 0 0 1 4-4Z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/>
|
|
10
|
+
</svg>`}</span>
|
|
11
|
+
<span class="emp-static-badge">${v(l)}</span>
|
|
12
|
+
</span>
|
|
13
|
+
<span class="emp-static-name">${v(c)}</span>
|
|
14
|
+
<span class="emp-static-meta"><b>Type</b>${v(m)}</span>
|
|
15
|
+
<span class="emp-static-meta"><b>Size</b>${v(f)}</span>
|
|
16
|
+
<span class="emp-static-meta emp-static-modified"><b>Modified</b>${v(h)}</span>
|
|
17
|
+
</a>`}));return`<!doctype html>
|
|
18
|
+
<html lang="en">
|
|
19
|
+
<head>
|
|
20
|
+
<meta charset="utf-8">
|
|
21
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
22
|
+
<title>EMP Static Index ${v(i)}</title>
|
|
23
|
+
<style>
|
|
24
|
+
:root { color-scheme: light; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Helvetica Neue", sans-serif; }
|
|
25
|
+
body { margin: 0; min-height: 100vh; background: #f5f5f7; color: #1d1d1f; }
|
|
26
|
+
.emp-static-index { max-width: 1180px; margin: 0 auto; padding: 38px 24px 56px; }
|
|
27
|
+
.emp-static-shell { background: rgba(255, 255, 255, 0.86); border: 1px solid rgba(0, 0, 0, 0.08); border-radius: 8px; box-shadow: 0 18px 45px rgba(0, 0, 0, 0.08); overflow: hidden; }
|
|
28
|
+
header { display: flex; align-items: flex-end; justify-content: space-between; gap: 18px; padding: 22px 24px; border-bottom: 1px solid rgba(0, 0, 0, 0.07); background: rgba(250, 250, 252, 0.92); }
|
|
29
|
+
h1 { margin: 0 0 6px; font-size: 28px; line-height: 1.15; font-weight: 720; letter-spacing: 0; }
|
|
30
|
+
.path { color: #5f6368; font-family: "SF Mono", ui-monospace, Menlo, Monaco, Consolas, monospace; font-size: 13px; overflow-wrap: anywhere; }
|
|
31
|
+
.emp-static-count { color: #6e6e73; font-size: 13px; white-space: nowrap; }
|
|
32
|
+
.emp-static-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(188px, 1fr)); gap: 12px; padding: 18px; }
|
|
33
|
+
.emp-static-card { display: grid; grid-template-rows: auto auto 1fr; min-height: 166px; padding: 14px; border: 1px solid rgba(0, 0, 0, 0.08); border-radius: 8px; background: linear-gradient(180deg, #ffffff 0%, #fbfbfd 100%); color: inherit; text-decoration: none; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04); transition: transform 120ms ease, box-shadow 120ms ease, border-color 120ms ease; }
|
|
34
|
+
.emp-static-card:hover { transform: translateY(-2px); border-color: rgba(0, 113, 227, 0.35); box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1); }
|
|
35
|
+
.emp-static-file-card, .emp-static-folder-card { position: relative; display: inline-grid; place-items: center; width: 58px; height: 58px; margin-bottom: 12px; color: #06c; }
|
|
36
|
+
.emp-static-file-card { color: #5f6368; }
|
|
37
|
+
.emp-static-folder-card { color: #0071e3; }
|
|
38
|
+
.emp-static-icon { display: inline-grid; place-items: center; width: 58px; height: 58px; border-radius: 8px; background: #f5f5f7; }
|
|
39
|
+
.emp-static-folder-card .emp-static-icon { background: #e8f2ff; }
|
|
40
|
+
.emp-static-svg { width: 44px; height: 44px; color: currentColor; display: block; }
|
|
41
|
+
.emp-static-badge { position: absolute; right: -4px; bottom: 2px; min-width: 26px; max-width: 40px; padding: 2px 5px; border-radius: 6px; background: #1d1d1f; color: #fff; font-size: 10px; line-height: 1.2; font-weight: 700; text-align: center; letter-spacing: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
42
|
+
.emp-static-folder-card .emp-static-badge { background: #0071e3; }
|
|
43
|
+
.emp-static-kind-js { color: #b7791f; }
|
|
44
|
+
.emp-static-kind-js .emp-static-icon { background: #fff6d7; }
|
|
45
|
+
.emp-static-kind-js .emp-static-badge { background: #b7791f; }
|
|
46
|
+
.emp-static-kind-ts, .emp-static-kind-tsx { color: #0071e3; }
|
|
47
|
+
.emp-static-kind-ts .emp-static-icon, .emp-static-kind-tsx .emp-static-icon { background: #e8f2ff; }
|
|
48
|
+
.emp-static-kind-ts .emp-static-badge, .emp-static-kind-tsx .emp-static-badge { background: #0071e3; }
|
|
49
|
+
.emp-static-kind-css { color: #7e57c2; }
|
|
50
|
+
.emp-static-kind-css .emp-static-icon { background: #f0ebff; }
|
|
51
|
+
.emp-static-kind-css .emp-static-badge { background: #7e57c2; }
|
|
52
|
+
.emp-static-kind-html { color: #c2542d; }
|
|
53
|
+
.emp-static-kind-html .emp-static-icon { background: #fff0e8; }
|
|
54
|
+
.emp-static-kind-html .emp-static-badge { background: #c2542d; }
|
|
55
|
+
.emp-static-kind-json { color: #5f6368; }
|
|
56
|
+
.emp-static-kind-json .emp-static-icon { background: #eef0f3; }
|
|
57
|
+
.emp-static-kind-json .emp-static-badge { background: #5f6368; }
|
|
58
|
+
.emp-static-kind-vue { color: #2f8f63; }
|
|
59
|
+
.emp-static-kind-vue .emp-static-icon { background: #e7f6ee; }
|
|
60
|
+
.emp-static-kind-vue .emp-static-badge { background: #2f8f63; }
|
|
61
|
+
.emp-static-name { min-width: 0; margin-bottom: 12px; font-size: 15px; line-height: 1.3; font-weight: 650; overflow-wrap: anywhere; }
|
|
62
|
+
.emp-static-meta { display: flex; justify-content: space-between; gap: 10px; color: #6e6e73; font-size: 12px; line-height: 1.5; }
|
|
63
|
+
.emp-static-meta b { color: #3a3a3c; font-weight: 600; }
|
|
64
|
+
.emp-static-modified { margin-top: 2px; grid-column: 1; }
|
|
65
|
+
@media (max-width: 640px) {
|
|
66
|
+
.emp-static-index { padding: 20px 12px 32px; }
|
|
67
|
+
header { display: block; padding: 18px; }
|
|
68
|
+
.emp-static-count { display: block; margin-top: 12px; }
|
|
69
|
+
.emp-static-grid { grid-template-columns: 1fr; padding: 12px; }
|
|
70
|
+
}
|
|
71
|
+
</style>
|
|
72
|
+
</head>
|
|
73
|
+
<body>
|
|
74
|
+
<main class="emp-static-index">
|
|
75
|
+
<section class="emp-static-shell">
|
|
76
|
+
<header>
|
|
77
|
+
<div>
|
|
78
|
+
<h1>EMP Static Index</h1>
|
|
79
|
+
<div class="path">${v(i)}</div>
|
|
80
|
+
</div>
|
|
81
|
+
<div class="emp-static-count">${n.length} items</div>
|
|
82
|
+
</header>
|
|
83
|
+
<div class="emp-static-grid">${n.join("")}</div>
|
|
84
|
+
</section>
|
|
85
|
+
</main>
|
|
86
|
+
</body>
|
|
87
|
+
</html>`}async function $(t,e=""){let o=decodeURIComponent(n(e).pathname||"/"),a="/"===o?".":o.replace(/^\/+/,""),i=s.resolve(t,a);if(w(t,i))return i}async function C(t,e,o,i){let r=await $(t,e);if(r){let e=await a.stat(r).catch(()=>void 0);if(e?.isFile())return{statusCode:200,filePath:r,body:await a.readFile(r)};if(e?.isDirectory()){for(let t of(i?.length?i:u).map(t=>t.trim()).filter(Boolean)){let e=s.resolve(r,t);if(!w(r,e))continue;let o=await a.stat(e).catch(()=>void 0);if(o?.isFile())return{statusCode:200,filePath:e,body:await a.readFile(e)}}return{statusCode:200,filePath:"",contentType:"text/html; charset=utf-8",body:Buffer.from(await k(t,r))}}}if(o){let e=s.resolve(t,"string"==typeof o?o:"index.html");return{statusCode:200,filePath:e,body:await a.readFile(e)}}return{statusCode:404,filePath:"",contentType:"text/plain; charset=utf-8",body:Buffer.alloc(0)}}async function j(e){var o;let a=(o=e.root,s.resolve(process.cwd(),o));if(!t.existsSync(a)||!t.statSync(a).isDirectory())throw Error(`Static root does not exist: ${a}`);let n=d();e.cors&&n.use(m()),n.use(async(t,o)=>{if("GET"!==t.method&&"HEAD"!==t.method){o.statusCode=404,o.end();return}try{var i;let r=await C(a,t.url,e.spa,e.index),n=r.contentType??(r.filePath?(i=r.filePath,g[s.extname(i).toLowerCase()]??"application/octet-stream"):"text/plain; charset=utf-8"),d=e.headers??{},m=r.body,f="";if(200===r.statusCode&&!1!==e.compression){let e=function(t,e,o,a){let i,r,s;if(i=e.split(";")[0].trim().toLowerCase(),!x.has(i)||(r=Object.entries(a??{}).find(([t])=>"cache-control"===t.toLowerCase())?.[1],r?.toLowerCase().includes("no-transform")))return{body:t,encoding:""};let n=(s=o.split(",").map(t=>t.trim().split(";")[0]).filter(Boolean)).includes("br")&&t.byteLength>=50?"br":s.includes("gzip")&&t.byteLength>=48?"gzip":"";return"br"===n?{body:Buffer.from(c(t,{params:{[p.BROTLI_PARAM_QUALITY]:4}})),encoding:n}:"gzip"===n?{body:Buffer.from(l(t,{level:8})),encoding:n}:{body:t,encoding:""}}(r.body,n,String(t.headers["accept-encoding"]??""),d);m=e.body,f=e.encoding}for(let[t,e]of(o.statusCode=r.statusCode,o.setHeader("Content-Type",n),o.setHeader("Vary","Accept-Encoding"),Object.entries(d)))o.setHeader(t,e);f&&o.setHeader("Content-Encoding",f),o.setHeader("Content-Length",m.byteLength),o.end("HEAD"===t.method?void 0:m)}catch(t){o.statusCode=500,o.end(t instanceof Error?t.message:String(t))}});let f=e.https?"https":"http",u=e.https?r.createServer(await y(e),n):i.createServer(n),b=e.port??0,w=e.host??"0.0.0.0";await new Promise((t,e)=>{u.once("error",e),u.listen(b,w,()=>t())});let v=u.address(),k="object"==typeof v&&v?v.port:b,$=function({protocol:t,host:e,port:o}){let a=h();return{localUrlForBrowser:`${t}://${"0.0.0.0"===e||"::"===e?"localhost":e}:${o}/`,localUrlForTerminal:`${t}://localhost:${o}/`,lanUrlForTerminal:`${t}://${a}:${o}/`}}({protocol:f,host:w,port:k});return{server:u,root:a,host:w,port:k,protocol:f,urls:$,close:()=>new Promise((t,e)=>{u.close(o=>o?e(o):t())})}}async function S(t,a){let i=await j(function(t,a){var i;let r=t||a.root,s=a.index;if(!r&&s&&s.length>1){let t=s.at(-1);t&&function(t){try{return e(t)&&o(t).isDirectory()}catch{return!1}}(t)&&(r=t,s=s.slice(0,-1))}return{root:r||"dist",host:a.host||"0.0.0.0",port:void 0===a.port?0:Number(a.port),cors:!!a.cors,spa:a.spa,https:!!a.https,cert:a.cert,key:a.key,headers:function(t){if(t&&0!==t.length)return Object.fromEntries(t.map(t=>{let e=t.indexOf("=");if(e<1)throw Error(`Invalid header format, expected key=value: ${t}`);return[t.slice(0,e),t.slice(e+1)]}))}(a.headers),index:s,compression:!1!==(i=a.compression)&&"false"!==i&&"off"!==i&&"none"!==i&&"cloudflare"}}(t,a)),r={root:i.root,protocol:i.protocol,host:i.host,port:i.port,urls:i.urls};a.json?console.log(JSON.stringify(r,null,2)):(console.log("EMP static server"),console.log(` root: ${i.root}`),console.log(` local: ${i.urls.localUrlForTerminal}`),console.log(` network: ${i.urls.lanUrlForTerminal}`)),a.open&&f(i.urls.localUrlForBrowser)}export{S as runStaticCommand};
|
package/dist/types/env.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export type EMPModeType = 'development' | 'production';
|
|
2
|
-
export type CliActionType = 'dev' | 'build' | 'serve';
|
|
2
|
+
export type CliActionType = 'dev' | 'build' | 'serve' | 'static';
|
|
3
3
|
export type EnvVarsType = Record<string, string>;
|
|
4
4
|
export type CliOptionsType = {
|
|
5
5
|
env?: string;
|
|
@@ -13,4 +13,15 @@ export type CliOptionsType = {
|
|
|
13
13
|
analyze?: boolean;
|
|
14
14
|
watch?: boolean;
|
|
15
15
|
serve?: boolean;
|
|
16
|
+
root?: string;
|
|
17
|
+
host?: string;
|
|
18
|
+
port?: string | number;
|
|
19
|
+
cors?: boolean;
|
|
20
|
+
spa?: boolean | string;
|
|
21
|
+
https?: boolean;
|
|
22
|
+
cert?: string;
|
|
23
|
+
key?: string;
|
|
24
|
+
headers?: string[];
|
|
25
|
+
compression?: string | boolean;
|
|
26
|
+
json?: boolean;
|
|
16
27
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@empjs/cli",
|
|
3
|
-
"version": "4.0.0-
|
|
3
|
+
"version": "4.0.0-beta.0",
|
|
4
4
|
"description": "emp",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -119,7 +119,7 @@
|
|
|
119
119
|
"ts-checker-rspack-plugin": "1.4.0",
|
|
120
120
|
"typescript-plugin-css-modules": "5.2.0",
|
|
121
121
|
"webpack-bundle-analyzer": "4.10.2",
|
|
122
|
-
"@empjs/chain": "4.0.0-
|
|
122
|
+
"@empjs/chain": "4.0.0-beta.0"
|
|
123
123
|
},
|
|
124
124
|
"scripts": {
|
|
125
125
|
"dev": "rslib build --watch --env-mode development",
|
|
@@ -127,7 +127,7 @@
|
|
|
127
127
|
"dev-rs": "pnpm run dev",
|
|
128
128
|
"build-rs": "pnpm run build",
|
|
129
129
|
"test": "node test/rslib-node-target.test.mjs && node test/cli-options.test.mjs && node test/config-file-discovery.test.mjs && node test/build-watch-shape.test.mjs && node test/lifecycle-order.test.mjs && pnpm run build && node test/cli-help.test.mjs && node test/rspack2-features-shape.test.mjs && node test/rspack-config-shape.test.mjs",
|
|
130
|
-
"test:real": "rstest run",
|
|
130
|
+
"test:real": "pnpm run build && rstest run",
|
|
131
131
|
"test:real:create": "rstest run test/agent-create-intent.test.ts test/agent-create-planner.test.ts test/agent-create-generator.test.ts test/agent-create-verify.test.ts test/agent-create-executor.test.ts test/agent-create-fix.test.ts test/cli-create-help.test.ts",
|
|
132
132
|
"test:real:create-help": "rstest run test/cli-create-help.test.ts",
|
|
133
133
|
"test:real:executor": "rstest run test/agent-create-executor.test.ts",
|