@empjs/cli 4.0.0-alpha.1 → 4.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,7 @@ EMP 是一个基于 Rspack 的高性能模块联邦框架,专注于微前端
11
11
 
12
12
  ### 环境要求
13
13
  - Node.js `^20.19.0 || >=22.12.0`
14
- - pnpm 8+(推荐)
14
+ - pnpm `10.x`(推荐使用仓库根 `packageManager` 指定的 `pnpm@10.33.0`)
15
15
 
16
16
  ### 安装
17
17
  ```bash
@@ -44,6 +44,12 @@ pnpm dev
44
44
 
45
45
  # 指定环境
46
46
  pnpm dev --env test
47
+
48
+ # 显式开启热更新
49
+ pnpm dev --hot
50
+
51
+ # 注入环境变量
52
+ pnpm dev --env-vars API_URL=https://example.com
47
53
  ```
48
54
 
49
55
  ### 构建
@@ -53,6 +59,12 @@ pnpm build
53
59
 
54
60
  # 分析包体积
55
61
  pnpm stat
62
+
63
+ # watch 构建
64
+ pnpm build --watch
65
+
66
+ # watch 构建后启动本地预览
67
+ pnpm build --watch --serve
56
68
  ```
57
69
 
58
70
  ### 本地预览
@@ -103,6 +115,45 @@ export default defineConfig(store => {
103
115
  })
104
116
  ```
105
117
 
118
+ ### Rspack 2 配置入口
119
+ `build.rspack` 用于显式接入 Rspack 2 的新增能力。EMP 不会默认开启高风险实验能力,业务需要按场景配置。
120
+
121
+ ```js
122
+ import {defineConfig} from '@empjs/cli'
123
+
124
+ export default defineConfig(() => {
125
+ return {
126
+ build: {
127
+ // ESM library 输出会自动使用 output.library.type = 'modern-module'
128
+ useESM: true,
129
+ target: 'es2018',
130
+ // Rspack 2 支持 hashed module id;默认仍保持 development=named、production=deterministic
131
+ moduleIds: 'hashed',
132
+ rspack: {
133
+ // 函数级 tree-shaking;错误标记 pure function 会删除实际有副作用调用
134
+ experiments: {pureFunctions: true},
135
+ // 大 chunk 强制拆分阈值;会影响请求数量和产物拆分形态
136
+ splitChunks: {chunks: 'all', enforceSizeThreshold: 80000},
137
+ parser: {
138
+ javascript: {
139
+ // 给第三方库或不可改源码手动声明纯函数名
140
+ pureFunctions: ['createPureValue'],
141
+ },
142
+ css: {
143
+ // false 时保留 CSS @import,交给浏览器或下游工具处理
144
+ resolveImport: false,
145
+ },
146
+ },
147
+ swc: {
148
+ // 让 builtin:swc-loader 按文件扩展名推断 JS/TS/JSX/TSX parser
149
+ detectSyntax: 'auto',
150
+ },
151
+ },
152
+ },
153
+ }
154
+ })
155
+ ```
156
+
106
157
  ### React 与模块联邦配置示例
