@moneko/core 3.39.1 → 3.39.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.
@@ -0,0 +1,11 @@
1
+ import { exec, type ExecException } from 'node:child_process';
2
+ import { join } from 'node:path';
3
+ import { platform } from 'node:process';
4
+ import { fileExists, loadFile, println, saveFile } from '@moneko/utils';
5
+ import { createCA, createCert } from 'mkcert';
6
+ import log from './log.mjs';
7
+ import { getIPv4 } from './net.mjs';
8
+ import paths from './paths.mjs';
9
+ declare function installCallback(error: ExecException | null, _stdout: string, stderr: string);
10
+ export declare function installCA(certPath: string);
11
+ export declare async function setupCert(domain?: string, install?: boolean);
@@ -0,0 +1 @@
1
+ import{exec as t}from"node:child_process";import{join as o}from"node:path";import{platform as r}from"node:process";import{fileExists as e,loadFile as i,println as a,saveFile as n}from"@moneko/utils";import{createCA as s,createCert as l}from"mkcert";import m from"./log.mjs";import{getIPv4 as c}from"./net.mjs";import d from"./paths.mjs";function p(t,o,r){if(t&&!r.includes("already exists")){m(t);return}}export function installCA(o){return"darwin"===r?t(`security add-trusted-cert -d -r trustRoot -k "$HOME/Library/Keychains/login.keychain-db" "${o}"`,p):"win32"===r?t(`certutil -addstore -user "Root" "${o}"`,p):void a(`⚠️ 暂不支持自动安装 CA 的平台: ${r}`)}export async function setupCert(t="localhost",r=!0){let a=o(d.CA_DIR,`${t}_cert.pem`),m=o(d.CA_DIR,`${t}_key.pem`),p="Moneko Dev CA";if(!e(a)||!e(m)){let t=await s({organization:p,validity:365,countryCode:"CN",state:"Hunan",locality:"Changsha"});await Promise.all([n(a,t.cert),n(m,t.key)])}r&&installCA(a);let u=await Promise.all([i(m),i(a)]);return l({ca:{key:u[0],cert:u[1]},domains:[...new Set([t,"localhost","127.0.0.1",c()].filter(Boolean))],organization:p,validity:365})}
@@ -15,6 +15,7 @@ declare const paths: {
15
15
  readonly denoNodeModules;
16
16
  readonly corePath;
17
17
  readonly programPath;
18
+ readonly CA_DIR;
18
19
  readonly webpackCachePath;
19
20
  readonly lintCachePath;
20
21
  readonly httpCachePath;
@@ -1 +1 @@
1
- import{resolve as o}from"node:path";import e from"node:url";import{fileExists as t}from"@moneko/utils";let n=JSON.parse(process.env.npm_config_argv||'{"original":[]}').original;export const __dirname=e.fileURLToPath(new URL("..",import.meta.url));export const yarnArgv={};for(let o=0,e=n.length;o<e;o++){let e=n[o].split("=");Object.assign(yarnArgv,{[e[0]]:e[1]||!0})}export const CUSTOMCONFIG=process.env.npm_config_config||yarnArgv.config||process.env.__args__config__;let c=process.cwd(),a=o(c,"./node_modules"),r={nodeModules:a,pnpmNodeModules:o(a,"./.pnpm/node_modules"),denoNodeModules:o(a,"./.deno"),corePath:__dirname,programPath:c,webpackCachePath:o(a,"./.cache"),lintCachePath:o(a,"./.cache"),httpCachePath:o(a,"./.cache/http"),swcCachePath:o(a,"./.cache/.swc"),configPath:o(c,"./config/index.ts"),customConfigPath:o(c,`./config/${CUSTOMCONFIG}.ts`),coveragePath:o(c,"./coverage/clover.xml"),pagesPath:o(c,"./src/pages"),componentsPath:o(c,"./components"),mockPath:o(c,"./mock")};export const config_files=[t(r.configPath)&&r.configPath,t(r.customConfigPath)&&r.customConfigPath].filter(Boolean);export const routeDir="library"===process.env.APPTYPE?r.componentsPath:r.pagesPath;export default r;
1
+ import{resolve as o}from"node:path";import e from"node:url";import{fileExists as t}from"@moneko/utils";let c=JSON.parse(process.env.npm_config_argv||'{"original":[]}').original;export const __dirname=e.fileURLToPath(new URL("..",import.meta.url));export const yarnArgv={};for(let o=0,e=c.length;o<e;o++){let e=c[o].split("=");Object.assign(yarnArgv,{[e[0]]:e[1]||!0})}export const CUSTOMCONFIG=process.env.npm_config_config||yarnArgv.config||process.env.__args__config__;let n=process.cwd(),a=o(n,"./node_modules"),r={nodeModules:a,pnpmNodeModules:o(a,"./.pnpm/node_modules"),denoNodeModules:o(a,"./.deno"),corePath:__dirname,programPath:n,CA_DIR:o(a,"./.cache/.ca"),webpackCachePath:o(a,"./.cache"),lintCachePath:o(a,"./.cache"),httpCachePath:o(a,"./.cache/http"),swcCachePath:o(a,"./.cache/.swc"),configPath:o(n,"./config/index.ts"),customConfigPath:o(n,`./config/${CUSTOMCONFIG}.ts`),coveragePath:o(n,"./coverage/clover.xml"),pagesPath:o(n,"./src/pages"),componentsPath:o(n,"./components"),mockPath:o(n,"./mock")};export const config_files=[t(r.configPath)&&r.configPath,t(r.customConfigPath)&&r.customConfigPath].filter(Boolean);export const routeDir="library"===process.env.APPTYPE?r.componentsPath:r.pagesPath;export default r;
package/lib/config.mjs CHANGED
@@ -1 +1 @@
1
- import{relative as e}from"node:path";import{fileExists as o}from"@moneko/utils";import{merge as t}from"webpack-merge";import r from"./commom/paths.mjs";import s from"./commom/require.mjs";import n from"./commom/setup-env.mjs";import i from"./options/jsx-dom-expressions.mjs";import a from"./options/split-chunk.mjs";import{isFunction as m,node_modules as l,resolveProgram as p}from"./utils/index.mjs";import{APPTYPE as c,FRAMEWORK as u,frameworkVersion as d,isCI as f,isDev as h,isLibrary as g,isMobile as x,isReact as j,jsxImportSource as v,mainDirectory as P,NODE_ENV as C,PACKAGENAME as b}from"./process-env.mjs";let k=["@app","@moneko","neko-ui",".cache/http/data","@element-plus","ant-design-vue","element-plus","element-ui","ng-zorro-antd","@mui","@du","@fontsource","@fortawesome","font-pingfang-sc","font-pingfang-tc","katex","react-markdown-editor-lite","react-photo-view","schema-design","monaco-editor"];export function getConfig(e){return delete s.cache[e],new Promise(t=>{if(o(e)){let o=s(e).default;return t(m(o)?o(process):o)}return t({})})}let w=await Promise.all([n(C,c,u,[]),getConfig(r.configPath),getConfig(r.customConfigPath)]),y=w[0],O=w[1],M=w[2],I={strict:!1,devtool:h?"eval-cheap-module-source-map":"cheap-module-source-map",seo:!1,mode:"csr",bundleAnalyzer:!1,polyfill:!1,entry:{},minifier:{},sourceMap:{filename:"[file].map",publicPath:""},env:y,basename:"/",publicPath:"/",rem:{designSize:x?375:1920},fallbackCompPath:null,modifyVars:{},prefixCls:"n",alias:Object.assign({"@":p(P)},j&&d<18?{"react/package.json":l("react/package.json"),"react/jsx-runtime":l("react/jsx-runtime.js"),"react/jsx-dev-runtime":l("react/jsx-dev-runtime.js")}:{}),moduleRules:[],prefixJsLoader:[],cssModules:[],cssModuleDefinition:!0,importOnDemand:{"@moneko/common":{transform:"esm/${member}"},lodash:{transform:"${member}"}},proxy:{},devServer:{host:"localhost",port:3e3,open:!0,https:!1},htmlPluginOption:{title:b.toLocaleUpperCase(),favicon:e(r.programPath,`${r.corePath}/options/favicon.ico`)},copy:{},routerMode:"browser",fixBrowserRouter:!1,plugins:[],resolvePlugins:[],overrideResolve:!1,splitChunk:a,runtimeChunk:"single",moduleFederation:[],rulesInclude:{css:k,js:k,media:k,font:k,wasm:[]},mdx:{jsx:!1,development:h,jsxImportSource:v,providerImportSource:`@moneko/${u}/mdx`},jsxDomExpressions:i,bar:{name:"Client",nameColor:"68",msgColor:"242",barBgColor:"15",barColor:"69",quiet:f},normalizeCss:!0,externalsPresets:{},buildHttp:void 0,virtualModule:{},cssExtract:{},externals:["@swc/core"],lazyCompilation:!1,performance:!1,refresh:"solid"!==u,bundleId:"com.moneko.bid",bundles:[],stylelint:{},eslint:{lintDirtyModulesOnly:!1}};g&&(I.alias=Object.assign(I.alias,{"@pkg":r.componentsPath,[b]:r.componentsPath}));let z=I;(!1===(z=t(z,O,M)).devtool||!1===z.sourceMap)&&(z.sourceMap=!1,z.devtool=!1),z.fixBrowserRouter&&z.htmlPluginOption&&(z.htmlPluginOption.tags||(z.htmlPluginOption.tags=[]),z.htmlPluginOption.tags.push({textContent:"(function(l) {if (l.search[1] === '/' ) {var decoded = l.search.slice(1).split('&').map(function(s) {return s.replace(/~and~/g, '&')}).join('?');window.history.replaceState(null, null,l.pathname.slice(0, -1) + decoded + l.hash);}}(window.location))"}));export const CONFIG=z;export const PUBLICPATH=CONFIG.publicPath;
1
+ import{relative as e}from"node:path";import{fileExists as o}from"@moneko/utils";import{merge as t}from"webpack-merge";import r from"./commom/paths.mjs";import s from"./commom/require.mjs";import n from"./commom/setup-env.mjs";import i from"./options/jsx-dom-expressions.mjs";import a from"./options/split-chunk.mjs";import{isFunction as m,node_modules as l,resolveProgram as p}from"./utils/index.mjs";import{APPTYPE as c,FRAMEWORK as u,frameworkVersion as d,isCI as f,isDev as h,isLibrary as g,isMobile as v,isReact as x,jsxImportSource as j,mainDirectory as C,NODE_ENV as P,PACKAGENAME as b}from"./process-env.mjs";let k=["@app","@moneko","neko-ui",".cache/http/data","@element-plus","ant-design-vue","element-plus","element-ui","ng-zorro-antd","@mui","@du","@fontsource","@fortawesome","font-pingfang-sc","font-pingfang-tc","katex","react-markdown-editor-lite","react-photo-view","schema-design","monaco-editor"];export function getConfig(e){return delete s.cache[e],new Promise(t=>{if(o(e)){let o=s(e).default;return t(m(o)?o(process):o)}return t({})})}let w=await Promise.all([n(P,c,u,[]),getConfig(r.configPath),getConfig(r.customConfigPath)]),O=w[0],y=w[1],M=w[2],S={strict:!1,devtool:h?"eval-cheap-module-source-map":"cheap-module-source-map",seo:!1,mode:"csr",bundleAnalyzer:!1,polyfill:!1,entry:{},minifier:{},sourceMap:{filename:"[file].map",publicPath:""},env:O,basename:"/",publicPath:"/",rem:{designSize:v?375:1920},fallbackCompPath:null,modifyVars:{},prefixCls:"n",alias:Object.assign({"@":p(C)},x&&d<18?{"react/package.json":l("react/package.json"),"react/jsx-runtime":l("react/jsx-runtime.js"),"react/jsx-dev-runtime":l("react/jsx-dev-runtime.js")}:{}),moduleRules:[],prefixJsLoader:[],cssModules:[],cssModuleDefinition:!0,importOnDemand:{"@moneko/common":{transform:"esm/${member}"},lodash:{transform:"${member}"}},proxy:{},devServer:{host:"localhost",port:3e3,open:!0,https:!1},htmlPluginOption:{title:b.toLocaleUpperCase(),favicon:e(r.programPath,`${r.corePath}/options/favicon.ico`)},copy:{},routerMode:"browser",fixBrowserRouter:!1,plugins:[],resolvePlugins:[],overrideResolve:!1,splitChunk:a,runtimeChunk:"single",moduleFederation:[],rulesInclude:{css:k,js:k,media:k,font:k,wasm:[]},mdx:{jsx:!1,development:h,jsxImportSource:j,providerImportSource:`@moneko/${u}/mdx`},jsxDomExpressions:i,bar:{name:"Client",nameColor:"68",msgColor:"242",barBgColor:"15",barColor:"69",quiet:f},normalizeCss:!0,externalsPresets:{},buildHttp:void 0,virtualModule:{},cssExtract:{},externals:["@swc/core"],lazyCompilation:!1,performance:!1,refresh:"solid"!==u,bundleId:"com.moneko.bid",bundles:[],stylelint:{},eslint:{lintDirtyModulesOnly:!1}};g&&(S.alias=Object.assign(S.alias,{"@pkg":r.componentsPath,[b]:r.componentsPath}));let I=S;(!1===(I=t(I,y,M)).devtool||!1===I.sourceMap)&&(I.sourceMap=!1,I.devtool=!1),I.fixBrowserRouter&&I.htmlPluginOption&&(I.htmlPluginOption.tags||(I.htmlPluginOption.tags=[]),I.htmlPluginOption.tags.push({textContent:"(function(l) {if (l.search[1] === '/' ) {var decoded = l.search.slice(1).split('&').map(function(s) {return s.replace(/~and~/g, '&')}).join('?');window.history.replaceState(null, null,l.pathname.slice(0, -1) + decoded + l.hash);}}(window.location))"})),"true"===process.env.CODESPACES&&(I.devServer.https=!1);export const CONFIG=I;export const PUBLICPATH=CONFIG.publicPath;
package/lib/dev.d.mts CHANGED
@@ -3,13 +3,12 @@ import { type createReadStream, type existsSync, watchFile } from 'node:fs';
3
3
  import { extname, relative, sep } from 'node:path';
4
4
  import { ink, loadFile, print, println, progressBar } from '@moneko/utils';
5
5
  import fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify';
6
- import { createCA, createCert } from 'mkcert';
7
6
  import webpack, { type Compiler, type OutputFileSystem, type Watching, type WebpackPluginInstance } from 'webpack';
8
7
  import webpackHotMiddleware, { type ClientOptions } from 'webpack-hot-middleware';
9
8
  import { merge } from 'webpack-merge';
9
+ import { setupCert } from './commom/ca.mjs';
10
10
  import { diffObject } from './commom/diff-object.mjs';
11
11
  import mime from './commom/mime.mjs';
12
- import { getIPv4 } from './commom/net.mjs';
13
12
  import open from './commom/open.mjs';
14
13
  import paths, { config_files } from './commom/paths.mjs';
15
14
  import sigintExit from './commom/sigint-exit.mjs';
package/lib/dev.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{exec as e,spawn as t}from"node:child_process";import{watchFile as o}from"node:fs";import{extname as r,relative as s,sep as n}from"node:path";import{ink as i,loadFile as l,print as a,println as c,progressBar as m}from"@moneko/utils";import p from"fastify";import{createCA as d,createCert as h}from"mkcert";import f from"webpack";import u from"webpack-hot-middleware";import{merge as g}from"webpack-merge";import{diffObject as y}from"./commom/diff-object.mjs";import v from"./commom/mime.mjs";import{getIPv4 as w}from"./commom/net.mjs";import x from"./commom/open.mjs";import b,{config_files as k}from"./commom/paths.mjs";import $ from"./commom/sigint-exit.mjs";import{devLog as C,getServerAddress as j,PORT as S}from"./dev/config.mjs";import P from"./dev/mock.mjs";import{setupProxy as A}from"./dev/proxy.mjs";import _ from"./options/reslove.mjs";import z from"./plugin/eslint.mjs";import T from"./plugin/stylelint.mjs";import{empty as E}from"./utils/index.mjs";import{commonConfig as H}from"./common.mjs";import{CONFIG as I,getConfig as M,PUBLICPATH as O}from"./config.mjs";import{outputFileSystem as B}from"./file-system.mjs";import R from"./module.config.mjs";import{isLibrary as q,isReact as U,refresh as D}from"./process-env.mjs";let F=`${O.endsWith("/")?"":"/"}__hmr__`,N=new URLSearchParams({name:"client",path:F,dynamicPublicPath:!0,timeout:2e3,reload:!D,quiet:!0,noInfo:!0,overlay:!1,autoConnect:!0}).toString(),L=g(H,{watchOptions:{ignored:/node_modules\/(?!(@app|@moneko)).+/},entry:{main:[`${_.hotMiddlewareClient}?${N}`]},module:R(!1),plugins:[new f.HotModuleReplacementPlugin,new f.WatchIgnorePlugin({paths:[/node_modules\/(?!(@app|@moneko)).+/,/\.d\.ts$/]})]});if(L.plugins||(L.plugins=[]),U){let e=(await import("@pmmmwh/react-refresh-webpack-plugin")).default;L.plugins.push(new e({overlay:!1}))}function G(e){let t=e.join(","),o=[s(b.programPath,`${I.alias["@"]}/**/*.{${t}}`).replace(/\\/g,"/")];return q&&o.push(s(b.programPath,`${I.alias["@pkg"]}/**/*.{${t}}`).replace(/\\/g,"/")),o}I.eslint&&L.plugins.push(new z({fix:!0,cache:!0,cacheLocation:`${b.lintCachePath}/.eslintcache`,cacheStrategy:"metadata",files:G(["js","jsx","ts","tsx","json","html","vue"]),...I.eslint})),I.stylelint&&L.plugins.push(new T({fix:!0,cache:!0,cacheLocation:`${b.lintCachePath}/.stylelintcache`,files:G(["css","scss","sass","less","ts","tsx","js","jsx"]),...I.stylelint}));let W=!1,K="/____progress____",X={percentage:0,info:""};if(I.bar){let e=I.bar,t=e.name||"Build";L.plugins.push(new f.ProgressPlugin({handler(o,r,...s){let n=s.length?`[${r}] ${s.join(" ")}`:" ";W||(X.info=n,X.percentage=o,W=1===o),e.quiet?process.stdout.write(`${n}
2
- `):(m(o||0,1,{msg:n,name:t,barColor:e.barColor,nameColor:e.nameColor,barBgColor:e.barBgColor,msgColor:e.msgColor}),1===o&&process.stdout.write("\r\x1b[2K"))}}))}let Y=f(L);Y.outputFileSystem=B;let J=Y.watch(Y.options.watchOptions,C);Y.hooks.done.tap("client-log",e=>{C(null,e)});let Q={};async function V(){if("object"==typeof I.devServer.https&&I.devServer.https.key&&I.devServer.https.cert){let e=await Promise.all([l(I.devServer.https.key),l(I.devServer.https.cert)]);return e[0]||(c(i(`法加载私钥。请检查路径和文件是否存在,并确保路径正确:${I.devServer.https.key}`,"red")),process.exit(1)),e[1]||(c(i(`无法加载证书。请检查路径和文件是否存在,并确保路径正确:${I.devServer.https.cert}`,"red")),process.exit(1)),{key:e[0],cert:e[1]}}let e=await d({organization:"Moneko Dev CA",countryCode:"CN",state:"Hunan",locality:"Changsha",validity:365});return await h({ca:{key:e.key,cert:e.cert},organization:"Moneko Dev CA",domains:[...new Set([I.devServer.host,"localhost","127.0.0.1",w()].filter(Boolean))],validity:365})}if(I.devServer.https){let e=await V();Q.http2=!0,Q.https={key:e.key,cert:e.cert}}let Z=u(Y,{log:!1,path:F,heartbeat:2e3}),ee=p({logger:!1,...Q});P(ee,{directory:b.mockPath}),A(ee,I.proxy);let et={"Access-Control-Allow-Credentials":"true","Access-Control-Allow-Headers":"DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization","Access-Control-Allow-Methods":"GET, POST, OPTIONS, DELETE, PATCH, PUT","Access-Control-Allow-Origin":"*","Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate",Pragma:"no-cache",Expires:"0",...I.devServer.headers||{}};function eo(e,t,o){t.headers(et),e.headers.origin&&t.header("Access-Control-Allow-Origin",e.headers.origin);let s=Y.outputFileSystem,n=e.headers["accept-encoding"],i=n?.includes("br"),l=`${o}.${i?"br":"gz"}`,a=s.existsSync?.(l);a&&t.header("content-encoding",i?"br":"gzip");let c=s.createReadStream?.(a?l:o,{autoClose:!0});c?.on("error",e=>{if(c.destroy(),!t.sent)return t.code(404).type("text/html").send(`File not found: ${e.message}`)});let m=v[r(o)];return m&&t.header("content-type",m),t.send(c)}function er(){process.exit(0)}ee.get(K,(e,t)=>{t.headers(et),t.send(X)}),ee.get(`/${F}`.replace("//","/"),async(e,t)=>{if("text/event-stream"===e.headers.accept){e.raw.url=F,Z(e.raw,t.raw,()=>{t.raw.writableEnded&&(t.sent=!0)});return}}),ee.addHook("onRequest",(e,t,o)=>{if(e.url===K)return o();if(!W)return t.type("text/html").send(function(e){let t=Math.floor(100*e.percentage);return`<!DOCTYPE html><html><head><title>Building...</title><link rel="image/x-icon" href="/favicon.ico"><style>html{ display:flex; justify-content:center; align-items:center; block-size:100vb;}.progress-container{ position:relative; overflow:hidden; margin:1rem auto; border:0.0625rem solid #ccc; border-radius:0.625rem; inline-size:18.75rem; block-size:1.25rem;}.progress-bar{ block-size:100%; background:#4caf50; inline-size:0%; transition:inline-size 0.5s ease;}#progress-text{ position:absolute; margin:auto; font-size:0.875rem; font-family:sans-serif; font-weight:600; text-align:center; color:#fff; text-shadow:0 0 0.0625rem black; inset-inline:0; inset-block:0; line-height:1.25rem;}#progress-info{ font-size:small; font-family:sans-serif; font-weight:100; text-align:center; opacity:0.5; margin-block-start:0.625rem;}</style></head><body><div class="progress-container"><div class="progress-bar"></div><div id="progress-text">${t}%</div></div><div id="progress-info">${e.info}</div><script>function checkProgress() {fetch('${K}').then(r => r.json()) .then(data => {const percentage = Math.floor(data.percentage * 100);document.querySelector('.progress-bar').style.width = percentage + '%';document.getElementById('progress-text').textContent = percentage + '%';document.getElementById('progress-info').textContent = data.info;if (percentage === 100) {window.location.reload();} else {setTimeout(checkProgress, 500);}});}checkProgress();</script></body></html>`}(X)),o();let r=decodeURIComponent(`${Y.options.output.path}${n}${"/"===e.url?"index.html":e.url}`);return Y.outputFileSystem?.existsSync?.(r)?eo(e,t,r):o()}),ee.setNotFoundHandler((e,t)=>eo(e,t,`${Y.options.output.path}${n}index.html`)),ee.addHook("onClose",()=>{J.close(E),ee.server.close(E)}),ee.listen({port:S}),I.devServer.open&&x(j("local"));let es=await Promise.all(k.map(M)),en=g(es[0]||{},es[1]||{});k.forEach(function(t){o(t,async function(){let[o,r]=await Promise.all(k.map(M)),s=g(o||{},r||{}),n=y(en,s);1===Object.keys(n).length&&"proxy"in n?(a(i(`代理更新中...`,"yellow"),!0),await A(ee,s.proxy),a(i(`代理更新完成...`,"green"),!0),I.proxy=s.proxy,en.proxy=s.proxy,en=s):(en=s,c(i(`检测到工程配置${i(`[${t}]`,"blue")}变更, 程序即将重启...`,"yellow"),!0),e(ei?`netstat -ano | findstr :${S}`:`lsof -i :${S} -t`,(e,t)=>{if(e){c(i(`查找端口 ${S} 时发生错误: ${e.message}`,"red")),c(i("请尝试手动重启程序","yellow"));return}let o=t.trim().replace(/\r\n/g,"\n").split("\n").filter(Boolean),r=ei?o[0]?.split(/\s+/).pop()?.trim():o[0]?.trim();if(!r){c(i(`未找到占用端口 ${S} 的进程, 请尝试手动重启程序`,"yellow"));return}try{process.kill(Number(r),"SIGHUP")}catch(e){c(i(`终止进程 ${r} 时发生错误: ${e.message}`,"red"))}}))})});let ei="win32"===process.platform;process.on("SIGHUP",function(){ee.close(E),function(){let e=t(process.argv[0],process.argv.slice(1),{detached:!1,stdio:"inherit"});e.unref(),e.on("close",er)}()}),process.on("exit",function(){ee.close(E)}),$(er);
1
+ import{exec as e,spawn as t}from"node:child_process";import{watchFile as o}from"node:fs";import{extname as r,relative as s,sep as n}from"node:path";import{ink as i,loadFile as l,print as a,println as c,progressBar as m}from"@moneko/utils";import p from"fastify";import d from"webpack";import h from"webpack-hot-middleware";import{merge as f}from"webpack-merge";import{setupCert as u}from"./commom/ca.mjs";import{diffObject as g}from"./commom/diff-object.mjs";import y from"./commom/mime.mjs";import v from"./commom/open.mjs";import w,{config_files as x}from"./commom/paths.mjs";import b from"./commom/sigint-exit.mjs";import{devLog as $,getServerAddress as j,PORT as k}from"./dev/config.mjs";import C from"./dev/mock.mjs";import{setupProxy as S}from"./dev/proxy.mjs";import P from"./options/reslove.mjs";import _ from"./plugin/eslint.mjs";import A from"./plugin/stylelint.mjs";import{empty as z}from"./utils/index.mjs";import{commonConfig as T}from"./common.mjs";import{CONFIG as E,getConfig as I,PUBLICPATH as O}from"./config.mjs";import{outputFileSystem as H}from"./file-system.mjs";import B from"./module.config.mjs";import{isLibrary as M,isReact as R,refresh as q}from"./process-env.mjs";let U=`${O.endsWith("/")?"":"/"}__hmr__`,F=new URLSearchParams({name:"client",path:U,dynamicPublicPath:!0,timeout:2e3,reload:!q,quiet:!0,noInfo:!0,overlay:!1,autoConnect:!0}).toString(),L=f(T,{watchOptions:{ignored:/node_modules\/(?!(@app|@moneko)).+/},entry:{main:[`${P.hotMiddlewareClient}?${F}`]},module:B(!1),plugins:[new d.HotModuleReplacementPlugin,new d.WatchIgnorePlugin({paths:[/node_modules\/(?!(@app|@moneko)).+/,/\.d\.ts$/]})]});if(L.plugins||(L.plugins=[]),R){let e=(await import("@pmmmwh/react-refresh-webpack-plugin")).default;L.plugins.push(new e({overlay:!1}))}function N(e){let t=e.join(","),o=[s(w.programPath,`${E.alias["@"]}/**/*.{${t}}`).replace(/\\/g,"/")];return M&&o.push(s(w.programPath,`${E.alias["@pkg"]}/**/*.{${t}}`).replace(/\\/g,"/")),o}E.eslint&&L.plugins.push(new _({fix:!0,cache:!0,cacheLocation:`${w.lintCachePath}/.eslintcache`,cacheStrategy:"metadata",files:N(["js","jsx","ts","tsx","json","html","vue"]),...E.eslint})),E.stylelint&&L.plugins.push(new A({fix:!0,cache:!0,cacheLocation:`${w.lintCachePath}/.stylelintcache`,files:N(["css","scss","sass","less","ts","tsx","js","jsx"]),...E.stylelint}));let D=!1,G="/____progress____",W={percentage:0,info:""};if(E.bar){let e=E.bar,t=e.name||"Build";L.plugins.push(new d.ProgressPlugin({handler(o,r,...s){let n=s.length?`[${r}] ${s.join(" ")}`:" ";D||(W.info=n,W.percentage=o,D=1===o),e.quiet?process.stdout.write(`${n}
2
+ `):(m(o||0,1,{msg:n,name:t,barColor:e.barColor,nameColor:e.nameColor,barBgColor:e.barBgColor,msgColor:e.msgColor}),1===o&&process.stdout.write("\r\x1b[2K"))}}))}let K=d(L);K.outputFileSystem=H;let X=K.watch(K.options.watchOptions,$);K.hooks.done.tap("client-log",e=>{$(null,e)});let Y={};async function J(){if("object"==typeof E.devServer.https&&"key"in E.devServer.https){let e=await Promise.all([l(E.devServer.https.key),l(E.devServer.https.cert)]);return e[0]||(c(i(`法加载私钥。请检查路径和文件是否存在,并确保路径正确:${E.devServer.https.key}`,"red")),process.exit(1)),e[1]||(c(i(`无法加载证书。请检查路径和文件是否存在,并确保路径正确:${E.devServer.https.cert}`,"red")),process.exit(1)),{key:e[0],cert:e[1]}}return u(E.devServer.host,!0===E.devServer.https||"object"==typeof E.devServer.https&&E.devServer.https.install)}E.devServer.https&&(Y.http2=!0,Y.https=await J());let Q=h(K,{log:!1,path:U,heartbeat:2e3}),V=p({logger:!1,...Y});C(V,{directory:w.mockPath}),S(V,E.proxy);let Z={"Access-Control-Allow-Credentials":"true","Access-Control-Allow-Headers":"DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization","Access-Control-Allow-Methods":"GET, POST, OPTIONS, DELETE, PATCH, PUT","Access-Control-Allow-Origin":"*","Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate",Pragma:"no-cache",Expires:"0",...E.devServer.headers||{}};function ee(e,t,o){t.headers(Z),e.headers.origin&&t.header("Access-Control-Allow-Origin",e.headers.origin);let s=K.outputFileSystem,n=e.headers["accept-encoding"],i=n?.includes("br"),l=`${o}.${i?"br":"gz"}`,a=s.existsSync?.(l);a&&t.header("content-encoding",i?"br":"gzip");let c=s.createReadStream?.(a?l:o,{autoClose:!0});c?.on("error",e=>{if(c.destroy(),!t.sent)return t.code(404).type("text/html").send(`File not found: ${e.message}`)});let m=y[r(o)];return m&&t.header("content-type",m),t.send(c)}function et(){process.exit(0)}V.get(G,(e,t)=>{t.headers(Z),t.send(W)}),V.get(`/${U}`.replace("//","/"),async(e,t)=>{if("text/event-stream"===e.headers.accept){e.raw.url=U,Q(e.raw,t.raw,()=>{t.raw.writableEnded&&(t.sent=!0)});return}}),V.addHook("onRequest",(e,t,o)=>{if(e.url===G)return o();if(!D)return t.type("text/html").send(function(e){let t=Math.floor(100*e.percentage);return`<!DOCTYPE html><html><head><title>Building...</title><link rel="image/x-icon" href="/favicon.ico"><style>html{ display:flex; justify-content:center; align-items:center; block-size:100vb;}.progress-container{ position:relative; overflow:hidden; margin:1rem auto; border:0.0625rem solid #ccc; border-radius:0.625rem; inline-size:18.75rem; block-size:1.25rem;}.progress-bar{ block-size:100%; background:#4caf50; inline-size:0%; transition:inline-size 0.5s ease;}#progress-text{ position:absolute; margin:auto; font-size:0.875rem; font-family:sans-serif; font-weight:600; text-align:center; color:#fff; text-shadow:0 0 0.0625rem black; inset-inline:0; inset-block:0; line-height:1.25rem;}#progress-info{ font-size:small; font-family:sans-serif; font-weight:100; text-align:center; opacity:0.5; margin-block-start:0.625rem;}</style></head><body><div class="progress-container"><div class="progress-bar"></div><div id="progress-text">${t}%</div></div><div id="progress-info">${e.info}</div><script>function checkProgress() {fetch('${G}').then(r => r.json()) .then(data => {const percentage = Math.floor(data.percentage * 100);document.querySelector('.progress-bar').style.width = percentage + '%';document.getElementById('progress-text').textContent = percentage + '%';document.getElementById('progress-info').textContent = data.info;if (percentage === 100) {window.location.reload();} else {setTimeout(checkProgress, 500);}});}checkProgress();</script></body></html>`}(W)),o();let r=decodeURIComponent(`${K.options.output.path}${n}${"/"===e.url?"index.html":e.url}`);return K.outputFileSystem?.existsSync?.(r)?ee(e,t,r):o()}),V.setNotFoundHandler((e,t)=>ee(e,t,`${K.options.output.path}${n}index.html`)),V.addHook("onClose",()=>{X.close(z),V.server.close(z)}),V.listen({port:k}),E.devServer.open&&v(j("local"));let eo=await Promise.all(x.map(I)),er=f(eo[0]||{},eo[1]||{});x.forEach(function(t){o(t,async function(){let[o,r]=await Promise.all(x.map(I)),s=f(o||{},r||{}),n=g(er,s);1===Object.keys(n).length&&"proxy"in n?(a(i(`代理更新中...`,"yellow"),!0),await S(V,s.proxy),a(i(`代理更新完成...`,"green"),!0),E.proxy=s.proxy,er.proxy=s.proxy,er=s):(er=s,c(i(`检测到工程配置${i(`[${t}]`,"blue")}变更, 程序即将重启...`,"yellow"),!0),e(es?`netstat -ano | findstr :${k}`:`lsof -i :${k} -t`,(e,t)=>{if(e){c(i(`查找端口 ${k} 时发生错误: ${e.message}`,"red")),c(i("请尝试手动重启程序","yellow"));return}let o=t.trim().replace(/\r\n/g,"\n").split("\n").filter(Boolean),r=es?o[0]?.split(/\s+/).pop()?.trim():o[0]?.trim();if(!r){c(i(`未找到占用端口 ${k} 的进程, 请尝试手动重启程序`,"yellow"));return}try{process.kill(Number(r),"SIGHUP")}catch(e){c(i(`终止进程 ${r} 时发生错误: ${e.message}`,"red"))}}))})});let es="win32"===process.platform;process.on("SIGHUP",function(){V.close(z),function(){let e=t(process.argv[0],process.argv.slice(1),{detached:!1,stdio:"inherit"});e.unref(),e.on("close",et)}()}),process.on("exit",function(){V.close(z)}),b(et);
@@ -1 +1 @@
1
- import e from"webpack";import t from"./plugin/compression.mjs";import{CopyPlugin as i}from"./plugin/copy.mjs";import{HtmlPlugin as o}from"./plugin/html-plugin.mjs";import r from"./plugin/module-federation.mjs";import{VirtualModuleWebpackPlugin as l}from"./plugin/virtual-module.mjs";import{CONFIG as n}from"./config.mjs";import{isDev as p,packageJson as a}from"./process-env.mjs";let s=[...r,new l(n.virtualModule),new i(n.copy),new e.DefinePlugin({"process.env":JSON.stringify(n.env)}),new e.IgnorePlugin({resourceRegExp:/\/(__(tests|mocks)__|test|spec|e2e)\//}),...n.plugins,p&&new t({algorithm:"brotli",test:/\.(js|css|html|svg)$/})].filter(Boolean);if(n.htmlPluginOption){let e={charset:"UTF-8","X-UA-Compatible":{"http-equiv":"X-UA-Compatible",content:"IE=edge,Chrome=1"},HandheldFriendly:"true",MobileOptimized:"320","screen-orientation":"portrait","x5-orientation":"portrait",browsermode:"application","x5-page-mode":"app","msapplication-tap-highlight":"no","mobile-web-app-capable":"yes",renderer:"webkit",description:a.description,keywords:Array.isArray(a.keywords)?a.keywords.toString():"","http-equiv":"refresh",viewport:"width=device-width, initial-scale=1"};n.seo&&(e.relCanonical={rel:"canonical",href:`https://${n.seo.domain}${n.basename}`}),n.htmlPluginOption.meta&&Object.assign(e,n.htmlPluginOption.meta),s.push(new o({...n.htmlPluginOption,meta:e}))}if(n.fixBrowserRouter){let e=n.basename.split("/").filter(Boolean).length,t=`${Array(e).fill("..").join("/")+(e?"/":"")}404.html`,i=n.fixBrowserRouter.pathSegmentsToKeep??e;s.push(new o({filename:n.fixBrowserRouter.path??t,inject:!1,templateContent:()=>`<html lang="en"><head><title>Redirect</title><script>const pathKeep = ${i};const l = window.location;l.replace(l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') + l.pathname.split('/').slice(0, 1 + pathKeep).join('/') + '/?/' + l.pathname.slice(1).split('/').slice(pathKeep).join('/').replace(/&/g, '~and~') + (l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') + l.hash);</script></head><body></body></html>`}))}n.sourceMap&&s.push(new e.SourceMapDevToolPlugin(n.sourceMap));export default s;
1
+ import e from"webpack";import t from"./plugin/compression.mjs";import{CopyPlugin as i}from"./plugin/copy.mjs";import{HtmlPlugin as o}from"./plugin/html-plugin.mjs";import r from"./plugin/module-federation.mjs";import{VirtualModuleWebpackPlugin as l}from"./plugin/virtual-module.mjs";import{CONFIG as n}from"./config.mjs";import{isDev as p,packageJson as a}from"./process-env.mjs";let s=[...r,new l(n.virtualModule),new i(n.copy),new e.DefinePlugin({"process.env":JSON.stringify(n.env)}),new e.IgnorePlugin({resourceRegExp:/\/(__(tests|mocks)__|test|spec|e2e)\//}),...n.plugins,p&&new t({algorithm:n.devServer.https?"brotli":"gzip",test:/\.(js|css|html|svg)$/})].filter(Boolean);if(n.htmlPluginOption){let e={charset:"UTF-8","X-UA-Compatible":{"http-equiv":"X-UA-Compatible",content:"IE=edge,Chrome=1"},HandheldFriendly:"true",MobileOptimized:"320","screen-orientation":"portrait","x5-orientation":"portrait",browsermode:"application","x5-page-mode":"app","msapplication-tap-highlight":"no","mobile-web-app-capable":"yes",renderer:"webkit",description:a.description,keywords:Array.isArray(a.keywords)?a.keywords.toString():"","http-equiv":"refresh",viewport:"width=device-width, initial-scale=1"};n.seo&&(e.relCanonical={rel:"canonical",href:`https://${n.seo.domain}${n.basename}`}),n.htmlPluginOption.meta&&Object.assign(e,n.htmlPluginOption.meta),s.push(new o({...n.htmlPluginOption,meta:e}))}if(n.fixBrowserRouter){let e=n.basename.split("/").filter(Boolean).length,t=`${Array(e).fill("..").join("/")+(e?"/":"")}404.html`,i=n.fixBrowserRouter.pathSegmentsToKeep??e;s.push(new o({filename:n.fixBrowserRouter.path??t,inject:!1,templateContent:()=>`<html lang="en"><head><title>Redirect</title><script>const pathKeep = ${i};const l = window.location;l.replace(l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') + l.pathname.split('/').slice(0, 1 + pathKeep).join('/') + '/?/' + l.pathname.slice(1).split('/').slice(pathKeep).join('/').replace(/&/g, '~and~') + (l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') + l.hash);</script></head><body></body></html>`}))}n.sourceMap&&s.push(new e.SourceMapDevToolPlugin(n.sourceMap));export default s;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moneko/core",
3
- "version": "3.39.1",
3
+ "version": "3.39.3",
4
4
  "description": "core",
5
5
  "main": "lib/index.mjs",
6
6
  "type": "module",
@@ -43,7 +43,7 @@
43
43
  "style-loader": "4.0.0",
44
44
  "swc-loader": "0.2.6",
45
45
  "typescript": "5.8.3",
46
- "webpack": "5.99.3",
46
+ "webpack": "5.99.5",
47
47
  "webpack-hot-middleware": "2.26.1",
48
48
  "webpack-merge": "6.0.1",
49
49
  "webpack-virtual-modules": "0.6.2"
@@ -264,6 +264,11 @@ export declare type ConfigType = {
264
264
  * 'server.key'
265
265
  */
266
266
  cert: string;
267
+ } | {
268
+ /** 安装 CA 根证书
269
+ * @default true
270
+ */
271
+ install: boolean;
267
272
  };
268
273
  /** 打开浏览器
269
274
  * @default true