107
158
  ```js
108
159
  import {defineConfig} from '@empjs/cli'
package/dist/346.js CHANGED
@@ -1,10 +1,10 @@
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 v from"fs-extra";import y from"@empjs/chain";import{glob as b}from"glob";import C 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 x}from"node:child_process";import{fileURLToPath as $}from"node:url";var E,S={},N={};function D(e){var t=N[e];if(void 0!==t)return t.exports;var s=N[e]={exports:{}};return S[e](s,s.exports,D),s.exports}D.m=S,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 R={};D.r(R),D.d(R,{chalk:()=>I,color:()=>es,glob:()=>b,logger:()=>eo,utils:()=>L});var L={};D.r(L),D.d(L,{clearConsole:()=>em,deepAssign:()=>eu,ensureArray:()=>eg,getLanIp:()=>eh,getPkgVersion:()=>ec,importJsVm:()=>ey,jsonFilter:()=>ed,timeFormat:()=>ev,vCompare:()=>ef});var T=JSON.parse('{"rE":"4.0.0-alpha.1"}');async function _(){o.version(T.rE,"-v, --version").usage("<command> [options]"),o.command("dev").description("Dev 模式").option("-e, --env <env>","部署环境 dev、test、prod").option("-rd, --doctor","开启rsdoctor,可通过debug.rsdoctor操作").option("-h, --hot","是否使用热更新 默认启动").option("-o, --open","是否打开调试页面 默认不打开").option("-t, --ts","生成类型文件 默认为 false").option("-pr, --profile","统计模块消耗").option("-cl, --clearLog <clearLog>","清空日志 默认为 true").option("-ev, --env-vars <key=value>","定义一个环境变量 -ev key=value 多个环境变量重复调用 -ev key=value -ev key=value",(e,t)=>{let[s,i]=e.split("=");return t[s]=i,t},{}).action(async e=>{let{default:t}=await import("./dev.js");await t.setup("dev",e)}),o.command("build").description("Build 模式").option("-e, --env <env>","部署环境 dev、test、prod").option("-rd, --doctor","开启rsdoctor,可通过debug.rsdoctor操作").option("-a, --analyze","生成分析报告 默认为 false").option("-t, --ts","生成类型文件 默认为 false").option("-pr, --profile","统计模块消耗").option("-cl, --clearLog <clearLog>","清空日志 默认为 true").option("-w, --watch","watch 模式").option("-sv, --serve","watch 模式下启动serve").option("-ev, --env-vars <key=value>","定义一个环境变量 -ev key=value 多个环境变量重复调用 -ev key=value -ev key=value",(e,t)=>{let[s,i]=e.split("=");return t[s]=i,t},{}).action(async e=>{let{default:t}=await import("./build.js");await t.setup("build",e)}),o.command("serve").description("Server 模式").option("-cl, --clearLog <clearLog>","清空日志 默认为 true").option("-e, --env <env>","部署环境 dev、test、prod").option("-ev, --env-vars <key=value>","定义一个环境变量 -ev key=value 多个环境变量重复调用 -ev key=value -ev key=value",(e,t)=>{let[s,i]=e.split("=");return t[s]=i,t},{}).action(async e=>{let{default:t}=await import("./serve.js");await t.setup("serve",e)}),o.command("dts").description("拉取 remote 项目的 d.ts").option("-p, --typingsPath <typingsPath>","下载目录").option("-e, --env <env>","部署环境 dev、test、prod").action(e=>{}),o.command("init").description("初始化 emp 项目").option("-d, --data [data]","JSON数据 http地址 或者 文件路径相对、绝对路径").action(e=>{}),o.parse(r.argv)}var M=l($(import.meta.url)),U=$(import.meta.url);let F=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(M,U).replace(`${a.sep}dist${a.sep}index.js`,"")}(M),J=e=>"function"==typeof e&&"function"==typeof e.hex,I=(e=>{let t=e.default;if(J(t))return t;if(t&&"object"==typeof t){let e=t.default;if(J(e))return e}return e})(g),H=I.hex("#1abc9c"),z=I.hex("#16a085"),B=I.hex("#2ecc71"),V=I.hex("#27ae60"),G=I.hex("#e74c3c"),W=I.hex("#c0392b"),q=I.hex("#f1c40f"),K=I.hex("#f39c12"),Q=I.hex("#3498db"),X=I.hex("#2980b9"),Y=I.hex("#ecf0f1"),Z=I.hex("#fd79a8"),ee=I.hex("#e84393"),et=I.hex("#7f8c8d"),es={lightGreen:H,green:z,lightCyan:B,cyan:V,lightRed:G,red:W,yellow:q,orange:K,lightBlue:Q,blue:X,white:Y,lightMagenta:Z,magenta:ee,gray:et};class ei{brandName="";fullName="";logLevel="info";isLogTime=!1;setup({brandName:e,logLevel:t,fullName:s}){this.brandName=` [${e}] `,this.fullName=` ${s} `,this.fullName=es.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(`${es.lightBlue(this.brandName)}${es.blue(` ${e} `)}
2
- `)};cyan=e=>{console.log(`${es.lightCyan(this.brandName)}${es.cyan(` ${e} `)}
3
- `)};magenta=e=>{console.log(`${es.lightMagenta(this.brandName)}${es.magenta(` ${e} `)}
4
- `)};green=e=>{console.log(`${es.lightGreen(this.brandName)}${es.green(` ${e} `)}
5
- `)};yellow=e=>{console.log(`${es.yellow(this.brandName)}${es.orange(` ${e} `)}
6
- `)};red=e=>{console.log(`${es.lightRed(this.brandName)}${es.red(` ${e} `)}
7
- `)};sysError=e=>{console.log(`${es.lightRed(" System Error Tips ")}${es.red(` ${e} `)}
8
- `)};link=e=>es.blue(e);title=e=>{console.log(`${this.fullName}${es.yellow.underline(`${e}`)}
9
- `)}}let eo=new ei;var er=$(import.meta.url);let en=["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"],ea=m(er,{interopDefault:!0,fsCache:!0,moduleCache:!0,cacheVersion:T.rE}),el=async()=>{let e="store.getEmpConfigPath";eo.time(e);let t=en.map(e=>u.resolve(eI.root,e)),s=await Promise.all(t.map(e=>c.promises.access(e).then(()=>!0,()=>!1))),i=t.find((e,t)=>s[t]);return eo.timeEnd(e),i},ep=async()=>{let e=u.join(eI.root,"tsconfig.json");return await c.promises.access(e).then(()=>!0,()=>!1)||(e=void 0),e},eh=()=>{let e="127.0.0.1";try{let{int:t}=f();return d(t||"")||e}catch(t){return e}},ec=e=>{try{let{version:t}=v.readJSONSync(e);return t}catch(e){return}};function em(){process.stdout.write("win32"===process.platform?"\x1b[2J\x1b[0f":"\x1b[2J\x1b[3J\x1b[H")}function eu(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]=eu(o,i);continue}e[t]=s[t]}return e}let eg=e=>Array.isArray(e)?e:[e],ed=(e={},t=[])=>Object.keys(e).filter(e=>!t.includes(e)).reduce((t,s)=>(t[s]=e[s],t),{}),ef=(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},ev=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),I.bold(t)} s`}if(e<60){let t;return`${t=e.toFixed(1),I.bold(t)} s`}let s=e/60;return`${t=s.toFixed(2),I.bold(t)} m`},ey=e=>`data:text/javascript,${e}`,eb={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 eC{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 afterBulid(){this.op.afterBulid&&await this.op.afterBulid()}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 ew=new class{store;appSrc="src";appEntry="";base="";target=[];assign(e,t){return eu(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 eC(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,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:{},target:"es5",useESM:!1,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};return this.assign(o,this.store.empOptions.output)}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 eu({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";if(eo.time(e),!this.store.rootPaths.empConfig)return;let{default:t}=await ea(this.store.rootPaths.empConfig);"function"==typeof t?this.store.empOptions=await t(this.store):this.store.empOptions=t||{},eo.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):eo.title(`${e.cliAction}`)}},eO=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=[er],eI.rootPaths.pkg&&e.push(eI.rootPaths.pkg),eI.rootPaths.empConfig&&e.push(eI.rootPaths.empConfig),eI.rootPaths.tsConfig&&e.push(eI.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:!0,asyncWebAssembly:!0,css:!0},incremental:"advance-silent",lazyCompilation:this.store.isDev,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 v.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:{chunks:"async",cacheGroups:{}}};"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})}},eP=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 ek{apply(e){let{webpack:t}=e;eI.empConfig.build.polyfill.entryCdn||new t.EntryPlugin(e.context,ey(`import 'core-js/${eI.empConfig.build.polyfill.coreJsFeatures}'`),{name:void 0}).apply(e)}}class ej{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=>{C.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 ex=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(C,[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(){eo.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 b([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))}),eo.timeEnd("setAutoPage")}async setDefaultEntry(){let e="store.empConfig.setDefaultEntry";eo.time(e);let t=a.join(this.store.appSrc,this.store.empConfig.appEntry?this.store.empConfig.appEntry:"index.{ts,tsx,jsx,js}"),s=await b([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])}eo.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(){this.store.chain.merge({module:{parser:{javascript:{dynamicImportMode:"lazy",dynamicImportPrefetch:!1,dynamicImportPreload:!1,url:!0,importMeta:!0},css:{namedExports:!1},"css/auto":{namedExports:!1},"css/module":{namedExports:!1}}}})}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={jsc:eu(this.swcJsc(e),{...this.store.empConfig.build.swcConfig}),isModule:"unknown"};return this.isPolyfill&&(delete t.jsc.target,t.env={coreJs:this.swcCoreVersion,targets:this.store.empConfig.build.polyfill.browserslist},this.store.empConfig.isESM||(t.env.mode=this.store.empConfig.build.polyfill.mode),"usage"===this.store.empConfig.build.polyfill.mode&&(t.env.shippedProposals=!0,t.env.include=this.store.empConfig.build.polyfill.include)),t}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=ec(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"}}}})}},eE=new class{store;async setup(e){this.store=e;let t=[this.define(),this.anylayze(),this.progress(),this.copy(),this.minify(),this.redoctor(),this.sourceMapDevToolPlugin(),this.tsCheckerRspackPlugin(),this.cssChunkingPlugin(),this.esmLibraryPlugin()];this.beforeLifeCycle(),await this.store.empConfig.lifeCycle.beforePlugin(),await Promise.all(t),await this.store.empConfig.lifeCycle.afterPlugin()}beforeLifeCycle(){let{store:e}=this;"entry"===e.empConfig.build.polyfill.mode&&e.chain.plugin("empPolyfill").use(ek)}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(){this.store.empConfig.debug.cssChunkingPlugin&&this.store.chain.plugin("CssChunkingPlugin").use(s.experiments.CssChunkingPlugin,[{}])}esmLibraryPlugin(){if(!this.store.empConfig.isESM)return;let{EsmLibraryPlugin:e}=s.experiments;if(!e)return;let t=u.resolve(this.store.root,"src");this.store.chain.plugin("esmLibraryPlugin").use(e,[{preserveModules:t}]),this.store.chain.optimization.merge({runtimeChunk:!0})}},eS=new class{store;async setup(e){this.store=e;let t=[eO.setup(this.store),e$.setup(this.store),eE.setup(this.store),ex.setup(this.store),eP.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()}},eN=(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)})})}),eD=async(e,t)=>{let s=new Set(["EADDRNOTAVAIL","EINVAL"]);for(let i of t)try{await eN(e,i)}catch(e){if(!s.has(e.code))throw e}return e};async function eA(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 eD(i,s)}catch(e){if(!r.has(e.code))throw e;i+=1}throw Error("No available ports found")}class eR{imf={protocol:"",port:8e3,pathname:"/"};host="0.0.0.0";urls={lanUrlForConfig:"",lanUrlForTerminal:et("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=eh;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:I.bold(s),pathname:i})}}let eL=new eR,eT=h(x),e_=["Google Chrome Canary","Google Chrome Dev","Google Chrome Beta","Google Chrome","Microsoft Edge","Brave Browser","Vivaldi","Chromium"],eM=async()=>{let e=process.env.BROWSER;if(!e||!e_.includes(e)){let{stdout:t}=await eT("ps cax");e=e_.find(e=>t.includes(e))}return e},eU=async e=>{if("darwin"===process.platform)try{let t=await eM();if(t){let s=`osascript openChrome.applescript "${encodeURI(e)}" "${t}"`;return await eT(s,{cwd:eI.resource.dir}),!0}}catch(e){eo.debug(e)}try{let{default:t}=await import("open");return await t(e),!0}catch(e){return eo.error("Failed to open start URL."),eo.error(e),!1}};class eF{ip=eh();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 eA(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 eA(e.empConfig.server.port)),eL.setup(this),this.publicPath&&(this.publicPath.indexOf("http://")>-1||this.publicPath.indexOf("https://")>-1)?(this.url=this.publicPath,this.publicHasHttp=!0,this.urls.localUrlForTerminal=eL.prettyPrintUrl("localhost")):(this.urls=eL.urls,this.url=this.urls.localUrlForBrowser)}startOpen(){let{urls:e}=this;this.publicHasHttp?(eo.info(`${z("➜")} Local: ${eo.link(e.localUrlForTerminal)}`),eo.info(`${z("➜")} Network: ${eo.link(this.publicPath)}`)):(eo.info(`${z("➜")} Local: ${eo.link(e.localUrlForTerminal)}`),eo.info(`${z("➜")} Network: ${eo.link(e.lanUrlForTerminal)}
10
- `)),this.isOpenBrower&&eU(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 eA(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 eJ{rspack=i;rspackVersion=i.rspackVersion;isOldRspack=-1===ef(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=F;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=eb;server=new eF(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";eo.time(s),this.beforeSetup&&await this.beforeSetup();let[i,o]=await Promise.all([el(),ep()]);this.rootPaths.empConfig=i,this.rootPaths.tsConfig=o,this.rootPaths.pkg=this.resolve("package.json"),await this.initVars(this.cliAction,this.cliOptions),this.empConfig=ew,await this.empConfig.setup(this),this.debug={...this.empConfig.debug},this.initPaths(),this.chain=new y,await eS.setup(this),this.setLogger(),this.toConfig(),this.logConfig(),await this.server.setupOnStore(),this.afterSetup&&await this.afterSetup(),eo.timeEnd(s),this.debug.clearLog&&em()}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),eo.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?eu(e,this.debug.showRsconfig):e;console.log(eo.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=ef;deepAssign=eu;getLanIp=eh;injectTags(e=[],t="",s=""){this.chain.plugin(`${ej}-${t}`).use(ej,[e,t,s])}}let eI=new eJ;function eH(e){return e}export{A as __webpack_require__,ei as Logger,X as blue,I as chalk,es as color,eu as deepAssign,eH as defineConfig,et as gray,z as green,R as empHelper,eo as logger,ee as magenta,o as program,W as red,i as rspack,_ as runScript,eI as store,ev as timeFormat,Y as white,q as yellow};
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 f}from"address";import{gateway4sync as d}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 x}from"node:child_process";import{fileURLToPath as S}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[e](s,s.exports,D),s.exports}D.m=E,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})},$={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($,s)&&$[s]&&$[s][0](),$[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:()=>ed,getPkgVersion:()=>ey,importJsVm:()=>ek,jsonFilter:()=>ew,timeFormat:()=>eP,vCompare:()=>eO});var M=JSON.parse('{"rE":"4.0.0-alpha.3"}');function T(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",T,{})}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 I(){o.version(M.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("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 B=l(S(import.meta.url)),H=S(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(B,H).replace(`${a.sep}dist${a.sep}index.js`,"")}(B),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
+ `)};cyan=e=>{console.log(`${ea.lightCyan(this.brandName)}${ea.cyan(` ${e} `)}
3
+ `)};magenta=e=>{console.log(`${ea.lightMagenta(this.brandName)}${ea.magenta(` ${e} `)}
4
+ `)};green=e=>{console.log(`${ea.lightGreen(this.brandName)}${ea.green(` ${e} `)}
5
+ `)};yellow=e=>{console.log(`${ea.yellow(this.brandName)}${ea.orange(` ${e} `)}
6
+ `)};red=e=>{console.log(`${ea.lightRed(this.brandName)}${ea.red(` ${e} `)}
7
+ `)};sysError=e=>{console.log(`${ea.lightRed(" System Error Tips ")}${ea.red(` ${e} `)}
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(),ef()]);this.rootPaths.empConfig=i,this.rootPaths.tsConfig=o,this.rootPaths.pkg=this.resolve("package.json"),await this.initVars(this.cliAction,this.cliOptions),this.empConfig=eS,await this.empConfig.setup(this),this.debug={...this.empConfig.debug},this.initPaths(),this.chain=new v,await eM.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=ed;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,eU as getPorts,en as gray,q as green,_ as empHelper,ep as logger,er as magenta,Y as red,i as rspack,I as runScript,eG as store,eP as timeFormat,ei as white,Z as yellow};
package/dist/627.js CHANGED
@@ -1,5 +1,5 @@
1
- import"node:module";import e from"node:fs";import t from"node:path";import{gzipSizeSync as i}from"gzip-size";import{rspackVersion as s}from"@rspack/core";import{chalk as n,logger as o,yellow as r,white as l,magenta as a,store as m,green as p,red as d,gray as u,blue as c,timeFormat as $}from"./346.js";let f=/\.html$/,g=/\.(?:js|mjs|cjs|jsx)$/,h=/\.css$/,b=s=>{let n=s.name.split("?")[0],o=z(s.size),a=t.basename(n),p=t.join(t.basename(m.empConfig.build.outDir),t.dirname(n)),u=e.readFileSync(t.join(m.empConfig.build.outDir,n)),c=u.length,$=i(u),f=($>3e5?d:$>1e5?r:l)(z($));return{size:c,folder:p,name:a,gzippedSize:$,sizeLabel:o,gzipSizeLabel:f}},z=e=>{let t=e/1e3;return`${t.toFixed(t<1?2:1)} kB`};async function x(e){let i,s,l=e.toJson({all:!1,assets:!0,timings:!0}),m=l.assets.filter(e=>{let t;return t=e.name,!/\.map$/.test(t)&&!/\.LICENSE\.txt$/.test(t)}).map(b);m.sort((e,t)=>e.size-t.size);let d=Math.max(...m.map(e=>e.sizeLabel.length)),x=Math.max(...m.map(e=>(e.folder+t.sep+e.name).length));i=[x,d],s=["File","Size","Gzipped"].reduce((e,t,s)=>{let n=i[s],o=t;return n&&(o=t.length<n?t+" ".repeat(n-t.length):t),`${e+o} `}," "),console.log(c.bold(s));let y=0,S=0;m.forEach(e=>{var i;let{sizeLabel:s}=e,{name:n,folder:l,gzipSizeLabel:m}=e,$=(l+t.sep+n).length,b=s.length;y+=e.size,S+=e.gzippedSize,b<d&&(s+=" ".repeat(d-b));let z=u(e.folder+t.sep)+(i=e.name,g.test(i)?r(i):h.test(i)?p(i):f.test(i)?c(i):a(i));$<x&&(z+=" ".repeat(x-$)),o.info(` ${z} ${u(s)} ${m}`)});let E=`${c.bold("Total size:")} ${z(y)}`,k=`${c.bold("Gzipped size:")} ${z(S)}`;o.info(`
2
- ${E}
3
- ${k}
4
- `),o.info(`${n.green("ready ")}Built in ${$(Number(l.time))}
5
- `)}function y(e,t){console.log(("start"===e?n.cyan("start "):n.green("ready "))+n.white(t))}function S(e=0,t="Ready"){o.info(`${n.green("ready ")}${t} in ${$(Number(e))}`)}function E(e="build"){y("start",`${e} Started...`)}function k(e){let t=e?.toJson({all:!1,colors:!1,assets:!1,chunks:!1,timings:!0});y("ready",`built in ${n.bold((t.time/1e3).toFixed(2))} s`)}function F(e="build started..."){y("start",e)}function j(e,t="built"){let i;i="number"==typeof e?(e/1e3).toFixed(2):((e?.toJson({all:!1,colors:!1,assets:!1,chunks:!1,timings:!0})).time/1e3).toFixed(2),y("ready",`${t} in ${n.bold(i)} s`)}class C{async setup(e,t){let i=`${e}.setup`,n=`${e}.run`;o.time(i),await m.setup(e,t),m.empConfig.showLogTitle({cliAction:e,cliOptions:t,rspackVersion:s,empVersion:m.empPkg.version}),o.time(n),await this.run(),this.processExit(),o.timeEnd(n),o.timeEnd(i)}async run(){}processExit(){process.on("SIGINT",function(){process.exit()})}}export{C as BaseScript,j as logDone,F as logStart,k as printBuildDone,E as printBuildStart,x as printFileSizes,S as timeDone};
1
+ import"node:module";import e from"node:fs";import t from"node:path";import{gzipSizeSync as s}from"gzip-size";import{rspackVersion as o}from"@rspack/core";import{chalk as i,logger as n,yellow as r,white as l,magenta as a,store as c,green as m,red as p,gray as d,blue as u,timeFormat as g}from"./346.js";let h=/\.html$/,f=/\.(?:js|mjs|cjs|jsx)$/,$=/\.css$/,b=o=>{let i=o.name.split("?")[0],n=k(o.size),a=t.basename(i),m=t.join(t.basename(c.empConfig.build.outDir),t.dirname(i)),d=e.readFileSync(t.join(c.empConfig.build.outDir,i)),u=d.length,g=s(d),h=(g>3e5?p:g>1e5?r:l)(k(g));return{size:u,folder:m,name:a,gzippedSize:g,sizeLabel:n,gzipSizeLabel:h}},k=e=>{let t=e/1e3;return`${t.toFixed(t<1?2:1)} kB`};async function y(e){let s,o,l=e.toJson({all:!1,assets:!0,timings:!0}),c=l.assets.filter(e=>{let t;return t=e.name,!/\.map$/.test(t)&&!/\.LICENSE\.txt$/.test(t)}).map(b);c.sort((e,t)=>e.size-t.size);let p=Math.max(...c.map(e=>e.sizeLabel.length)),y=Math.max(...c.map(e=>(e.folder+t.sep+e.name).length));s=[y,p],o=["File","Size","Gzipped"].reduce((e,t,o)=>{let i=s[o],n=t;return i&&(n=t.length<i?t+" ".repeat(i-t.length):t),`${e+n} `}," "),console.log(u.bold(o));let z=0,S=0;c.forEach(e=>{var s;let{sizeLabel:o}=e,{name:i,folder:l,gzipSizeLabel:c}=e,g=(l+t.sep+i).length,b=o.length;z+=e.size,S+=e.gzippedSize,b<p&&(o+=" ".repeat(p-b));let k=d(e.folder+t.sep)+(s=e.name,f.test(s)?r(s):$.test(s)?m(s):h.test(s)?u(s):a(s));g<y&&(k+=" ".repeat(y-g)),n.info(` ${k} ${d(o)} ${c}`)});let x=`${u.bold("Total size:")} ${k(z)}`,H=`${u.bold("Gzipped size:")} ${k(S)}`;n.info(`
2
+ ${x}
3
+ ${H}
4
+ `),n.info(`${i.green("ready ")}Built in ${g(Number(l.time))}
5
+ `)}function z(e,t){console.log(("start"===e?i.cyan("start "):i.green("ready "))+i.white(t))}function S(e=0,t="Ready"){n.info(`${i.green("ready ")}${t} in ${g(Number(e))}`)}function x(e="build"){z("start",`${e} Started...`)}function H(e){let t=e?.toJson({all:!1,colors:!1,assets:!1,chunks:!1,timings:!0});z("ready",`built in ${i.bold((t.time/1e3).toFixed(2))} s`)}function E(e="build started..."){z("start",e)}function C(e,t="built"){let s;s="number"==typeof e?(e/1e3).toFixed(2):((e?.toJson({all:!1,colors:!1,assets:!1,chunks:!1,timings:!0})).time/1e3).toFixed(2),z("ready",`${t} in ${i.bold(s)} s`)}class F{static isSigintRegistered=!1;closeHooks=[];addCloseHook(e){this.closeHooks.push(e)}async executeCloseHooks(){if(this.closeHooks.length>0){for(let e of(n.debug(`[EMP] 执行 ${this.closeHooks.length} 个Hook...`),this.closeHooks))try{await e()}catch(e){n.error("[EMP] 执行清理钩子时出错:",e)}this.closeHooks=[]}}async setup(e,t){let s=`${e}.setup`,i=`${e}.run`;n.time(s),await c.setup(e,t),c.empConfig.showLogTitle({cliAction:e,cliOptions:t,rspackVersion:o,empVersion:c.empPkg.version}),n.time(i),await this.run(),this.processExit(),n.timeEnd(i),n.timeEnd(s)}async run(){}processExit(){F.isSigintRegistered||(F.isSigintRegistered=!0,process.once("SIGINT",async()=>{await this.executeCloseHooks(),process.exit()}))}}export{F as BaseScript,C as logDone,E as logStart,H as printBuildDone,x as printBuildStart,y as printFileSizes,S as timeDone};
@@ -0,0 +1,25 @@
1
+ import type { CommandResult, CreateOptions, CreateProjectPlan } from './types';
2
+ interface CreateCommandInput {
3
+ name: string;
4
+ command: string;
5
+ args: string[];
6
+ cwd: string;
7
+ timeoutMs: number;
8
+ }
9
+ interface StartDevCommandOptions {
10
+ command?: string;
11
+ args?: string[];
12
+ startupWindowMs?: number;
13
+ readinessTimeoutMs?: number;
14
+ readinessPollIntervalMs?: number;
15
+ }
16
+ type CreateDevPlan = Pick<CreateProjectPlan, 'rootDir'> & Partial<Pick<CreateProjectPlan, 'apps'>>;
17
+ interface CreateCommandRuntime {
18
+ runCommandForCreate?: (input: CreateCommandInput) => Promise<CommandResult>;
19
+ startDevCommandForCreate?: (plan: CreateDevPlan, options?: StartDevCommandOptions) => Promise<CommandResult>;
20
+ devCommand?: StartDevCommandOptions;
21
+ }
22
+ export declare function runCommandForCreate(input: CreateCommandInput): Promise<CommandResult>;
23
+ export declare function startDevCommandForCreate(plan: CreateDevPlan, options?: StartDevCommandOptions): Promise<CommandResult>;
24
+ export declare function runCreateCommands(plan: Pick<CreateProjectPlan, 'rootDir' | 'apps'>, options: Pick<CreateOptions, 'install' | 'verify' | 'dev'>, runtime?: CreateCommandRuntime): Promise<CommandResult[]>;
25
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { CreateProjectPlan, FixResult, VerificationCheck } from './types';
2
+ export declare function fixGeneratedProject(plan: CreateProjectPlan, checks: VerificationCheck[]): Promise<FixResult[]>;
@@ -0,0 +1,4 @@
1
+ import type { CreateProjectPlan, GeneratedFile } from './types';
2
+ export declare function generateProject(plan: CreateProjectPlan, options: {
3
+ dryRun: boolean;
4
+ }): Promise<GeneratedFile[]>;
@@ -0,0 +1,2 @@
1
+ import type { CreateIntent } from './types';
2
+ export declare function parseCreateIntent(input: string): CreateIntent;
@@ -0,0 +1,3 @@
1
+ import type { CreateIntent, CreateOptions, CreateProjectPlan } from './types';
2
+ export declare function createProjectPlan(intent: CreateIntent, options: CreateOptions): CreateProjectPlan;
3
+ export declare function assignAvailableCreatePorts(plan: CreateProjectPlan): Promise<CreateProjectPlan>;
@@ -0,0 +1,3 @@
1
+ import type { CommandResult, CreateProjectPlan, EmpCreateReport, VerificationCheck } from './types';
2
+ export declare function buildCreateReport(plan: CreateProjectPlan, checks: VerificationCheck[], commands: CommandResult[]): EmpCreateReport;
3
+ export declare function writeCreateReport(report: EmpCreateReport): Promise<void>;
@@ -0,0 +1,4 @@
1
+ import type { CreateProjectPlan, GeneratedFile } from './types';
2
+ type PlannedProject = Omit<CreateProjectPlan, 'files'>;
3
+ export declare function createTemplateFiles(plan: PlannedProject): GeneratedFile[];
4
+ export {};
@@ -0,0 +1,71 @@
1
+ export type Framework = 'react' | 'vue';
2
+ export type AppRole = 'host' | 'remote';
3
+ export type CheckStatus = 'passed' | 'failed' | 'skipped';
4
+ export interface CreateIntent {
5
+ raw: string;
6
+ host: {
7
+ framework: 'react';
8
+ name: 'host';
9
+ };
10
+ remotes: [{
11
+ framework: 'vue';
12
+ name: 'user';
13
+ }];
14
+ }
15
+ export interface CreateOptions {
16
+ targetDir: string;
17
+ dryRun: boolean;
18
+ install: boolean;
19
+ dev: boolean;
20
+ verify: boolean;
21
+ json: boolean;
22
+ }
23
+ export interface CreateAppPlan {
24
+ name: string;
25
+ role: AppRole;
26
+ framework: Framework;
27
+ port: number;
28
+ }
29
+ export interface GeneratedFile {
30
+ path: string;
31
+ content: string;
32
+ }
33
+ export interface CreateProjectPlan {
34
+ rootName: string;
35
+ rootDir: string;
36
+ intent: CreateIntent;
37
+ options: CreateOptions;
38
+ packageManager: 'pnpm';
39
+ apps: CreateAppPlan[];
40
+ files: GeneratedFile[];
41
+ }
42
+ export interface VerificationCheck {
43
+ name: string;
44
+ status: CheckStatus;
45
+ message: string;
46
+ }
47
+ export interface FixResult {
48
+ name: string;
49
+ status: 'applied' | 'skipped';
50
+ message: string;
51
+ }
52
+ export interface CommandResult {
53
+ name: string;
54
+ command: string;
55
+ status: CheckStatus;
56
+ exitCode: number | null;
57
+ stdout: string;
58
+ stderr: string;
59
+ }
60
+ export interface EmpCreateReport {
61
+ status: CheckStatus;
62
+ rootDir: string;
63
+ apps: Array<{
64
+ name: string;
65
+ role: AppRole;
66
+ framework: Framework;
67
+ url: string;
68
+ }>;
69
+ checks: VerificationCheck[];
70
+ commands: CommandResult[];
71
+ }
@@ -0,0 +1,2 @@
1
+ import type { CreateProjectPlan, VerificationCheck } from './types';
2
+ export declare function verifyGeneratedProject(plan: CreateProjectPlan): Promise<VerificationCheck[]>;
package/dist/build.js CHANGED
@@ -1 +1 @@
1
- import"node:module";import{rspack as s}from"@rspack/core";import{BaseScript as e,printFileSizes as i}from"./627.js";import{logger as t,store as r}from"./346.js";let o=new class extends e{isWatchMode=!1;rspackConfig;isuseServe=!1;isStartServe=!1;watchMode(){this.isWatchMode&&this.rspackConfig.optimization&&(this.rspackConfig.optimization.moduleIds="named",this.rspackConfig.optimization.chunkIds="named",this.rspackConfig.watch=!0)}async startServe(){if(!this.isuseServe||this.isStartServe)return;this.isStartServe=!0;let{default:s}=await import("./serve.js");await s.setup("serve",r.cliOptions)}async run(){await r.empConfig.lifeCycle.beforeBuild(),this.isWatchMode=!!r.cliOptions.watch,this.isuseServe=!!r.cliOptions.serve,this.rspackConfig=r.rsConfig,this.isWatchMode&&this.watchMode(),s(this.rspackConfig,async(s,e)=>{if(console.log("\n"),r.debug.showScriptDebug&&console.log(e?.toString()),null!==s){t.error(s.stack||s),s.message&&t.error(s.message);return}e?(e.hasErrors()&&(t.error(e.toString({all:!1,colors:!0,errors:!0})),t.red("Failed to compile."),process.exit(1)),e.hasWarnings()&&(t.yellow("Compiled with warnings."),t.warn(e.toString({all:!1,chunks:!1,assets:!1,colors:!0,errors:!0,warnings:!0}))),await i(e),this.startServe(),await r.empConfig.lifeCycle.afterBulid()):t.red("Stats is Undefined.")})}};export default o;
1
+ import"node:module";import{rspack as e}from"@rspack/core";import{BaseScript as r,printFileSizes as s}from"./627.js";import{logger as i,store as t}from"./346.js";let o=new class extends r{isWatchMode=!1;rspackConfig;isuseServe=!1;isStartServe=!1;watchMode(){this.isWatchMode&&(this.rspackConfig.watch=!0,this.rspackConfig.optimization={...this.rspackConfig.optimization,moduleIds:"named",chunkIds:"named"})}async startServe(){if(!this.isuseServe||this.isStartServe)return;this.isStartServe=!0;let{default:e}=await import("./serve.js");await e.setup("serve",t.cliOptions)}async run(){await t.empConfig.lifeCycle.beforeBuild(),this.isWatchMode=!!t.cliOptions.watch,this.isuseServe=!!t.cliOptions.serve,this.rspackConfig=t.rsConfig,this.isWatchMode&&this.watchMode(),await new Promise((r,o)=>{e(this.rspackConfig,async(e,a)=>{try{if(console.log("\n"),t.debug.showScriptDebug&&console.log(a?.toString()),e){i.error(e.stack||e),e.message&&i.error(e.message),process.exitCode=1,o(e);return}if(!a){let e=Error("Stats is Undefined.");i.red(e.message),process.exitCode=1,o(e);return}if(a.hasErrors()){i.error(a.toString({all:!1,colors:!0,errors:!0})),i.red("Failed to compile."),process.exitCode=1,o(Error("Failed to compile."));return}a.hasWarnings()&&(i.yellow("Compiled with warnings."),i.warn(a.toString({all:!1,chunks:!1,assets:!1,colors:!0,errors:!0,warnings:!0}))),await s(a),await this.startServe(),await t.empConfig.lifeCycle.afterBuild(),r()}catch(e){process.exitCode=1,o(e)}})})}};export default o;
package/dist/create.js ADDED
@@ -0,0 +1,102 @@
1
+ import"node:module";import e from"node:fs/promises";import t from"node:path";import{execFile as r,spawn as o}from"node:child_process";import n from"node:fs";import a from"node:http";import s from"node:https";import i from"node:os";import{promisify as p}from"node:util";import{getPorts as m}from"./346.js";async function l(t){try{return(await e.readdir(t)).length>0}catch(e){if("ENOENT"===e.code)return!1;throw e}}async function c(r,o){let n=r.files.map(e=>({file:e,absolutePath:function(e,r){if(t.isAbsolute(r)||t.win32.isAbsolute(r))throw Error(`文件路径必须是相对路径: ${r}`);if(r.split(/[\\/]+/).includes(".."))throw Error(`文件路径不能逃逸目标目录: ${r}`);let o=t.resolve(e,r),n=t.relative(e,o);if(n.startsWith("..")||t.isAbsolute(n))throw Error(`文件路径不能逃逸目标目录: ${r}`);return o}(r.rootDir,e.path)}));if(o.dryRun)return r.files;if(await l(r.rootDir))throw Error("目标目录已存在且非空,EMP 不会覆盖已有项目");for(let{file:r,absolutePath:o}of n)await e.mkdir(t.dirname(o),{recursive:!0}),await e.writeFile(o,r.content,"utf8");return r.files}let u="[A-Za-z0-9_-]";function d(e){return"host"===e?`(?:host(?!${u})|主应用)`:`(?:remote(?!${u})|子应用)`}function f(e,t){let r=RegExp(`(?<!${u})${d(t)}`,"gi");return Array.from(e.matchAll(r)).length}function h(e,t,r){let o=RegExp(`(?<!${u})${t}\\s*${d(r)}`,"gi");return Array.from(e.matchAll(o)).length}let g="^4.0.0-alpha.2";function w(e){return`${JSON.stringify(e,null,2)}
2
+ `}function y(e,t){let r=e.apps.find(e=>e.role===t);if(!r)throw Error(`缺少 ${t} 应用计划`);return r}function v(e){let t,r,o,n,a;return[{path:"package.json",content:w({name:e.rootName,version:"0.0.0",private:!0,type:"module",packageManager:"pnpm@10.33.0",engines:{node:"^20.19.0 || >=22.12.0",pnpm:"10.x"},scripts:{dev:'pnpm --parallel --filter "./apps/*" dev',build:'pnpm --filter "./apps/*" build',verify:'pnpm --filter "./apps/*" build'},devDependencies:{"@empjs/cli":g,"@empjs/plugin-react":g,"@empjs/plugin-vue3":g,"@empjs/share":g,typescript:"^5.9.2"}})},{path:"pnpm-workspace.yaml",content:`packages:
3
+ - apps/*
4
+ `},{path:"emp.intent.yaml",content:(t=y(e,"host"),r=y(e,"remote"),`name: ${e.rootName}
5
+ intent: ${JSON.stringify(e.intent.raw)}
6
+ packageManager: pnpm
7
+ apps:
8
+ - name: ${t.name}
9
+ role: ${t.role}
10
+ framework: ${t.framework}
11
+ port: ${t.port}
12
+ - name: ${r.name}
13
+ role: ${r.role}
14
+ framework: ${r.framework}
15
+ port: ${r.port}
16
+ shared:
17
+ react: singleton
18
+ react-dom: singleton
19
+ `)},{path:"apps/host/package.json",content:w({name:"host",version:"0.0.0",private:!0,type:"module",scripts:{dev:"emp dev",build:"emp build",start:"emp serve"},dependencies:{"@empjs/bridge-react":g,"@empjs/bridge-vue3":g,"@empjs/cli":g,"@empjs/plugin-react":g,"@empjs/share":g,react:"^19.0.0","react-dom":"^19.0.0",vue:"^3.5.21"},devDependencies:{"@types/react":"^19.0.0","@types/react-dom":"^19.0.0",typescript:"^5.9.2"}})},{path:"apps/host/emp.config.ts",content:(o=y(e,"host"),n=y(e,"remote"),`import {defineConfig} from '@empjs/cli'
20
+ import pluginReact from '@empjs/plugin-react'
21
+ import {pluginRspackEmpShare} from '@empjs/share/rspack'
22
+
23
+ export default defineConfig({
24
+ appEntry: 'main.tsx',
25
+ html: {mountId: 'root'},
26
+ server: {port: ${o.port}},
27
+ plugins: [
28
+ pluginReact(),
29
+ pluginRspackEmpShare({
30
+ name: '${o.name}',
31
+ remotes: {
32
+ ${n.name}: '${n.name}@http://localhost:${n.port}/emp.js',
33
+ },
34
+ shared: {
35
+ react: {singleton: true},
36
+ 'react-dom': {singleton: true},
37
+ },
38
+ }),
39
+ ],
40
+ })
41
+ `)},{path:"apps/host/src/main.tsx",content:`import React from 'react'
42
+ import {createRoot} from 'react-dom/client'
43
+ import App from './App'
44
+
45
+ createRoot(document.getElementById('root')!).render(<App />)
46
+ `},{path:"apps/host/src/App.tsx",content:`import React from 'react'
47
+ import * as Vue from 'vue'
48
+ import {createRemoteAppComponent} from '@empjs/bridge-react'
49
+ import {createBridgeComponent} from '@empjs/bridge-vue3'
50
+
51
+ const RemoteApp = React.lazy(async () => {
52
+ const module = await import('user/App')
53
+ const BridgeComponent = createBridgeComponent(module.default, {Vue})
54
+ return {default: createRemoteAppComponent(BridgeComponent, {React})}
55
+ })
56
+
57
+ export default function App() {
58
+ return (
59
+ <main>
60
+ <h1>EMP Host</h1>
61
+ <React.Suspense fallback={<p>Loading remote...</p>}>
62
+ <RemoteApp />
63
+ </React.Suspense>
64
+ </main>
65
+ )
66
+ }
67
+ `},{path:"apps/host/src/remotes.d.ts",content:`declare module 'user/App' {
68
+ const App: unknown
69
+ export default App
70
+ }
71
+ `},{path:"apps/user/package.json",content:w({name:"user",version:"0.0.0",private:!0,type:"module",scripts:{dev:"emp dev",build:"emp build",start:"emp serve"},dependencies:{"@empjs/cli":g,"@empjs/plugin-vue3":g,"@empjs/share":g,vue:"^3.5.21"},devDependencies:{typescript:"^5.9.2"}})},{path:"apps/user/emp.config.ts",content:(a=y(e,"remote"),`import {defineConfig} from '@empjs/cli'
72
+ import pluginVue from '@empjs/plugin-vue3'
73
+ import {pluginRspackEmpShare} from '@empjs/share/rspack'
74
+
75
+ export default defineConfig({
76
+ appEntry: 'main.ts',
77
+ html: {mountId: 'app'},
78
+ server: {port: ${a.port}},
79
+ plugins: [
80
+ pluginVue(),
81
+ pluginRspackEmpShare({
82
+ name: '${a.name}',
83
+ exposes: {
84
+ './App': './src/App.vue',
85
+ },
86
+ }),
87
+ ],
88
+ })
89
+ `)},{path:"apps/user/src/main.ts",content:`import {createApp} from 'vue'
90
+ import App from './App.vue'
91
+
92
+ createApp(App).mount('#app')
93
+ `},{path:"apps/user/src/App.vue",content:`<template>
94
+ <section>
95
+ <h2>EMP Remote</h2>
96
+ <p>Vue remote is running.</p>
97
+ </section>
98
+ </template>
99
+ `}]}async function k(e){if(e.options.dryRun||!e.options.dev)return e;let t=e.apps.find(e=>"host"===e.role),r=e.apps.find(e=>"remote"===e.role);if(!t||!r)return e;let o=await m(t.port),n=await m(Math.max(r.port,o+1)),a=e.apps.map(e=>"host"===e.role?{...e,port:o}:"remote"===e.role?{...e,port:n}:e),s={rootName:e.rootName,rootDir:e.rootDir,intent:e.intent,options:e.options,packageManager:e.packageManager,apps:a};return{...s,files:v(s)}}function $(e,t,r){let o,n;return{status:(o=t.every(e=>"passed"===e.status||"skipped"===e.status),n=r.every(e=>"passed"===e.status||"skipped"===e.status),o&&n?"passed":"failed"),rootDir:e.rootDir,apps:e.apps.map(e=>({name:e.name,role:e.role,framework:e.framework,url:`http://localhost:${e.port}`})),checks:t,commands:r}}async function j(r){let o=t.join(r.rootDir,"emp-report.json"),n=t.join(r.rootDir,`emp-report.json.${process.pid}.${Date.now()}.tmp`);await e.mkdir(r.rootDir,{recursive:!0});try{await e.writeFile(n,`${JSON.stringify(r,null,2)}
100
+ `,"utf8"),await e.rename(n,o)}catch(t){throw await e.rm(n,{force:!0}).catch(()=>{}),t}}let E=p(r);function R(e,t){return[e,...t].join(" ")}function b(e){return e?.toString()??""}function D(e,t,r){return{name:e,command:t,status:"skipped",exitCode:null,stdout:"",stderr:r}}function A(e,t,r){return D(e,t,`由于前置命令 ${r.name} 失败,已跳过`)}function S(e){try{let t=n.readFileSync(e,"utf8");return t.length>131072?t.slice(-131072):t}catch{return""}}function x(e,t){return e?`${e.trimEnd()}
101
+ ${t}`:t}async function C(e,t){return(await Promise.all(e.map(async e=>{try{return await new Promise((r,o)=>{let n=new URL(e),i=("https:"===n.protocol?s:a).get(n,e=>{let t=e.statusCode??0;e.resume(),e.once("end",()=>{t>=200&&t<400?r():o(Error(`HTTP ${t}`))})});i.setTimeout(t,()=>{i.destroy(Error(`timeout after ${t}ms`))}),i.once("error",o)}),null}catch(r){let t=r instanceof Error?r.message:String(r);return`${e} (${t})`}}))).filter(e=>!!e)}async function M(e,t){let r=function(e){let t=e.apps??[],r=t.find(e=>"host"===e.role),o=t.filter(e=>"remote"===e.role),n=[];for(let e of(r&&n.push(`http://localhost:${r.port}/`),o))n.push(`http://localhost:${e.port}/emp.js`);return n}(e),o=t.readinessTimeoutMs??1e4,n=t.readinessPollIntervalMs??250,a=Math.min(1e3,Math.max(50,n));if(0===r.length)return{ok:!1,message:"readiness probe failed: create plan does not include host/remote app URLs"};let s=Date.now()+o,i=r.map(e=>`${e} (not probed)`);for(;Date.now()<=s;){if(0===(i=await C(r,a)).length)return{ok:!0,message:`readiness probes passed: ${r.join(", ")}`};let e=s-Date.now();if(e<=0)break;await function(e){return new Promise(t=>setTimeout(t,e))}(Math.min(n,e))}return{ok:!1,message:`readiness probe failed after ${o}ms: ${i.join("; ")}`}}function N(e){if(e.pid)try{process.kill(-e.pid,"SIGTERM")}catch{try{process.kill(e.pid,"SIGTERM")}catch{}}}async function P(e){let t=R(e.command,e.args);try{let{stdout:r,stderr:o}=await E(e.command,e.args,{cwd:e.cwd,timeout:e.timeoutMs,maxBuffer:0xa00000});return{name:e.name,command:t,status:"passed",exitCode:0,stdout:r,stderr:o}}catch(r){return{name:e.name,command:t,status:"failed",exitCode:"number"==typeof r.code?r.code:null,stdout:b(r.stdout),stderr:b(r.stderr)||r.message}}}async function T(e,r={}){let a,s=r.command??"pnpm",p=r.args??["dev"],m=r.startupWindowMs??1e3,l=R(s,p),c=n.mkdtempSync(t.join(i.tmpdir(),"emp-create-dev-")),u=t.join(c,"stdout.log"),d=t.join(c,"stderr.log"),f=n.openSync(u,"a"),h=n.openSync(d,"a");try{a=o(s,p,{cwd:e.rootDir,detached:!0,stdio:["ignore",f,h]})}catch(e){return n.closeSync(f),n.closeSync(h),{name:"dev",command:l,status:"failed",exitCode:null,stdout:"",stderr:e instanceof Error?e.message:String(e)}}return n.closeSync(f),n.closeSync(h),new Promise(t=>{let o,n=!1,s=e=>{n||(n=!0,clearTimeout(o),a.off("error",i),a.off("exit",p),t(e))},i=e=>{s({name:"dev",command:l,status:"failed",exitCode:null,stdout:S(u),stderr:x(S(d),e.message)})},p=(e,t)=>{let r=`dev command exited before startup window (code=${e??"null"}, signal=${t??"null"})`;s({name:"dev",command:l,status:"failed",exitCode:e,stdout:S(u),stderr:x(S(d),r)})};a.once("error",i),a.once("exit",p),o=setTimeout(()=>{(async()=>{try{let t=await M(e,r);if(!t.ok){n||N(a),s({name:"dev",command:l,status:"failed",exitCode:null,stdout:x(S(u),`pid=${a.pid}`),stderr:x(S(d),t.message)});return}a.unref(),s({name:"dev",command:l,status:"passed",exitCode:null,stdout:x(S(u),`pid=${a.pid}`),stderr:S(d)})}catch(e){n||N(a),s({name:"dev",command:l,status:"failed",exitCode:null,stdout:x(S(u),`pid=${a.pid}`),stderr:x(S(d),e instanceof Error?e.message:String(e))})}})()},m)})}async function O(e,t,r={}){let o=[],n=r.runCommandForCreate??P,a=r.startDevCommandForCreate??T;o.push(t.install?await n({name:"install",command:"pnpm",args:["install"],cwd:e.rootDir,timeoutMs:12e4}):D("install","pnpm install","已通过 --skip-install 跳过"));let s=o[0];if(s?.status==="failed")return o.push(A("build","pnpm build",s)),o.push(A("dev","pnpm dev",s)),o;if(s?.status==="skipped")return o.push(t.verify?D("build","pnpm build","由于依赖安装已跳过,已跳过 build 命令;静态 verify 仍会执行"):D("build","pnpm build","已通过 --skip-verify 跳过")),o.push(t.dev?D("dev","pnpm dev","由于依赖安装已跳过,已跳过 dev 命令"):D("dev","pnpm dev","已通过 --skip-dev 跳过")),o;o.push(t.verify?await n({name:"build",command:"pnpm",args:["build"],cwd:e.rootDir,timeoutMs:12e4}):D("build","pnpm build","已通过 --skip-verify 跳过"));let i=o[1];return i?.status==="failed"?o.push(A("dev","pnpm dev",i)):o.push(t.dev?await a(e,r.devCommand):D("dev","pnpm dev","已通过 --skip-dev 跳过")),o}async function F(r,o,n){try{let a=await e.readFile(t.join(r,o),"utf8");return n.test(a)}catch(e){if("ENOENT"===e.code)return!1;throw e}}async function I(r,o,n){try{let a=await e.readFile(t.join(r,o),"utf8");return n.every(e=>a.includes(e))}catch(e){if("ENOENT"===e.code)return!1;throw e}}function V(e,t){return{name:e,status:"passed",message:t}}function _(e,t){return{name:e,status:"failed",message:t}}async function B(r){let o=[];try{JSON.parse(await e.readFile(t.join(r.rootDir,"package.json"),"utf8")),o.push(V("root-package","根 package.json 可解析"))}catch{o.push(_("root-package","根 package.json 不存在或不可解析"))}o.push(await F(r.rootDir,"pnpm-workspace.yaml",/apps\/\*/)?V("workspace","pnpm workspace 已包含 apps/*"):_("workspace","pnpm workspace 未包含 apps/*")),o.push(await F(r.rootDir,"emp.intent.yaml",/role: host/)&&await F(r.rootDir,"emp.intent.yaml",/role: remote/)?V("intent","emp.intent.yaml 已记录 host/remote 意图"):_("intent","emp.intent.yaml 缺少 host/remote 意图"));let n=r.apps.filter(e=>"remote"===e.role).map(e=>`${e.name}@http://localhost:${e.port}/emp.js`);return o.push(n.length>0&&await I(r.rootDir,"apps/host/emp.config.ts",n)?V("host-config",`host 已配置计划 remote: ${n.join(", ")}`):_("host-config",`host 未配置计划 remote: ${n.join(", ")}`)),o.push(await F(r.rootDir,"apps/user/emp.config.ts",/'\.\/App': '\.\/src\/App\.vue'/)?V("remote-config","remote 已暴露 ./App"):_("remote-config","remote 未暴露 ./App")),o}function J(e,t,r){if("failed"===e.status&&(process.exitCode=1,!r)){for(let r of(console.log("EMP 新项目创建失败"),console.log(`目录: ${e.rootDir}`),console.log(`报告: ${t}`),e.checks.filter(e=>"failed"===e.status)))console.log(`失败检查: ${r.name} - ${r.message}`);for(let t of e.commands.filter(e=>"failed"===e.status))console.log(`失败命令: ${t.name} - ${t.command}`)}}function H(e){return e instanceof Error?e.message:String(e)}function L(e,t,r,o="写入失败报告失败"){return{...e,status:"failed",checks:[...e.checks,{name:"report",status:"failed",message:`${o}: ${t} - ${H(r)}`}]}}async function U(t){try{return await e.access(t),!0}catch(e){if("ENOENT"===e.code)return!1;throw e}}async function z(r,o){if(await U(o))return;await e.mkdir(t.dirname(o),{recursive:!0});let n=`${o}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`,a=!1;try{await e.writeFile(n,`${JSON.stringify(r,null,2)}
102
+ `,{encoding:"utf8",flag:"wx"}),a=!0;try{await e.link(n,o)}catch(e){if("EEXIST"===e.code)return;throw e}}finally{if(a)try{await e.unlink(n)}catch(e){if("ENOENT"!==e.code)throw e}}}async function G(e,r={}){var o,n,a;let s,i,p={targetDir:t.resolve(r.dir??"emp-app"),dryRun:!!r.dryRun,install:!r.skipInstall,dev:!r.skipDev,verify:!r.skipVerify,json:!!r.json},m=(i=t.resolve(p.targetDir),{rootName:t.basename(i),rootDir:i,intent:{raw:e.trim(),host:{framework:"react",name:"host"},remotes:[{framework:"vue",name:"user"}]},options:{...p,targetDir:i},packageManager:"pnpm",apps:[{name:"host",role:"host",framework:"react",port:3e3},{name:"user",role:"remote",framework:"vue",port:3001}],files:[]}),l=t.join(m.rootDir,"emp-report.json"),u=[],d=[],g=[],w="create";try{let r=function(e){let t=e.trim();if(!t)throw Error("create 命令需要项目意图,例如:React 主应用 + Vue 子应用");let r=h(t,"react","host"),o=h(t,"vue","remote");if(0===r||0===o)throw Error("P0 仅支持 React 主应用 + Vue 子应用");if(1!==r||1!==o||1!==f(t,"host")||1!==f(t,"remote"))throw Error("P0 仅支持单 host + 单 remote");return{raw:t,host:{framework:"react",name:"host"},remotes:[{framework:"vue",name:"user"}]}}(e);if(m=await k(function(e,r){var o=e.remotes;if(1!==o.length)throw Error("P0 仅支持单 host + 单 remote");let n=t.resolve(r.targetDir),a=t.basename(n),s={...r},[i]=e.remotes,p={rootName:a,rootDir:n,intent:e,options:s,packageManager:"pnpm",apps:[{name:e.host.name,role:"host",framework:e.host.framework,port:3e3},{name:i.name,role:"remote",framework:i.framework,port:3001}]};return{...p,files:v(p)}}(r,p)),u=await c(m,{dryRun:m.options.dryRun}),w="commands",d=m.options.dryRun?[]:await O(m,{install:m.options.install,verify:m.options.verify,dev:m.options.dev}),w="verify",g=m.options.verify&&!m.options.dryRun?await B(m):[],s=$(m,g,d),!m.options.dryRun)try{await j(s)}catch(e){s=L(s,l,e,"写入创建报告失败")}}catch(e){if(s=function(e,t,r=[],o=[],n="create"){return $(e,[...r,{name:n,status:"failed",message:H(t)}],o)}(m,e,g,d,w),!m.options.dryRun)try{await z(s,l)}catch(e){s=L(s,l,e)}}if(m.options.json){o=m,n=u,a=s,console.log(JSON.stringify({plan:o,files:n.map(e=>e.path),report:a,reportPath:l},null,2)),J(s,l,!0);return}J(s,l,!1),"failed"!==s.status&&(console.log(m.options.dryRun?"EMP create dry-run 完成":"EMP 新项目创建完成"),console.log(`目录: ${m.rootDir}`),console.log(`文件数: ${u.length}`),m.options.dryRun||console.log(`报告: ${l}`))}export{G as runCreateCommand};
package/dist/dev.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /*! LICENSE: dev.js.LICENSE.txt */
2
- import t from"node:module";let e=t.createRequire(import.meta.url);import{rspack as i}from"@rspack/core";import s,{stat as r,unwatchFile as a,watch as o,watchFile as n}from"fs";import{lstat as h,open as l,readdir as d,realpath as c,stat as f}from"fs/promises";import{EventEmitter as m}from"events";import{lstat as p,readdir as u,realpath as w,stat as _}from"node:fs/promises";import{Readable as g}from"node:stream";import{join as y,relative as v,resolve as b,sep as P}from"node:path";import{type as E}from"os";import k,*as S from"path";import{printBuildDone as x,logStart as D,printBuildStart as C,logDone as F,BaseScript as W}from"./627.js";import{chalk as R,logger as z,deepAssign as M,store as j}from"./346.js";import{DevServer as I}from"./server.js";let A="files",O="directories",T="files_directories",H={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:A,lstat:!1,depth:0x80000000,alwaysStat:!1,highWaterMark:4096};Object.freeze(H);let N="READDIRP_RECURSIVE_ERROR",U=new Set(["ENOENT","EPERM","EACCES","ELOOP",N]),L=[O,"all",T,A],$=new Set([O,"all",T]),K=new Set(["all",T,A]),q="win32"===process.platform,V=t=>!0,B=t=>{if(void 0===t)return V;if("function"==typeof t)return t;if("string"==typeof t){let e=t.trim();return t=>t.basename===e}if(Array.isArray(t)){let e=t.map(t=>t.trim());return t=>e.some(e=>t.basename===e)}return V};class G extends g{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let e={...H,...t},{root:i,type:s}=e;this._fileFilter=B(e.fileFilter),this._directoryFilter=B(e.directoryFilter);let r=e.lstat?p:_;q?this._stat=t=>r(t,{bigint:!0}):this._stat=r,this._maxDepth=e.depth??H.depth,this._wantsDir=!!s&&$.has(s),this._wantsFile=!!s&&K.has(s),this._wantsEverything="all"===s,this._root=b(i),this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,i=e&&e.files;if(i&&i.length>0){let{path:s,depth:r}=e,a=i.splice(0,t).map(t=>this._formatEntry(t,s));for(let e of(await Promise.all(a))){if(!e)continue;if(this.destroyed)return;let i=await this._getEntryType(e);"directory"===i&&this._directoryFilter(e)?(r<=this._maxDepth&&this.parents.push(this._exploreDir(e.fullPath,r+1)),this._wantsDir&&(this.push(e),t--)):("file"===i||this._includeAsFile(e))&&this._fileFilter(e)&&this._wantsFile&&(this.push(e),t--)}}else{let t=this.parents.pop();if(!t){this.push(null);break}if(this.parent=await t,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(t,e){let i;try{i=await u(t,this._rdOptions)}catch(t){this._onError(t)}return{files:i,depth:e,path:t}}async _formatEntry(t,e){let i,s=this._isDirent?t.name:t;try{let r=b(y(e,s));(i={path:v(this._root,r),fullPath:r,basename:s})[this._statsProp]=this._isDirent?t:await this._stat(r)}catch(t){this._onError(t);return}return i}_onError(t){U.has(t.code)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let e=t[this._statsProp];if(e.isFile())return"file";if(e.isDirectory())return"directory";if(e&&e.isSymbolicLink()){let e=t.fullPath;try{let t=await w(e),i=await p(t);if(i.isFile())return"file";if(i.isDirectory()){let i=t.length;if(e.startsWith(t)&&e.substr(i,1)===P){let i=Error(`Circular symlink detected: "${e}" points to "${t}"`);return i.code=N,this._onError(i)}return"directory"}}catch(t){return this._onError(t),""}}}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}}let J=()=>{},Q=process.platform,X="win32"===Q,Y="darwin"===Q,Z="linux"===Q,tt="freebsd"===Q,te="OS400"===E(),ti="all",ts="ready",tr="add",ta="change",to="addDir",tn="unlink",th="unlinkDir",tl="raw",td="error",tc={lstat:h,stat:f},tf="listeners",tm="errHandlers",tp="rawEmitters",tu=[tf,tm,tp],tw=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),t_=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},tg=(t,e,i)=>{let s=t[e];s instanceof Set||(t[e]=s=new Set([s])),s.add(i)},ty=(t,e,i)=>{let s=t[e];s instanceof Set?s.delete(i):s===i&&delete t[e]},tv=t=>t instanceof Set?0===t.size:!t,tb=new Map;function tP(t,e,i,s,r){try{return o(t,{persistent:e.persistent},(e,s)=>{i(t),r(e,s,{watchedPath:t}),s&&t!==s&&tE(S.resolve(t,s),tf,S.join(t,s))})}catch(t){s(t);return}}let tE=(t,e,i,s,r)=>{let a=tb.get(t);a&&t_(a[e],t=>{t(i,s,r)})},tk=new Map;class tS{constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let i,s=this.fsw.options,r=S.dirname(t),o=S.basename(t);this.fsw._getWatchedDir(r).add(o);let h=S.resolve(t),d={persistent:s.persistent};if(e||(e=J),s.usePolling)d.interval=s.interval!==s.binaryInterval&&tw.has(S.extname(o).slice(1).toLowerCase())?s.binaryInterval:s.interval,i=((t,e,i,s)=>{let{listener:r,rawEmitter:o}=s,h=tk.get(e),l=h&&h.options;return l&&(l.persistent<i.persistent||l.interval>i.interval)&&(a(e),h=void 0),h?(tg(h,tf,r),tg(h,tp,o)):(h={listeners:r,rawEmitters:o,options:i,watcher:n(e,i,(i,s)=>{t_(h.rawEmitters,t=>{t(ta,e,{curr:i,prev:s})});let r=i.mtimeMs;(i.size!==s.size||r>s.mtimeMs||0===r)&&t_(h.listeners,e=>e(t,i))})},tk.set(e,h)),()=>{ty(h,tf,r),ty(h,tp,o),tv(h.listeners)&&(tk.delete(e),a(e),h.options=h.watcher=void 0,Object.freeze(h))}})(t,h,d,{listener:e,rawEmitter:this.fsw._emitRaw});else i=((t,e,i,s)=>{let r,{listener:a,errHandler:o,rawEmitter:n}=s,h=tb.get(e);if(!i.persistent){if(!(r=tP(t,i,a,o,n)))return;return r.close.bind(r)}if(h)tg(h,tf,a),tg(h,tm,o),tg(h,tp,n);else{if(!(r=tP(t,i,tE.bind(null,e,tf),o,tE.bind(null,e,tp))))return;r.on(td,async i=>{let s=tE.bind(null,e,tm);if(h&&(h.watcherUnusable=!0),X&&"EPERM"===i.code)try{let e=await l(t,"r");await e.close(),s(i)}catch(t){}else s(i)}),h={listeners:a,errHandlers:o,rawEmitters:n,watcher:r},tb.set(e,h)}return()=>{if(ty(h,tf,a),ty(h,tm,o),ty(h,tp,n),tv(h.listeners)){let t;h.watcher.close(),tb.delete(e),tu.forEach((t=h,e=>{let i=t[e];i instanceof Set?i.clear():delete t[e]})),h.watcher=void 0,Object.freeze(h)}}})(t,h,d,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return i}_handleFile(t,e,i){if(this.fsw.closed)return;let s=S.dirname(t),r=S.basename(t),a=this.fsw._getWatchedDir(s),o=e;if(a.has(r))return;let n=async(e,i)=>{if(this.fsw._throttle("watch",t,5))if(i&&0!==i.mtimeMs){if(a.has(r)){let e=i.atimeMs,s=i.mtimeMs;(!e||e<=s||s!==o.mtimeMs)&&this.fsw._emit(ta,t,i),o=i}}else try{let i=await f(t);if(this.fsw.closed)return;let s=i.atimeMs,r=i.mtimeMs;if((!s||s<=r||r!==o.mtimeMs)&&this.fsw._emit(ta,t,i),(Y||Z||tt)&&o.ino!==i.ino){this.fsw._closeFile(e),o=i;let s=this._watchWithNodeFs(t,n);s&&this.fsw._addPathCloser(e,s)}else o=i}catch(t){this.fsw._remove(s,r)}},h=this._watchWithNodeFs(t,n);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(tr,t,0))return;this.fsw._emit(tr,t,e)}return h}async _handleSymlink(t,e,i,s){if(this.fsw.closed)return;let r=t.fullPath,a=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){let e;this.fsw._incrReadyCount();try{e=await c(i)}catch(t){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;return a.has(s)?this.fsw._symlinkPaths.get(r)!==e&&(this.fsw._symlinkPaths.set(r,e),this.fsw._emit(ta,i,t.stats)):(a.add(s),this.fsw._symlinkPaths.set(r,e),this.fsw._emit(tr,i,t.stats)),this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(r))return!0;this.fsw._symlinkPaths.set(r,!0)}_handleRead(t,e,i,s,r,a,o){if(t=S.join(t,""),!(o=this.fsw._throttle("readdir",t,1e3)))return;let n=this.fsw._getWatchedDir(i.path),h=new Set,l=this.fsw._readdirp(t,{fileFilter:t=>i.filterPath(t),directoryFilter:t=>i.filterDir(t)});if(l)return l.on("data",async o=>{if(this.fsw.closed){l=void 0;return}let d=o.path,c=S.join(t,d);if(h.add(d),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,t,c,d))){if(this.fsw.closed){l=void 0;return}d!==s&&(s||n.has(d))||(this.fsw._incrReadyCount(),c=S.join(r,S.relative(r,c)),this._addToNodeFs(c,e,i,a+1))}}).on(td,this._boundHandleError),new Promise((e,d)=>{if(!l)return d();l.once("end",()=>{if(this.fsw.closed){l=void 0;return}let d=!!o&&o.clear();e(void 0),n.getChildren().filter(e=>e!==t&&!h.has(e)).forEach(e=>{this.fsw._remove(t,e)}),l=void 0,d&&this._handleRead(t,!1,i,s,r,a,o)})})}async _handleDir(t,e,i,s,r,a,o){let n,h,l=this.fsw._getWatchedDir(S.dirname(t)),d=l.has(S.basename(t));i&&this.fsw.options.ignoreInitial||r||d||this.fsw._emit(to,t,e),l.add(S.basename(t)),this.fsw._getWatchedDir(t);let c=this.fsw.options.depth;if((null==c||s<=c)&&!this.fsw._symlinkPaths.has(o)){if(!r&&(await this._handleRead(t,i,a,r,t,s,n),this.fsw.closed))return;h=this._watchWithNodeFs(t,(e,i)=>{i&&0===i.mtimeMs||this._handleRead(e,!1,a,r,t,s,n)})}return h}async _addToNodeFs(t,e,i,s,r){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(t);i&&(o.filterPath=t=>i.filterPath(t),o.filterDir=t=>i.filterDir(t));try{let i,n=await tc[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let h=this.fsw.options.followSymlinks;if(n.isDirectory()){let a=S.resolve(t),l=h?await c(t):t;if(this.fsw.closed||(i=await this._handleDir(o.watchPath,n,e,s,r,o,l),this.fsw.closed))return;a!==l&&void 0!==l&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let r=h?await c(t):t;if(this.fsw.closed)return;let a=S.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(tr,o.watchPath,n),i=await this._handleDir(a,n,e,s,t,o,r),this.fsw.closed)return;void 0!==r&&this.fsw._symlinkPaths.set(S.resolve(t),r)}else i=this._handleFile(o.watchPath,n,e);return a(),i&&this.fsw._addPathCloser(t,i),!1}catch(e){if(this.fsw._handleError(e))return a(),t}}}let tx=/\\/g,tD=/\/\//,tC=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,tF=/^\.[/\\]/;function tW(t){return Array.isArray(t)?t:[t]}let tR=t=>"object"==typeof t&&null!==t&&!(t instanceof RegExp);function tz(t,e,i){let s=function(t){if("string"!=typeof t)throw Error("string expected");t=(t=S.normalize(t)).replace(/\\/g,"/");let e=!1;t.startsWith("//")&&(e=!0);let i=/\/\//;for(;t.match(i);)t=t.replace(i,"/");return e&&(t="/"+t),t}(e);for(let e=0;e<t.length;e++)if((0,t[e])(s,i))return!0;return!1}let tM=t=>{let e=tW(t).flat();if(!e.every(t=>"string"==typeof t))throw TypeError(`Non-string provided as watch path: ${e}`);return e.map(tI)},tj=t=>{let e=t.replace(tx,"/"),i=!1;for(e.startsWith("//")&&(i=!0);e.match(tD);)e=e.replace(tD,"/");return i&&(e="/"+e),e},tI=t=>tj(S.normalize(tj(t))),tA=(t="")=>e=>"string"==typeof e?tI(S.isAbsolute(e)?e:S.join(t,e)):e,tO=Object.freeze(new Set);class tT{constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&"."!==t&&".."!==t&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let i=this.path;try{await d(i)}catch(t){this._removeWatcher&&this._removeWatcher(S.dirname(i),S.basename(i))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=J,this.items=tO,Object.freeze(this)}}class tH{constructor(t,e,i){this.fsw=i;let s=t;this.path=t=t.replace(tF,""),this.watchPath=s,this.fullWatchPath=S.resolve(s),this.dirParts=[],this.dirParts.forEach(t=>{t.length>1&&t.pop()}),this.followSymlinks=e,this.statMethod=e?"stat":"lstat"}entryPath(t){return S.join(this.watchPath,S.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let i=this.entryPath(t);return this.fsw._isntIgnored(i,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}}class tN extends m{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?tW(t.ignored):tW([]),awaitWriteFinish:!0===e?i:"object"==typeof e&&{...i,...e}};te&&(s.usePolling=!0),void 0===s.atomic&&(s.atomic=!s.usePolling);let r=process.env.CHOKIDAR_USEPOLLING;if(void 0!==r){let t=r.toLowerCase();"false"===t||"0"===t?s.usePolling=!1:"true"===t||"1"===t?s.usePolling=!0:s.usePolling=!!t}let a=process.env.CHOKIDAR_INTERVAL;a&&(s.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{++o>=this._readyCount&&(this._emitReady=J,this._readyEmitted=!0,process.nextTick(()=>this.emit(ts)))},this._emitRaw=(...t)=>this.emit(tl,...t),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new tS(this),Object.freeze(s)}_addIgnoredPath(t){if(tR(t)){for(let e of this._ignoredPaths)if(tR(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),"string"==typeof t)for(let e of this._ignoredPaths)tR(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,i){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let r=tM(t);return s&&(r=r.map(t=>S.isAbsolute(t)?t:S.join(s,t))),r.forEach(t=>{this._removeIgnoredPath(t)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=r.length,Promise.all(r.map(async t=>{let s=await this._nodeFsHandler._addToNodeFs(t,!i,void 0,0,e);return s&&this._emitReady(),s})).then(t=>{this.closed||t.forEach(t=>{t&&this.add(S.dirname(t),S.basename(e||t))})}),this}unwatch(t){if(this.closed)return this;let e=tM(t),{cwd:i}=this.options;return e.forEach(t=>{S.isAbsolute(t)||this._closers.has(t)||(i&&(t=S.join(i,t)),t=S.resolve(t)),this._closePath(t),this._addIgnoredPath(t),this._watched.has(t)&&this._addIgnoredPath({path:t,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(e=>{let i=e();i instanceof Promise&&t.push(i)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,i)=>{t[(this.options.cwd?S.relative(this.options.cwd,i):i)||"."]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==td&&this.emit(ti,t,...e)}async _emit(t,e,i){let s;if(this.closed)return;let r=this.options;X&&(e=S.normalize(e)),r.cwd&&(e=S.relative(r.cwd,e));let a=[e];null!=i&&a.push(i);let o=r.awaitWriteFinish;if(o&&(s=this._pendingWrites.get(e)))return s.lastChange=new Date,this;if(r.atomic){if(t===tn)return this._pendingUnlinks.set(e,[t,...a]),setTimeout(()=>{this._pendingUnlinks.forEach((t,e)=>{this.emit(...t),this.emit(ti,...t),this._pendingUnlinks.delete(e)})},"number"==typeof r.atomic?r.atomic:100),this;t===tr&&this._pendingUnlinks.has(e)&&(t=ta,this._pendingUnlinks.delete(e))}if(o&&(t===tr||t===ta)&&this._readyEmitted){let i=(e,i)=>{e?(t=td,a[0]=e,this.emitWithAll(t,a)):i&&(a.length>1?a[1]=i:a.push(i),this.emitWithAll(t,a))};return this._awaitWriteFinish(e,o.stabilityThreshold,t,i),this}if(t===ta&&!this._throttle(ta,e,50))return this;if(r.alwaysStat&&void 0===i&&(t===tr||t===to||t===ta)){let t,i=r.cwd?S.join(r.cwd,e):e;try{t=await f(i)}catch(t){}if(!t||this.closed)return;a.push(t)}return this.emitWithAll(t,a),this}_handleError(t){let e=t&&t.code;return t&&"ENOENT"!==e&&"ENOTDIR"!==e&&(!this.options.ignorePermissionErrors||"EPERM"!==e&&"EACCES"!==e)&&this.emit(td,t),t||this.closed}_throttle(t,e,i){let s;this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw Error("invalid throttle");let a=r.get(e);if(a)return a.count++,!1;let o=()=>{let t=r.get(e),i=t?t.count:0;return r.delete(e),clearTimeout(s),t&&clearTimeout(t.timeoutObject),i},n={timeoutObject:s=setTimeout(o,i),clear:o,count:0};return r.set(e,n),n}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,i,s){let a,o=this.options.awaitWriteFinish;if("object"!=typeof o)return;let n=o.pollInterval,h=t;this.options.cwd&&!S.isAbsolute(t)&&(h=S.join(this.options.cwd,t));let l=new Date,d=this._pendingWrites;d.has(t)||(d.set(t,{lastChange:l,cancelWait:()=>(d.delete(t),clearTimeout(a),i)}),a=setTimeout(function i(o){r(h,(r,h)=>{if(r||!d.has(t)){r&&"ENOENT"!==r.code&&s(r);return}let l=Number(new Date);o&&h.size!==o.size&&(d.get(t).lastChange=l),l-d.get(t).lastChange>=e?(d.delete(t),s(void 0,h)):a=setTimeout(i,n,h)})},n))}_isIgnored(t,e){if(this.options.atomic&&tC.test(t))return!0;if(!this._userIgnored){let{cwd:t}=this.options,e=(this.options.ignored||[]).map(tA(t)),i=[...[...this._ignoredPaths].map(tA(t)),...e];this._userIgnored=function(t,e){if(null==t)throw TypeError("anymatch: specify first argument");let i=tW(t).map(t=>"function"==typeof t?t:"string"==typeof t?e=>t===e:t instanceof RegExp?e=>t.test(e):"object"==typeof t&&null!==t?e=>{if(t.path===e)return!0;if(t.recursive){let i=S.relative(t.path,e);return!!i&&!i.startsWith("..")&&!S.isAbsolute(i)}return!1}:()=>!1);return null==e?(t,e)=>tz(i,t,e):tz(i,e)}(i,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new tH(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=S.resolve(t);return this._watched.has(e)||this._watched.set(e,new tT(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return!!this.options.ignorePermissionErrors||!!(256&Number(t.mode))}_remove(t,e,i){let s=S.join(t,e),r=S.resolve(s);if(i=null!=i?i:this._watched.has(s)||this._watched.has(r),!this._throttle("remove",s,100))return;i||1!==this._watched.size||this.add(t,e,!0),this._getWatchedDir(s).getChildren().forEach(t=>this._remove(s,t));let a=this._getWatchedDir(t),o=a.has(e);a.remove(e),this._symlinkPaths.has(r)&&this._symlinkPaths.delete(r);let n=s;if(this.options.cwd&&(n=S.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(n)&&this._pendingWrites.get(n).cancelWait()===tr)return;this._watched.delete(s),this._watched.delete(r);let h=i?th:tn;o&&!this._isIgnored(s)&&this._emit(h,s),this._closePath(s)}_closePath(t){this._closeFile(t);let e=S.dirname(t);this._getWatchedDir(e).remove(S.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(t=>t()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let i=this._closers.get(t);i||(i=[],this._closers.set(t,i)),i.push(e)}_readdirp(t,e){if(this.closed)return;let i=function(t,e={}){let i=e.entryType||e.type;if("both"===i&&(i=T),i&&(e.type=i),t){if("string"!=typeof t)throw TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");else if(i&&!L.includes(i))throw Error(`readdirp: Invalid type passed. Use one of ${L.join(", ")}`)}else throw Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=t,new G(e)}(t,{type:ti,alwaysStat:!0,lstat:!0,...e,depth:0});return this._streams.add(i),i.once("close",()=>{i=void 0}),i.once("end",()=>{i&&(this._streams.delete(i),i=void 0)}),i}}let tU=function(t,e={}){let i=new tN(e);return i.add(t),i},tL=/\/src\//,t$=/node_modules/;function tK(t,e){return t.map(t=>{let i=k.relative(e,t);return R.dim(k.dirname(i)+k.sep)+R.dim(k.basename(i))})}let tq=new I,tV=new class extends W{closeHooks=[];get stats(){return{all:j.empConfig.debug.devShowAllLog,colors:!0,assets:!1,chunks:!1,entrypoints:!1,timings:!1,version:!1,errors:!0,warnings:!0}}async getRspackDevConfig(){let t=M(j.rsConfig,{stats:this.stats,devServer:{open:!1,setupExitSignals:!0,port:j.server.port}}),{devServer:e}=t;if(j.server.isHttps&&(!e.server||"https"===e.server.type&&!e.server.options)){let{key:t,cert:i}=await j.server.getcert();e.server={type:"https",options:{key:t,cert:i}}}return Object.hasOwn(e,"https")&&delete e.https,t}async startDevServer(t=!1){try{let e,s,r,a,o,n,h,l,{server:d}=j,c=await this.getRspackDevConfig();c=await tq.beforeCompiler(c);let f=i(c);await j.empConfig.lifeCycle.beforeDevServe(),d.startOpen(),C("DevServer"),await tq.setup(f,c,j,async t=>{tq.isServerStarted=!0,x(t),await j.empConfig.lifeCycle.afterDevServe()});let m=(e="emp:compiler",s=new Set,r=new Map,a=!1,o=new Set,n=!1,h=f.options.context||process.cwd(),l=t=>tL.test(t)&&!t$.test(t),f.hooks.watchRun.tap(e,t=>{if(n)return;n=!0,s.clear(),o.clear();let{changed:e,removed:i}=(t=>{let e=new Set,i=new Set;if(t.modifiedFiles||t.removedFiles){if(t.modifiedFiles){for(let i of t.modifiedFiles)if(l(i)){let t=r.get(i)||0,s=Date.now();s-t>300&&(e.add(i),r.set(i,s))}}if(t.removedFiles)for(let e of t.removedFiles)l(e)&&(i.add(e),r.delete(e));return{changed:e,removed:i}}if(t.watchFileSystem?.watcher){let i=t.watchFileSystem.watcher.mtimes||{};for(let t of Object.keys(i)){if(!l(t))continue;let s=i[t],a=r.get(t)||0,o=Date.now();a<s&&o-a>300&&(e.add(t),r.set(t,o))}}return{changed:e,removed:i}})(t);(a=e.size>0||i.size>0)&&function(t,e){if(!tq.isServerStarted)return;let i=Array.from(t),s=Array.from(e),r=Array.from(o);if(0===i.length&&0===s.length&&0===r.length)return;let a="";if(i.length>0){let t=tK(i,h);a+=`modified ${t.join(", ")}`}if(r.length>0){let t=tK(r,h);a+=`lazyLoaded ${t.join(", ")}`}if(s.length>0){let t=tK(s,h);a+=`removed ${t.join(", ")}`}D(a)}(e,i),e.forEach(t=>s.add(t))}),f.hooks.done.tap(e,t=>{if(!tq.isServerStarted||!a){n=!1;return}(s.size>0||o.size>0)&&(F(t),a=!1),n=!1}),{cleanup:()=>{s.clear(),r.clear(),o.clear(),a=!1,n=!1}});this.closeHooks.push(()=>m.cleanup()),t&&z.debug("[EMP] Dev server restarted successfully")}catch(e){z.error(`[EMP] Failed to ${t?"restart":"start"} dev server:`,e)}}watchConfigFile(){let t=k.resolve(process.cwd(),"emp.config.ts");if(!s.existsSync(t))return;z.debug("[EMP] Watching for changes in emp.config.ts...");let i=s.readFileSync(t,"utf-8");tU(t,{ignored:/(^|[/\\])\../,persistent:!0}).on("change",async r=>{let a=s.readFileSync(t,"utf-8");i===a?z.debug("[EMP] 配置文件无实际变更(空保存),跳过重启"):(i=a,z.debug(`[EMP] Config file changed: ${r}`),Object.keys(e.cache).forEach(t=>{t.includes("emp.config")&&delete e.cache[t]}),z.debug("[EMP] 配置文件已变更,正在重启服务..."),this.executeCloseHooks(),await tq.close(),await j.setup(),z.debug("[EMP] 重启服务完成,新配置如下:",j.empConfig.debug),await this.startDevServer(!0))})}async run(){await this.startDevServer(!1),this.watchConfigFile()}lastBuildTime=0;executeCloseHooks(){if(this.closeHooks.length>0){for(let t of(z.debug(`[EMP] 执行 ${this.closeHooks.length} 个Hook...`),this.closeHooks))try{t()}catch(t){z.error("[EMP] 执行清理钩子时出错:",t)}this.closeHooks=[]}}};export default tV;
2
+ import t from"node:module";let e=t.createRequire(import.meta.url);import{rspack as i}from"@rspack/core";import s,{stat as r,unwatchFile as a,watch as o,watchFile as n}from"fs";import{lstat as h,open as l,readdir as d,realpath as c,stat as f}from"fs/promises";import{EventEmitter as m}from"events";import{lstat as p,readdir as u,realpath as w,stat as _}from"node:fs/promises";import{Readable as g}from"node:stream";import{join as y,relative as v,resolve as b,sep as P}from"node:path";import{type as E}from"os";import S,*as k from"path";import{printBuildDone as x,logStart as D,printBuildStart as C,logDone as F,BaseScript as W}from"./627.js";import{chalk as R,logger as z,getEmpConfigCandidatePaths as j,deepAssign as M,store as I}from"./346.js";import{DevServer as A}from"./server.js";let O="files",T="directories",N="files_directories",H={root:".",fileFilter:t=>!0,directoryFilter:t=>!0,type:O,lstat:!1,depth:0x80000000,alwaysStat:!1,highWaterMark:4096};Object.freeze(H);let U="READDIRP_RECURSIVE_ERROR",L=new Set(["ENOENT","EPERM","EACCES","ELOOP",U]),$=[T,"all",N,O],K=new Set([T,"all",N]),q=new Set(["all",N,O]),V="win32"===process.platform,G=t=>!0,B=t=>{if(void 0===t)return G;if("function"==typeof t)return t;if("string"==typeof t){let e=t.trim();return t=>t.basename===e}if(Array.isArray(t)){let e=t.map(t=>t.trim());return t=>e.some(e=>t.basename===e)}return G};class J extends g{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let e={...H,...t},{root:i,type:s}=e;this._fileFilter=B(e.fileFilter),this._directoryFilter=B(e.directoryFilter);let r=e.lstat?p:_;V?this._stat=t=>r(t,{bigint:!0}):this._stat=r,this._maxDepth=e.depth??H.depth,this._wantsDir=!!s&&K.has(s),this._wantsFile=!!s&&q.has(s),this._wantsEverything="all"===s,this._root=b(i),this._isDirent=!e.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let e=this.parent,i=e&&e.files;if(i&&i.length>0){let{path:s,depth:r}=e,a=i.splice(0,t).map(t=>this._formatEntry(t,s));for(let e of(await Promise.all(a))){if(!e)continue;if(this.destroyed)return;let i=await this._getEntryType(e);"directory"===i&&this._directoryFilter(e)?(r<=this._maxDepth&&this.parents.push(this._exploreDir(e.fullPath,r+1)),this._wantsDir&&(this.push(e),t--)):("file"===i||this._includeAsFile(e))&&this._fileFilter(e)&&this._wantsFile&&(this.push(e),t--)}}else{let t=this.parents.pop();if(!t){this.push(null);break}if(this.parent=await t,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(t,e){let i;try{i=await u(t,this._rdOptions)}catch(t){this._onError(t)}return{files:i,depth:e,path:t}}async _formatEntry(t,e){let i,s=this._isDirent?t.name:t;try{let r=b(y(e,s));(i={path:v(this._root,r),fullPath:r,basename:s})[this._statsProp]=this._isDirent?t:await this._stat(r)}catch(t){this._onError(t);return}return i}_onError(t){L.has(t.code)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let e=t[this._statsProp];if(e.isFile())return"file";if(e.isDirectory())return"directory";if(e&&e.isSymbolicLink()){let e=t.fullPath;try{let t=await w(e),i=await p(t);if(i.isFile())return"file";if(i.isDirectory()){let i=t.length;if(e.startsWith(t)&&e.substr(i,1)===P){let i=Error(`Circular symlink detected: "${e}" points to "${t}"`);return i.code=U,this._onError(i)}return"directory"}}catch(t){return this._onError(t),""}}}_includeAsFile(t){let e=t&&t[this._statsProp];return e&&this._wantsEverything&&!e.isDirectory()}}let Q=()=>{},X=process.platform,Y="win32"===X,Z="darwin"===X,tt="linux"===X,te="freebsd"===X,ti="OS400"===E(),ts="all",tr="ready",ta="add",to="change",tn="addDir",th="unlink",tl="unlinkDir",td="raw",tc="error",tf={lstat:h,stat:f},tm="listeners",tp="errHandlers",tu="rawEmitters",tw=[tm,tp,tu],t_=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),tg=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},ty=(t,e,i)=>{let s=t[e];s instanceof Set||(t[e]=s=new Set([s])),s.add(i)},tv=(t,e,i)=>{let s=t[e];s instanceof Set?s.delete(i):s===i&&delete t[e]},tb=t=>t instanceof Set?0===t.size:!t,tP=new Map;function tE(t,e,i,s,r){try{return o(t,{persistent:e.persistent},(e,s)=>{i(t),r(e,s,{watchedPath:t}),s&&t!==s&&tS(k.resolve(t,s),tm,k.join(t,s))})}catch(t){s(t);return}}let tS=(t,e,i,s,r)=>{let a=tP.get(t);a&&tg(a[e],t=>{t(i,s,r)})},tk=new Map;class tx{constructor(t){this.fsw=t,this._boundHandleError=e=>t._handleError(e)}_watchWithNodeFs(t,e){let i,s=this.fsw.options,r=k.dirname(t),o=k.basename(t);this.fsw._getWatchedDir(r).add(o);let h=k.resolve(t),d={persistent:s.persistent};if(e||(e=Q),s.usePolling)d.interval=s.interval!==s.binaryInterval&&t_.has(k.extname(o).slice(1).toLowerCase())?s.binaryInterval:s.interval,i=((t,e,i,s)=>{let{listener:r,rawEmitter:o}=s,h=tk.get(e),l=h&&h.options;return l&&(l.persistent<i.persistent||l.interval>i.interval)&&(a(e),h=void 0),h?(ty(h,tm,r),ty(h,tu,o)):(h={listeners:r,rawEmitters:o,options:i,watcher:n(e,i,(i,s)=>{tg(h.rawEmitters,t=>{t(to,e,{curr:i,prev:s})});let r=i.mtimeMs;(i.size!==s.size||r>s.mtimeMs||0===r)&&tg(h.listeners,e=>e(t,i))})},tk.set(e,h)),()=>{tv(h,tm,r),tv(h,tu,o),tb(h.listeners)&&(tk.delete(e),a(e),h.options=h.watcher=void 0,Object.freeze(h))}})(t,h,d,{listener:e,rawEmitter:this.fsw._emitRaw});else i=((t,e,i,s)=>{let r,{listener:a,errHandler:o,rawEmitter:n}=s,h=tP.get(e);if(!i.persistent){if(!(r=tE(t,i,a,o,n)))return;return r.close.bind(r)}if(h)ty(h,tm,a),ty(h,tp,o),ty(h,tu,n);else{if(!(r=tE(t,i,tS.bind(null,e,tm),o,tS.bind(null,e,tu))))return;r.on(tc,async i=>{let s=tS.bind(null,e,tp);if(h&&(h.watcherUnusable=!0),Y&&"EPERM"===i.code)try{let e=await l(t,"r");await e.close(),s(i)}catch(t){}else s(i)}),h={listeners:a,errHandlers:o,rawEmitters:n,watcher:r},tP.set(e,h)}return()=>{if(tv(h,tm,a),tv(h,tp,o),tv(h,tu,n),tb(h.listeners)){let t;h.watcher.close(),tP.delete(e),tw.forEach((t=h,e=>{let i=t[e];i instanceof Set?i.clear():delete t[e]})),h.watcher=void 0,Object.freeze(h)}}})(t,h,d,{listener:e,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return i}_handleFile(t,e,i){if(this.fsw.closed)return;let s=k.dirname(t),r=k.basename(t),a=this.fsw._getWatchedDir(s),o=e;if(a.has(r))return;let n=async(e,i)=>{if(this.fsw._throttle("watch",t,5))if(i&&0!==i.mtimeMs){if(a.has(r)){let e=i.atimeMs,s=i.mtimeMs;(!e||e<=s||s!==o.mtimeMs)&&this.fsw._emit(to,t,i),o=i}}else try{let i=await f(t);if(this.fsw.closed)return;let s=i.atimeMs,r=i.mtimeMs;if((!s||s<=r||r!==o.mtimeMs)&&this.fsw._emit(to,t,i),(Z||tt||te)&&o.ino!==i.ino){this.fsw._closeFile(e),o=i;let s=this._watchWithNodeFs(t,n);s&&this.fsw._addPathCloser(e,s)}else o=i}catch(t){this.fsw._remove(s,r)}},h=this._watchWithNodeFs(t,n);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(ta,t,0))return;this.fsw._emit(ta,t,e)}return h}async _handleSymlink(t,e,i,s){if(this.fsw.closed)return;let r=t.fullPath,a=this.fsw._getWatchedDir(e);if(!this.fsw.options.followSymlinks){let e;this.fsw._incrReadyCount();try{e=await c(i)}catch(t){return this.fsw._emitReady(),!0}if(this.fsw.closed)return;return a.has(s)?this.fsw._symlinkPaths.get(r)!==e&&(this.fsw._symlinkPaths.set(r,e),this.fsw._emit(to,i,t.stats)):(a.add(s),this.fsw._symlinkPaths.set(r,e),this.fsw._emit(ta,i,t.stats)),this.fsw._emitReady(),!0}if(this.fsw._symlinkPaths.has(r))return!0;this.fsw._symlinkPaths.set(r,!0)}_handleRead(t,e,i,s,r,a,o){if(t=k.join(t,""),!(o=this.fsw._throttle("readdir",t,1e3)))return;let n=this.fsw._getWatchedDir(i.path),h=new Set,l=this.fsw._readdirp(t,{fileFilter:t=>i.filterPath(t),directoryFilter:t=>i.filterDir(t)});if(l)return l.on("data",async o=>{if(this.fsw.closed){l=void 0;return}let d=o.path,c=k.join(t,d);if(h.add(d),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,t,c,d))){if(this.fsw.closed){l=void 0;return}d!==s&&(s||n.has(d))||(this.fsw._incrReadyCount(),c=k.join(r,k.relative(r,c)),this._addToNodeFs(c,e,i,a+1))}}).on(tc,this._boundHandleError),new Promise((e,d)=>{if(!l)return d();l.once("end",()=>{if(this.fsw.closed){l=void 0;return}let d=!!o&&o.clear();e(void 0),n.getChildren().filter(e=>e!==t&&!h.has(e)).forEach(e=>{this.fsw._remove(t,e)}),l=void 0,d&&this._handleRead(t,!1,i,s,r,a,o)})})}async _handleDir(t,e,i,s,r,a,o){let n,h,l=this.fsw._getWatchedDir(k.dirname(t)),d=l.has(k.basename(t));i&&this.fsw.options.ignoreInitial||r||d||this.fsw._emit(tn,t,e),l.add(k.basename(t)),this.fsw._getWatchedDir(t);let c=this.fsw.options.depth;if((null==c||s<=c)&&!this.fsw._symlinkPaths.has(o)){if(!r&&(await this._handleRead(t,i,a,r,t,s,n),this.fsw.closed))return;h=this._watchWithNodeFs(t,(e,i)=>{i&&0===i.mtimeMs||this._handleRead(e,!1,a,r,t,s,n)})}return h}async _addToNodeFs(t,e,i,s,r){let a=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(t);i&&(o.filterPath=t=>i.filterPath(t),o.filterDir=t=>i.filterDir(t));try{let i,n=await tf[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let h=this.fsw.options.followSymlinks;if(n.isDirectory()){let a=k.resolve(t),l=h?await c(t):t;if(this.fsw.closed||(i=await this._handleDir(o.watchPath,n,e,s,r,o,l),this.fsw.closed))return;a!==l&&void 0!==l&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let r=h?await c(t):t;if(this.fsw.closed)return;let a=k.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(ta,o.watchPath,n),i=await this._handleDir(a,n,e,s,t,o,r),this.fsw.closed)return;void 0!==r&&this.fsw._symlinkPaths.set(k.resolve(t),r)}else i=this._handleFile(o.watchPath,n,e);return a(),i&&this.fsw._addPathCloser(t,i),!1}catch(e){if(this.fsw._handleError(e))return a(),t}}}let tD=/\\/g,tC=/\/\//,tF=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,tW=/^\.[/\\]/;function tR(t){return Array.isArray(t)?t:[t]}let tz=t=>"object"==typeof t&&null!==t&&!(t instanceof RegExp);function tj(t,e,i){let s=function(t){if("string"!=typeof t)throw Error("string expected");t=(t=k.normalize(t)).replace(/\\/g,"/");let e=!1;t.startsWith("//")&&(e=!0);let i=/\/\//;for(;t.match(i);)t=t.replace(i,"/");return e&&(t="/"+t),t}(e);for(let e=0;e<t.length;e++)if((0,t[e])(s,i))return!0;return!1}let tM=t=>{let e=tR(t).flat();if(!e.every(t=>"string"==typeof t))throw TypeError(`Non-string provided as watch path: ${e}`);return e.map(tA)},tI=t=>{let e=t.replace(tD,"/"),i=!1;for(e.startsWith("//")&&(i=!0);e.match(tC);)e=e.replace(tC,"/");return i&&(e="/"+e),e},tA=t=>tI(k.normalize(tI(t))),tO=(t="")=>e=>"string"==typeof e?tA(k.isAbsolute(e)?e:k.join(t,e)):e,tT=Object.freeze(new Set);class tN{constructor(t,e){this.path=t,this._removeWatcher=e,this.items=new Set}add(t){let{items:e}=this;e&&"."!==t&&".."!==t&&e.add(t)}async remove(t){let{items:e}=this;if(!e||(e.delete(t),e.size>0))return;let i=this.path;try{await d(i)}catch(t){this._removeWatcher&&this._removeWatcher(k.dirname(i),k.basename(i))}}has(t){let{items:e}=this;if(e)return e.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Q,this.items=tT,Object.freeze(this)}}class tH{constructor(t,e,i){this.fsw=i;let s=t;this.path=t=t.replace(tW,""),this.watchPath=s,this.fullWatchPath=k.resolve(s),this.dirParts=[],this.dirParts.forEach(t=>{t.length>1&&t.pop()}),this.followSymlinks=e,this.statMethod=e?"stat":"lstat"}entryPath(t){return k.join(this.watchPath,k.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:e}=t;if(e&&e.isSymbolicLink())return this.filterDir(t);let i=this.entryPath(t);return this.fsw._isntIgnored(i,e)&&this.fsw._hasReadPermissions(e)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}}class tU extends m{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let e=t.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?tR(t.ignored):tR([]),awaitWriteFinish:!0===e?i:"object"==typeof e&&{...i,...e}};ti&&(s.usePolling=!0),void 0===s.atomic&&(s.atomic=!s.usePolling);let r=process.env.CHOKIDAR_USEPOLLING;if(void 0!==r){let t=r.toLowerCase();"false"===t||"0"===t?s.usePolling=!1:"true"===t||"1"===t?s.usePolling=!0:s.usePolling=!!t}let a=process.env.CHOKIDAR_INTERVAL;a&&(s.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{++o>=this._readyCount&&(this._emitReady=Q,this._readyEmitted=!0,process.nextTick(()=>this.emit(tr)))},this._emitRaw=(...t)=>this.emit(td,...t),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new tx(this),Object.freeze(s)}_addIgnoredPath(t){if(tz(t)){for(let e of this._ignoredPaths)if(tz(e)&&e.path===t.path&&e.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),"string"==typeof t)for(let e of this._ignoredPaths)tz(e)&&e.path===t&&this._ignoredPaths.delete(e)}add(t,e,i){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let r=tM(t);return s&&(r=r.map(t=>k.isAbsolute(t)?t:k.join(s,t))),r.forEach(t=>{this._removeIgnoredPath(t)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=r.length,Promise.all(r.map(async t=>{let s=await this._nodeFsHandler._addToNodeFs(t,!i,void 0,0,e);return s&&this._emitReady(),s})).then(t=>{this.closed||t.forEach(t=>{t&&this.add(k.dirname(t),k.basename(e||t))})}),this}unwatch(t){if(this.closed)return this;let e=tM(t),{cwd:i}=this.options;return e.forEach(t=>{k.isAbsolute(t)||this._closers.has(t)||(i&&(t=k.join(i,t)),t=k.resolve(t)),this._closePath(t),this._addIgnoredPath(t),this._watched.has(t)&&this._addIgnoredPath({path:t,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(e=>e.forEach(e=>{let i=e();i instanceof Promise&&t.push(i)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((e,i)=>{t[(this.options.cwd?k.relative(this.options.cwd,i):i)||"."]=e.getChildren().sort()}),t}emitWithAll(t,e){this.emit(t,...e),t!==tc&&this.emit(ts,t,...e)}async _emit(t,e,i){let s;if(this.closed)return;let r=this.options;Y&&(e=k.normalize(e)),r.cwd&&(e=k.relative(r.cwd,e));let a=[e];null!=i&&a.push(i);let o=r.awaitWriteFinish;if(o&&(s=this._pendingWrites.get(e)))return s.lastChange=new Date,this;if(r.atomic){if(t===th)return this._pendingUnlinks.set(e,[t,...a]),setTimeout(()=>{this._pendingUnlinks.forEach((t,e)=>{this.emit(...t),this.emit(ts,...t),this._pendingUnlinks.delete(e)})},"number"==typeof r.atomic?r.atomic:100),this;t===ta&&this._pendingUnlinks.has(e)&&(t=to,this._pendingUnlinks.delete(e))}if(o&&(t===ta||t===to)&&this._readyEmitted){let i=(e,i)=>{e?(t=tc,a[0]=e,this.emitWithAll(t,a)):i&&(a.length>1?a[1]=i:a.push(i),this.emitWithAll(t,a))};return this._awaitWriteFinish(e,o.stabilityThreshold,t,i),this}if(t===to&&!this._throttle(to,e,50))return this;if(r.alwaysStat&&void 0===i&&(t===ta||t===tn||t===to)){let t,i=r.cwd?k.join(r.cwd,e):e;try{t=await f(i)}catch(t){}if(!t||this.closed)return;a.push(t)}return this.emitWithAll(t,a),this}_handleError(t){let e=t&&t.code;return t&&"ENOENT"!==e&&"ENOTDIR"!==e&&(!this.options.ignorePermissionErrors||"EPERM"!==e&&"EACCES"!==e)&&this.emit(tc,t),t||this.closed}_throttle(t,e,i){let s;this._throttled.has(t)||this._throttled.set(t,new Map);let r=this._throttled.get(t);if(!r)throw Error("invalid throttle");let a=r.get(e);if(a)return a.count++,!1;let o=()=>{let t=r.get(e),i=t?t.count:0;return r.delete(e),clearTimeout(s),t&&clearTimeout(t.timeoutObject),i},n={timeoutObject:s=setTimeout(o,i),clear:o,count:0};return r.set(e,n),n}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,e,i,s){let a,o=this.options.awaitWriteFinish;if("object"!=typeof o)return;let n=o.pollInterval,h=t;this.options.cwd&&!k.isAbsolute(t)&&(h=k.join(this.options.cwd,t));let l=new Date,d=this._pendingWrites;d.has(t)||(d.set(t,{lastChange:l,cancelWait:()=>(d.delete(t),clearTimeout(a),i)}),a=setTimeout(function i(o){r(h,(r,h)=>{if(r||!d.has(t)){r&&"ENOENT"!==r.code&&s(r);return}let l=Number(new Date);o&&h.size!==o.size&&(d.get(t).lastChange=l),l-d.get(t).lastChange>=e?(d.delete(t),s(void 0,h)):a=setTimeout(i,n,h)})},n))}_isIgnored(t,e){if(this.options.atomic&&tF.test(t))return!0;if(!this._userIgnored){let{cwd:t}=this.options,e=(this.options.ignored||[]).map(tO(t)),i=[...[...this._ignoredPaths].map(tO(t)),...e];this._userIgnored=function(t,e){if(null==t)throw TypeError("anymatch: specify first argument");let i=tR(t).map(t=>"function"==typeof t?t:"string"==typeof t?e=>t===e:t instanceof RegExp?e=>t.test(e):"object"==typeof t&&null!==t?e=>{if(t.path===e)return!0;if(t.recursive){let i=k.relative(t.path,e);return!!i&&!i.startsWith("..")&&!k.isAbsolute(i)}return!1}:()=>!1);return null==e?(t,e)=>tj(i,t,e):tj(i,e)}(i,void 0)}return this._userIgnored(t,e)}_isntIgnored(t,e){return!this._isIgnored(t,e)}_getWatchHelpers(t){return new tH(t,this.options.followSymlinks,this)}_getWatchedDir(t){let e=k.resolve(t);return this._watched.has(e)||this._watched.set(e,new tN(e,this._boundRemove)),this._watched.get(e)}_hasReadPermissions(t){return!!this.options.ignorePermissionErrors||!!(256&Number(t.mode))}_remove(t,e,i){let s=k.join(t,e),r=k.resolve(s);if(i=null!=i?i:this._watched.has(s)||this._watched.has(r),!this._throttle("remove",s,100))return;i||1!==this._watched.size||this.add(t,e,!0),this._getWatchedDir(s).getChildren().forEach(t=>this._remove(s,t));let a=this._getWatchedDir(t),o=a.has(e);a.remove(e),this._symlinkPaths.has(r)&&this._symlinkPaths.delete(r);let n=s;if(this.options.cwd&&(n=k.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(n)&&this._pendingWrites.get(n).cancelWait()===ta)return;this._watched.delete(s),this._watched.delete(r);let h=i?tl:th;o&&!this._isIgnored(s)&&this._emit(h,s),this._closePath(s)}_closePath(t){this._closeFile(t);let e=k.dirname(t);this._getWatchedDir(e).remove(k.basename(t))}_closeFile(t){let e=this._closers.get(t);e&&(e.forEach(t=>t()),this._closers.delete(t))}_addPathCloser(t,e){if(!e)return;let i=this._closers.get(t);i||(i=[],this._closers.set(t,i)),i.push(e)}_readdirp(t,e){if(this.closed)return;let i=function(t,e={}){let i=e.entryType||e.type;if("both"===i&&(i=N),i&&(e.type=i),t){if("string"!=typeof t)throw TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");else if(i&&!$.includes(i))throw Error(`readdirp: Invalid type passed. Use one of ${$.join(", ")}`)}else throw Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=t,new J(e)}(t,{type:ts,alwaysStat:!0,lstat:!0,...e,depth:0});return this._streams.add(i),i.once("close",()=>{i=void 0}),i.once("end",()=>{i&&(this._streams.delete(i),i=void 0)}),i}}let tL=function(t,e={}){let i=new tU(e);return i.add(t),i},t$=/\/src\//,tK=/node_modules/;function tq(t,e){return t.map(t=>{let i=S.relative(e,t);return R.dim(S.dirname(i)+S.sep)+R.dim(S.basename(i))})}let tV=new A,tG=new class extends W{get stats(){return{all:I.empConfig.debug.devShowAllLog,colors:!0,assets:!1,chunks:!1,entrypoints:!1,timings:!1,version:!1,errors:!0,warnings:!0}}async getRspackDevConfig(){let t=M(I.rsConfig,{stats:this.stats,devServer:{open:!1,setupExitSignals:!0,port:I.server.port}}),{devServer:e}=t;if(I.server.isHttps&&(!e.server||"https"===e.server.type&&!e.server.options)){let{key:t,cert:i}=await I.server.getcert();e.server={type:"https",options:{key:t,cert:i}}}return Object.hasOwn(e,"https")&&delete e.https,t}async startDevServer(t=!1){try{let e,s,r,a,o,n,h,l,{server:d}=I,c=await this.getRspackDevConfig();c=await tV.beforeCompiler(c);let f=i(c);await I.empConfig.lifeCycle.beforeDevServe(),d.startOpen(),C("DevServer"),await tV.setup(f,c,I,async t=>{tV.isServerStarted=!0,x(t),await I.empConfig.lifeCycle.afterDevServe()});let m=(e="emp:compiler",s=new Set,r=new Map,a=!1,o=new Set,n=!1,h=f.options.context||process.cwd(),l=t=>t$.test(t)&&!tK.test(t),f.hooks.watchRun.tap(e,t=>{if(n)return;n=!0,s.clear(),o.clear();let{changed:e,removed:i}=(t=>{let e=new Set,i=new Set;if(t.modifiedFiles||t.removedFiles){if(t.modifiedFiles){for(let i of t.modifiedFiles)if(l(i)){let t=r.get(i)||0,s=Date.now();s-t>300&&(e.add(i),r.set(i,s))}}if(t.removedFiles)for(let e of t.removedFiles)l(e)&&(i.add(e),r.delete(e));return{changed:e,removed:i}}if(t.watchFileSystem?.watcher){let i=t.watchFileSystem.watcher.mtimes||{};for(let t of Object.keys(i)){if(!l(t))continue;let s=i[t],a=r.get(t)||0,o=Date.now();a<s&&o-a>300&&(e.add(t),r.set(t,o))}}return{changed:e,removed:i}})(t);(a=e.size>0||i.size>0)&&function(t,e){if(!tV.isServerStarted)return;let i=Array.from(t),s=Array.from(e),r=Array.from(o);if(0===i.length&&0===s.length&&0===r.length)return;let a="";if(i.length>0){let t=tq(i,h);a+=`modified ${t.join(", ")}`}if(r.length>0){let t=tq(r,h);a+=`lazyLoaded ${t.join(", ")}`}if(s.length>0){let t=tq(s,h);a+=`removed ${t.join(", ")}`}D(a)}(e,i),e.forEach(t=>s.add(t))}),f.hooks.done.tap(e,t=>{if(!tV.isServerStarted||!a){n=!1;return}(s.size>0||o.size>0)&&(F(t),a=!1),n=!1}),{cleanup:()=>{s.clear(),r.clear(),o.clear(),a=!1,n=!1}});this.addCloseHook(()=>m.cleanup()),t&&z.debug("[EMP] Dev server restarted successfully")}catch(e){z.error(`[EMP] Failed to ${t?"restart":"start"} dev server:`,e)}}watchConfigFile(){let t=j(process.cwd()),i=I.rootPaths.empConfig;if(!i)return;z.debug(`[EMP] Watching for changes in ${i}...`);let r=s.readFileSync(i,"utf-8"),a=tL(t,{ignored:/(^|[/\\])\../,persistent:!0,ignoreInitial:!0});this.addCloseHook(()=>a.close()),a.on("change",async t=>{let a=s.readFileSync(t,"utf-8");t===i&&r===a?z.debug("[EMP] 配置文件无实际变更(空保存),跳过重启"):(r=a,z.debug(`[EMP] Config file changed: ${t}`),Object.keys(e.cache).forEach(t=>{(t.includes("emp.config")||t.includes("emp-config"))&&delete e.cache[t]}),z.debug("[EMP] 配置文件已变更,正在重启服务..."),await this.executeCloseHooks(),await tV.close(),await I.setup(),z.debug("[EMP] 重启服务完成,新配置如下:",I.empConfig.debug),await this.startDevServer(!0),this.watchConfigFile())})}async run(){await this.startDevServer(!1),this.watchConfigFile()}};export default tG;
@@ -1,4 +1,5 @@
1
1
  export declare const DEFAULT_CONFIG_FILES: string[];
2
+ export declare const getEmpConfigCandidatePaths: (root?: string) => string[];
2
3
  export declare const loadConfig: import("jiti").Jiti;
3
4
  export declare const getEmpConfigPath: () => Promise<string | undefined>;
4
5
  export declare const getTsConfig: () => Promise<string | undefined>;
@@ -1,5 +1,9 @@
1
1
  import { CliActionType, CliOptionsType } from '../types/env';
2
2
  export declare class BaseScript {
3
+ private static isSigintRegistered;
4
+ protected closeHooks: Array<() => void | Promise<void>>;
5
+ protected addCloseHook(hook: () => void | Promise<void>): void;
6
+ protected executeCloseHooks(): Promise<void>;
3
7
  setup(cliAction?: CliActionType, cliOptions?: CliOptionsType): Promise<void>;
4
8
  run(): Promise<void>;
5
9
  processExit(): void;
@@ -0,0 +1,11 @@
1
+ import type { EmpCreateReport } from '../agent-create/types';
2
+ export interface CreateCommandOptions {
3
+ dir?: string;
4
+ dryRun?: boolean;
5
+ skipInstall?: boolean;
6
+ skipDev?: boolean;
7
+ skipVerify?: boolean;
8
+ json?: boolean;
9
+ }
10
+ export declare function applyCreateReportExitStatus(report: EmpCreateReport, reportPath: string, json: boolean): void;
11
+ export declare function runCreateCommand(intentText: string, options?: CreateCommandOptions): Promise<void>;
@@ -1,6 +1,5 @@
1
1
  import { BaseScript } from './base';
2
2
  declare class DevScript extends BaseScript {
3
- private closeHooks;
4
3
  get stats(): {
5
4
  all: boolean;
6
5
  colors: boolean;
@@ -20,11 +19,6 @@ declare class DevScript extends BaseScript {
20
19
  private startDevServer;
21
20
  private watchConfigFile;
22
21
  run(): Promise<void>;
23
- private lastBuildTime;
24
- /**
25
- * 执行所有关闭钩子函数
26
- */
27
- private executeCloseHooks;
28
22
  }
29
23
  declare const _default: DevScript;
30
24
  export default _default;
@@ -0,0 +1,8 @@
1
+ import type { Command } from 'commander';
2
+ import type { CliOptionsType, EnvVarsType } from '../types/env';
3
+ export declare function collectEnvVar(value: string, memo?: EnvVarsType): EnvVarsType;
4
+ export declare function parseBooleanOption(value: unknown, defaultValue?: boolean): boolean;
5
+ export declare function normalizeCliOptions(options?: CliOptionsType): CliOptionsType;
6
+ export declare function registerEnvOption(command: Command): Command;
7
+ export declare function registerCommonOptions(command: Command): Command;
8
+ export declare function registerUnsupportedCommand(program: Command, name: string, description: string): void;
@@ -37,6 +37,7 @@ export declare class LifeCycle {
37
37
  /**
38
38
  * 产物构建完成后
39
39
  */
40
+ afterBuild(): Promise<void>;
40
41
  afterBulid(): Promise<void>;
41
42
  /**
42
43
  * devServer启动前
@@ -13,7 +13,6 @@ declare class RspackPlugin {
13
13
  sourceMapDevToolPlugin(): void;
14
14
  circularDependency(): void;
15
15
  cssChunkingPlugin(): void;
16
- esmLibraryPlugin(): void;
17
16
  }
18
17
  declare const _default: RspackPlugin;
19
18
  export default _default;
@@ -1,6 +1,6 @@
1
1
  import type { InspectOptions } from 'node:util';
2
2
  import type { RsdoctorRspackPlugin } from '@rsdoctor/rspack-plugin';
3
- import type { DevServer as devServerConfig, CacheOptions, Externals, HtmlRspackPluginOptions, Output, Resolve, Configuration as RsConfig, RuleSetRule, SourceMapDevToolPluginOptions, SwcJsMinimizerRspackPluginOptions } from '@rspack/core';
3
+ import type { DevServer as devServerConfig, CacheOptions, Externals, HtmlRspackPluginOptions, Output, Resolve, Configuration as RsConfig, RuleSetRule, SourceMapDevToolPluginOptions, SwcLoaderOptions, SwcJsMinimizerRspackPluginOptions } from '@rspack/core';
4
4
  import type { HtmlTagObject } from 'html-webpack-plugin';
5
5
  import type { Options as SassOptions } from 'sass-embedded';
6
6
  import { Chain } from '../store/chain';
@@ -37,7 +37,12 @@ export type DebugType = {
37
37
  * https://rspack.rs/zh/plugins/rspack/css-chunking-plugin
38
38
  * 启用 CssChunkingPlugin 后,SplitChunksPlugin 将不再处理 CSS 模块。 这意味着 optimization.splitChunks 等配置对 CSS 模块将不再生效,所有 CSS 模块的代码分割逻辑完全由 CssChunkingPlugin 处理。
39
39
  */
40
- cssChunkingPlugin?: boolean;
40
+ cssChunkingPlugin?: boolean | Record<string, any>;
41
+ /**
42
+ * 是否启用 Rspack 原生文件监听器。
43
+ * @default true
44
+ */
45
+ nativeWatcher?: boolean;
41
46
  };
42
47
  export type ServerType = devServerConfig & {
43
48
  /**
@@ -100,6 +105,38 @@ export type SourceMapType = {
100
105
  css: boolean;
101
106
  devToolPluginOptions?: SourceMapDevToolPluginOptions;
102
107
  };
108
+ export type CssResolveImportType = boolean | ((context: {
109
+ url: string;
110
+ media: string | undefined;
111
+ resourcePath: string;
112
+ supports: string | undefined;
113
+ layer: string | undefined;
114
+ }) => boolean);
115
+ export type Rspack2BuildOptions = {
116
+ /**
117
+ * Rspack 2 experiments 显式开关。实验能力不默认开启,避免改变业务语义。
118
+ */
119
+ experiments?: Pick<NonNullable<RsConfig['experiments']>, 'pureFunctions' | 'deferImport'>;
120
+ /**
121
+ * Rspack splitChunks 透传配置,用于接入 enforceSizeThreshold 等 Rspack 2 分包能力。
122
+ */
123
+ splitChunks?: Exclude<NonNullable<NonNullable<RsConfig['optimization']>['splitChunks']>, false>;
124
+ /**
125
+ * Rspack parser 透传配置。
126
+ */
127
+ parser?: {
128
+ javascript?: {
129
+ pureFunctions?: string[];
130
+ };
131
+ css?: {
132
+ resolveImport?: CssResolveImportType;
133
+ };
134
+ };
135
+ /**
136
+ * builtin:swc-loader 的 Rspack 扩展配置。
137
+ */
138
+ swc?: Pick<SwcLoaderOptions, 'detectSyntax' | 'transformImport'>;
139
+ };
103
140
  export type BuildType = {
104
141
  /**
105
142
  * 生成代码目录
@@ -125,7 +162,7 @@ export type BuildType = {
125
162
  * named 使用有意义、方便调试的内容当作模块 id。此选项会在开发环境下默认开启。
126
163
  * deterministic 使用对模块标识符哈希后的数字当作模块 id,有益于长期缓存。此选项会在生产环境下默认开启。
127
164
  */
128
- moduleIds?: 'named' | 'deterministic';
165
+ moduleIds?: false | 'natural' | 'named' | 'deterministic' | 'hashed';
129
166
  /**
130
167
  * chunkIds
131
168
  * @default named|deterministic
@@ -153,6 +190,16 @@ export type BuildType = {
153
190
  */
154
191
  minOptions?: SwcJsMinimizerRspackPluginOptions;
155
192
  cssminOptions?: CssminOptionsType;
193
+ /**
194
+ * Rspack incremental build 配置。
195
+ * @default 'advance-silent'
196
+ */
197
+ incremental?: RsConfig['incremental'];
198
+ /**
199
+ * Rspack lazy compilation 配置。
200
+ * @default development mode true
201
+ */
202
+ lazyCompilation?: RsConfig['lazyCompilation'];
156
203
  /**
157
204
  * 生成代码 参考 https://swc.rs/docs/configuring-swc#jsctarget
158
205
  */
@@ -176,6 +223,10 @@ export type BuildType = {
176
223
  };
177
224
  preserveAllComments?: boolean;
178
225
  };
226
+ /**
227
+ * Rspack 2 新能力的显式配置入口。
228
+ */
229
+ rspack?: Rspack2BuildOptions;
179
230
  };
180
231
  export type JscTarget = 'es3' | 'es5' | 'es2015' | 'es2016' | 'es2017' | 'es2018' | 'es2019' | 'es2020' | 'es2021' | 'es2022';
181
232
  export interface HtmlType extends HtmlRspackPluginOptions {
@@ -1,3 +1,16 @@
1
1
  export type EMPModeType = 'development' | 'production';
2
2
  export type CliActionType = 'dev' | 'build' | 'serve';
3
- export type CliOptionsType = any;
3
+ export type EnvVarsType = Record<string, string>;
4
+ export type CliOptionsType = {
5
+ env?: string;
6
+ doctor?: boolean;
7
+ hot?: boolean;
8
+ open?: boolean;
9
+ ts?: boolean;
10
+ profile?: boolean;
11
+ clearLog?: boolean | string;
12
+ envVars?: EnvVarsType;
13
+ analyze?: boolean;
14
+ watch?: boolean;
15
+ serve?: boolean;
16
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@empjs/cli",
3
- "version": "4.0.0-alpha.1",
3
+ "version": "4.0.0-alpha.3",
4
4
  "description": "emp",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -76,6 +76,7 @@
76
76
  },
77
77
  "author": "Ken",
78
78
  "devDependencies": {
79
+ "@rstest/core": "0.10.6",
79
80
  "@types/compression": "^1.7.2",
80
81
  "@types/connect": "^3.4.38",
81
82
  "@types/cors": "^2.8.12",
@@ -87,6 +88,7 @@
87
88
  "@types/webpack": "^5.28.4",
88
89
  "@types/webpack-bundle-analyzer": "^4.6.2",
89
90
  "@types/webpack-sources": "^3.2.2",
91
+ "@vue/tsconfig": "^0.8.1",
90
92
  "chokidar": "^4.0.3",
91
93
  "vue": "^3.5.21"
92
94
  },
@@ -95,7 +97,6 @@
95
97
  "@rspack/core": "^2.0.0",
96
98
  "@rspack/dev-server": "^2.0.0",
97
99
  "@swc/helpers": "^0.5.18",
98
- "@vue/tsconfig": "^0.8.1",
99
100
  "address": "^2.0.2",
100
101
  "chalk": "^5.3.0",
101
102
  "commander": "11.1.0",
@@ -113,18 +114,28 @@
113
114
  "less-loader": "^12.2.0",
114
115
  "open": "10.2.0",
115
116
  "sass-embedded": "1.93.2",
116
- "sass-loader": "16.0.5",
117
+ "sass-loader": "17.0.0",
117
118
  "serve-static": "2.2.0",
118
- "ts-checker-rspack-plugin": "1.1.6",
119
+ "ts-checker-rspack-plugin": "1.4.0",
119
120
  "typescript-plugin-css-modules": "5.2.0",
120
121
  "webpack-bundle-analyzer": "4.10.2",
121
- "@empjs/chain": "4.0.0-alpha.1"
122
+ "@empjs/chain": "4.0.0-alpha.3"
122
123
  },
123
124
  "scripts": {
124
125
  "dev": "rslib build --watch --env-mode development",
125
126
  "build": "rslib build --env-mode production",
126
127
  "dev-rs": "pnpm run dev",
127
128
  "build-rs": "pnpm run build",
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",
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
+ "test:real:create-help": "rstest run test/cli-create-help.test.ts",
133
+ "test:real:executor": "rstest run test/agent-create-executor.test.ts",
134
+ "test:real:fix": "rstest run test/agent-create-fix.test.ts",
135
+ "test:real:generator": "rstest run test/agent-create-generator.test.ts",
136
+ "test:real:intent": "rstest run test/agent-create-intent.test.ts",
137
+ "test:real:planner": "rstest run test/agent-create-planner.test.ts",
138
+ "test:real:verify": "rstest run test/agent-create-verify.test.ts",
128
139
  "ph": "pnpm publish --no-git-checks"
129
140
  }
130
141
  }