@moneko/core 4.6.2 → 4.6.4

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/lib/common.mjs CHANGED
@@ -1 +1 @@
1
- import{extname as e,join as t,resolve as s}from"node:path";import o from"./commom/has-pkg.mjs";import a,{config_files as n,CUSTOMCONFIG as i}from"./commom/paths.mjs";import*as r from"./commom/rule.mjs";import{OverrideResolverPlugin as l}from"./plugin/override-resolve.mjs";import{isObject as m,resolveProgram as c}from"./utils/index.mjs";import{CONFIG as p}from"./config.mjs";import u from"./plugins.config.mjs";import{app_schema as d,CACHE_NAME as h,isDev as f,isLibrary as g,packageJson as y,projectNameCamelCase as b}from"./process-env.mjs";export const outputConfig={path:c(g?"docs":"dist"),filename:e=>e.filename?.includes(".worker")?"worker/[name].js":"js/[name].[contenthash].min.js",chunkFilename:"js/[contenthash].js",cssFilename:"style/[contenthash].css",cssChunkFilename:"style/[contenthash].css",assetModuleFilename:t=>{let s=e(t.filename||"").substring(1);return`assets/${s}/[hash][ext]`},library:{name:`${b}`,type:"umd",umdNamedDefine:!0},globalObject:"self",chunkLoadingGlobal:`webpackJsonp_${y.name}`,pathinfo:f,clean:!0,publicPath:p.publicPath,asyncChunks:!0,charset:!0,iife:!0,crossOriginLoading:"use-credentials",enabledWasmLoadingTypes:["fetch"],uniqueName:`${b}`};let j={main:[o(t(p.alias["@"],"service-worker")),`${d}:entry`].filter(Boolean)},v=[t(a.corePath,"./polyfills/public-path.mjs")];if(f&&p.refresh&&p.env.injectRemoteReactRefresh&&v.push(t(a.corePath,"./polyfills/inject-react-refresh.mjs")),p.polyfill&&v.push(t(a.corePath,"./polyfills/replace-children.mjs")),p.entry&&("string"==typeof p.entry?j={...j,main:[p.entry]}:Object.keys(p.entry)&&(j=Object.assign(j,p.entry))),"string"==typeof j.main?j.main=[...v,j.main]:Array.isArray(j.main)&&(j.main=[...v,...j.main]),p.output){if("string"==typeof p.output)outputConfig.path=p.output;else if(Object.keys(p.output)){let e=p.output,t={...outputConfig.library};Object.assign(outputConfig,e),"object"==typeof p.output&&e.library&&(outputConfig.library=Object.assign(t,e.library))}}let C={type:"filesystem",allowCollectingMemory:!0,cacheDirectory:a.webpackCachePath,memoryCacheUnaffected:!0,name:h,version:`${y.version}`,buildDependencies:{config:n},maxMemoryGenerations:1};!1===p.cache?C=!1:m(p.cache)&&(C=Object.assign(C,p.cache));let P={},k={imports:!0,entries:!0,test:e=>{let s=e.nameForCondition();return!!(s&&(/^[a-z][a-z0-9]*:.+$/.test(s)||s?.startsWith(t(a.programPath,"src"))||s?.startsWith(t(a.programPath,"site"))||s?.startsWith(a.componentsPath)))}};p.lazyCompilation&&f&&"true"!==process.env.IS_BUILD?m(p.lazyCompilation)?Object.assign(P,k,p.lazyCompilation):Object.assign(P,k):P=!1;export const commonConfig={name:"client",target:"web",devtool:p.devtool,entry:j,mode:p.mode??"production",cache:C,snapshot:{immutablePaths:[a.pnpmNodeModules,a.denoNodeModules,r.node_modules],managedPaths:[a.pnpmNodeModules,a.denoNodeModules,r.node_modules],resolveBuildDependencies:{timestamp:!0,hash:!0},resolve:{timestamp:!0,hash:!0},module:{timestamp:!0,hash:!0},buildDependencies:{timestamp:!0,hash:!0},contextModule:{timestamp:!0,hash:!0}},stats:"errors-only",infrastructureLogging:{level:"error"},externalsPresets:p.externalsPresets,plugins:u,node:{global:!1,__filename:!1,__dirname:!1},experiments:{asyncWebAssembly:!0,cacheUnaffected:!0,lazyCompilation:P,buildHttp:m(p.buildHttp)?{allowedUris:[],lockfileLocation:s(a.httpCachePath,"http.lock"),cacheLocation:s(a.httpCachePath,"data"),upgrade:!0,...p.buildHttp}:p.buildHttp,backCompat:!0,futureDefaults:!0,css:!0,outputModule:!1,deferImport:!0},resolve:{extensions:[".mts",".mjs",".ts",".tsx",".js",".jsx",".json",".wasm"],alias:p.alias,modules:[a.nodeModules,a.pnpmNodeModules,a.denoNodeModules],mainFields:["browser","module","main"],mainFiles:["index"],plugins:p.resolvePlugins,preferAbsolute:!0,cache:!0,fallback:{}},externals:p.externals,output:outputConfig,recordsPath:p.recordsPath};p.overrideResolve&&commonConfig.resolve.plugins.push(new l(Object.assign({original:p.alias["@"],override:i&&c(i)},p.overrideResolve)));
1
+ import{extname as e,join as t,resolve as s}from"node:path";import o from"./commom/has-pkg.mjs";import a,{config_files as n,CUSTOMCONFIG as i}from"./commom/paths.mjs";import*as r from"./commom/rule.mjs";import{OverrideResolverPlugin as l}from"./plugin/override-resolve.mjs";import{isObject as m,resolveProgram as c}from"./utils/index.mjs";import{CONFIG as p}from"./config.mjs";import u from"./plugins.config.mjs";import{app_schema as h,CACHE_NAME as d,isDev as f,isLibrary as g,packageJson as y,projectNameCamelCase as b}from"./process-env.mjs";export const outputConfig={path:c(g?"docs":"dist"),filename:e=>e.filename?.includes(".worker")?"worker/[name].js":e.chunk?.name==="main"?"js/[name].[contenthash].entry.js":"js/[name].[contenthash].js",chunkFilename:"js/[contenthash].js",cssFilename:"style/[contenthash].css",cssChunkFilename:"style/[contenthash].css",assetModuleFilename:t=>{let s=e(t.filename||"").substring(1);return`assets/${s}/[hash][ext]`},library:{name:`${b}`,type:"umd",umdNamedDefine:!0},globalObject:"self",chunkLoadingGlobal:`webpackJsonp_${y.name}`,pathinfo:f,clean:!0,publicPath:p.publicPath,asyncChunks:!0,charset:!0,iife:!0,crossOriginLoading:"use-credentials",enabledWasmLoadingTypes:["fetch"],uniqueName:`${b}`};let j={main:[o(t(p.alias["@"],"service-worker")),`${h}:entry`].filter(Boolean)},v=[t(a.corePath,"./polyfills/public-path.mjs")];if(f&&p.refresh&&p.env.injectRemoteReactRefresh&&v.push(t(a.corePath,"./polyfills/inject-react-refresh.mjs")),p.polyfill&&v.push(t(a.corePath,"./polyfills/replace-children.mjs")),p.entry&&("string"==typeof p.entry?j={...j,main:[p.entry]}:Object.keys(p.entry)&&(j=Object.assign(j,p.entry))),"string"==typeof j.main?j.main=[...v,j.main]:Array.isArray(j.main)&&(j.main=[...v,...j.main]),p.output){if("string"==typeof p.output)outputConfig.path=p.output;else if(Object.keys(p.output)){let e=p.output,t={...outputConfig.library};Object.assign(outputConfig,e),"object"==typeof p.output&&e.library&&(outputConfig.library=Object.assign(t,e.library))}}let C={type:"filesystem",allowCollectingMemory:!0,cacheDirectory:a.webpackCachePath,memoryCacheUnaffected:!0,name:d,version:`${y.version}`,buildDependencies:{config:n},maxMemoryGenerations:1};!1===p.cache?C=!1:m(p.cache)&&(C=Object.assign(C,p.cache));let P={},k={imports:!0,entries:!0,test:e=>{let s=e.nameForCondition();return!!(s&&(/^[a-z][a-z0-9]*:.+$/.test(s)||s?.startsWith(t(a.programPath,"src"))||s?.startsWith(t(a.programPath,"site"))||s?.startsWith(a.componentsPath)))}};p.lazyCompilation&&f&&"true"!==process.env.IS_BUILD?m(p.lazyCompilation)?Object.assign(P,k,p.lazyCompilation):Object.assign(P,k):P=!1;export const commonConfig={name:"client",target:"web",devtool:p.devtool,entry:j,mode:p.mode??"production",cache:C,snapshot:{immutablePaths:[a.pnpmNodeModules,a.denoNodeModules,r.node_modules],managedPaths:[a.pnpmNodeModules,a.denoNodeModules,r.node_modules],resolveBuildDependencies:{timestamp:!0,hash:!0},resolve:{timestamp:!0,hash:!0},module:{timestamp:!0,hash:!0},buildDependencies:{timestamp:!0,hash:!0},contextModule:{timestamp:!0,hash:!0}},stats:"errors-only",infrastructureLogging:{level:"error"},externalsPresets:p.externalsPresets,plugins:u,node:{global:!1,__filename:!1,__dirname:!1},experiments:{asyncWebAssembly:!0,cacheUnaffected:!0,lazyCompilation:P,buildHttp:m(p.buildHttp)?{allowedUris:[],lockfileLocation:s(a.httpCachePath,"http.lock"),cacheLocation:s(a.httpCachePath,"data"),upgrade:!0,...p.buildHttp}:p.buildHttp,backCompat:!0,futureDefaults:!0,css:!0,outputModule:!1,deferImport:!0},resolve:{extensions:[".mts",".mjs",".ts",".tsx",".js",".jsx",".json",".wasm"],alias:p.alias,modules:[a.nodeModules,a.pnpmNodeModules,a.denoNodeModules],mainFields:["browser","module","main"],mainFiles:["index"],plugins:p.resolvePlugins,preferAbsolute:!0,cache:!0,fallback:{}},externals:p.externals,output:outputConfig,recordsPath:p.recordsPath};p.overrideResolve&&commonConfig.resolve.plugins.push(new l(Object.assign({original:p.alias["@"],override:i&&c(i)},p.overrideResolve)));
package/lib/config.mjs CHANGED
@@ -1 +1 @@
1
- import{relative as e}from"node:path";import o from"node:process";import{merge as t}from"webpack-merge";import{CUSTOMCONFIG as a}from"./commom/custom-config.mjs";import n from"./commom/paths.mjs";import{join as s}from"./commom/posix.mjs";import r from"./commom/setup-env.mjs";import i from"./options/jsx-dom-expressions.mjs";import m from"./options/split-chunk.mjs";import{getConfigWithTypescript as l,isFunction as p,node_modules as c,resolveProgram as u}from"./utils/index.mjs";import{initDts as d}from"./vm/dts.mjs";import{APPTYPE as f,FRAMEWORK as h,frameworkVersion as g,isCI as v,isDev as x,isLibrary as j,isMobile as C,isReact as P,jsxImportSource as b,mainDirectory as k,NODE_ENV as w,PACKAGENAME as O}from"./process-env.mjs";let I=[/(app|vm|docs|example):[a-zA-Z_0-9]/,"@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 async function getConfig(e){let t=l(e).default;return(p(t)?await t(o):t)??{}}let S=await r(w,f,h,[],"true"===o.env.IS_BUILD,a),[y,M]=await Promise.all([getConfig(n.configPath),getConfig(n.customConfigPath)]),z={mode:w,strict:!1,devtool:"true"!==o.env.IS_BUILD&&x?"eval-cheap-module-source-map":"cheap-module-source-map",seo:!1,bundleAnalyzer:!1,polyfill:!1,entry:{},minifier:{},sourceMap:{filename:"[file].map",publicPath:"",namespace:O,moduleFilenameTemplate:"moneko://[namespace]/[resource-path]?[loaders]",fallbackModuleFilenameTemplate:"moneko://[namespace]/[resource-path]?[loaders]"},env:S,basename:"/",publicPath:"auto",rem:{designSize:C?375:1920},fallbackCompPath:null,modifyVars:{},prefixCls:"n",alias:Object.assign({"@":u(k)},P&&g<18?{"react/package.json":c("react/package.json"),"react/jsx-runtime":c("react/jsx-runtime.js"),"react/jsx-dev-runtime":c("react/jsx-dev-runtime.js")}:{}),moduleRules:[],prefixJsLoader:[],cssModules:[],cssModuleDefinition:!0,importOnDemand:{},proxy:{},devServer:{host:"localhost",port:3e3,open:!0},htmlPluginOption:{title:O.toLocaleUpperCase(),favicon:e(n.programPath,`${n.corePath}/options/favicon.ico`)},copy:{},routerMode:"browser",fixBrowserRouter:!1,plugins:[],resolvePlugins:[],overrideResolve:!1,splitChunk:m,runtimeChunk:"single",moduleFederation:[],rulesInclude:{css:I,js:I,media:I,font:I,wasm:[]},mdx:{jsx:!1,development:x,jsxImportSource:b,providerImportSource:`@moneko/${h}/mdx`},jsxDomExpressions:i,bar:{name:"Client",nameColor:"68",msgColor:"242",barBgColor:"15",barColor:"69",quiet:v},normalizeCss:!0,externalsPresets:{},buildHttp:void 0,virtualModule:{},cssExtract:{},externals:["@swc/core"],lazyCompilation:!1,performance:!1,refresh:"solid"!==h,bundleId:"com.moneko.bid",bundles:[],stylelint:{},eslint:{lintDirtyModulesOnly:!1},minChunkSize:1e3,compression:!1,manifest:{filename:"site.webmanifest"},corepack:!0,reactJsxRuntime:"automatic"};j&&(z.alias=Object.assign(z.alias,{"@pkg":n.componentsPath,[O]:n.componentsPath}));let D=z;if((!1===(D=t(D,y,M)).devtool||!1===D.sourceMap)&&(D.sourceMap=!1,D.devtool=!1),"true"===o.env.CODESPACES&&(D.devServer.https=!1),!1===D.devServer.https&&"darwin"===o.platform&&(D.devServer.open=!1),D.htmlPluginOption&&(D.htmlPluginOption.tags||(D.htmlPluginOption.tags=[]),D.fixBrowserRouter&&D.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))"}),D.manifest)){let e=D.manifest.publicPath??D.publicPath??"/";D.htmlPluginOption.tags.push({href:s("auto"===e?"/":e,D.manifest.filename),tag:"link",rel:"manifest"})}export const CONFIG=D;export const PUBLICPATH="auto"===CONFIG.publicPath?"":CONFIG.publicPath;d(CONFIG);
1
+ import{relative as e,sep as o}from"node:path";import t from"node:process";import{merge as a}from"webpack-merge";import{CUSTOMCONFIG as n}from"./commom/custom-config.mjs";import r from"./commom/paths.mjs";import{join as s}from"./commom/posix.mjs";import i from"./commom/setup-env.mjs";import m from"./options/jsx-dom-expressions.mjs";import l from"./options/split-chunk.mjs";import{getConfigWithTypescript as p,isFunction as c,node_modules as u,resolveProgram as d}from"./utils/index.mjs";import{initDts as f}from"./vm/dts.mjs";import{APPTYPE as h,FRAMEWORK as g,frameworkVersion as v,isCI as x,isDev as j,isLibrary as C,isMobile as P,isReact as b,jsxImportSource as k,mainDirectory as w,NODE_ENV as O,PACKAGENAME as I}from"./process-env.mjs";let S=[/(app|vm|docs|example):[a-zA-Z_0-9]/,"@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 async function getConfig(e){let o=p(e).default;return(c(o)?await o(t):o)??{}}let y=await i(O,h,g,[],"true"===t.env.IS_BUILD,n),[M,z]=await Promise.all([getConfig(r.configPath),getConfig(r.customConfigPath)]),D={mode:O,strict:!1,devtool:"true"!==t.env.IS_BUILD&&j?"eval-cheap-module-source-map":"cheap-module-source-map",seo:!1,bundleAnalyzer:!1,polyfill:!1,entry:{},minifier:{},sourceMap:{filename:"[file].map",publicPath:"",namespace:I,moduleFilenameTemplate:"moneko://[namespace]/[resource-path]?[loaders]",fallbackModuleFilenameTemplate:"moneko://[namespace]/[resource-path]?[loaders]"},env:y,basename:"/",publicPath:"auto",rem:{designSize:P?375:1920},fallbackCompPath:null,modifyVars:{},prefixCls:"n",alias:Object.assign({"@":d(w)},b&&v<18?{"react/package.json":u("react/package.json"),"react/jsx-runtime":u("react/jsx-runtime.js"),"react/jsx-dev-runtime":u("react/jsx-dev-runtime.js")}:{}),moduleRules:[],prefixJsLoader:[],cssModules:[],cssModuleDefinition:!0,importOnDemand:{},proxy:{},devServer:{host:"localhost",port:3e3,open:!0},htmlPluginOption:{title:I.toLocaleUpperCase(),favicon:e(r.programPath,`${r.corePath}/options/favicon.ico`)},copy:{},routerMode:"browser",fixBrowserRouter:!1,plugins:[],resolvePlugins:[],overrideResolve:!1,splitChunk:l,runtimeChunk:"single",moduleFederation:[],rulesInclude:{css:S,js:S,media:S,font:S,wasm:[]},mdx:{jsx:!1,development:j,jsxImportSource:k,providerImportSource:`@moneko/${g}/mdx`},jsxDomExpressions:m,bar:{name:"Client",nameColor:"68",msgColor:"242",barBgColor:"15",barColor:"69",quiet:x},normalizeCss:!0,externalsPresets:{},buildHttp:void 0,virtualModule:{},cssExtract:{},externals:["@swc/core"],lazyCompilation:!1,performance:!1,refresh:"solid"!==g,bundleId:"com.moneko.bid",bundles:[],stylelint:{},eslint:{lintDirtyModulesOnly:!1},minChunkSize:1e3,compression:!1,manifest:{filename:"site.webmanifest"},corepack:!0,reactJsxRuntime:"automatic"};C&&(D.alias=Object.assign(D.alias,{"@pkg":r.componentsPath,[I]:r.componentsPath}));let F=D;if((!1===(F=a(F,M,z)).devtool||!1===F.sourceMap)&&(F.sourceMap=!1,F.devtool=!1),"true"===t.env.CODESPACES&&(F.devServer.https=!1),!1===F.devServer.https&&"darwin"===t.platform&&(F.devServer.open=!1),F.htmlPluginOption&&(F.htmlPluginOption.tags||(F.htmlPluginOption.tags=[]),F.fixBrowserRouter&&F.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))"}),F.manifest)){let e=F.manifest.publicPath??F.publicPath??"/";F.htmlPluginOption.tags.push({href:s("auto"===e?"/":e,F.manifest.filename).replaceAll(o,"/"),tag:"link",rel:"manifest"})}export const CONFIG=F;export const PUBLICPATH="auto"===CONFIG.publicPath?"":CONFIG.publicPath;f(CONFIG);
@@ -1 +1 @@
1
- import{existsSync as t,readFileSync as e}from"node:fs";import{basename as s,resolve as i,sep as n}from"node:path";import o from"webpack";import{join as a}from"../commom/posix.mjs";export class HtmlPlugin{constructor(t={}){this.AddEntry=/(?:.*\/)?main\.[a-zA-Z0-9]+\.min\.js$/,this.faviconPath="",this.name="HtmlPlugin",this.cachedMetaTags=null,this.cachedCustomTags=null,this.options={title:"WebApp",filename:"index.html",inject:"head",...t}}getPublicPath(t){if("string"==typeof this.options.publicPath)return this.options.publicPath;let e=t.getAssetPath(t.outputOptions.publicPath,{hash:t.hash}),s="auto"===e?"/":e;return s.length&&!s.endsWith("/")&&(s+="/"),s}apply(h){h.hooks.compilation.tap(this.name,l=>{l.hooks.processAssets.tap({name:this.name,stage:o.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL},()=>{let r;if(this.options.favicon){let r=i(h.context,this.options.favicon);if(t(r)){let t=s(this.options.favicon),i=e(r);l.emitAsset(t,new o.sources.RawSource(i),{javascriptModule:!1});let h=this.getPublicPath(l);this.faviconPath=a(h,t).replaceAll(n,"/")}else l.warnings.push(new o.WebpackError(`Favicon file ${r} does not exist`))}if(r=this.options.templateContent?this.options.templateContent(this.options):this.options.template?e(i(h.context,this.options.template),{encoding:"utf-8"}):this.generateDefaultTemplate(),this.options.inject){let t=this.getAssets(l);r=this.injectAssets(r,t,this.options.inject)}let c="function"==typeof this.options.filename?this.options.filename("index"):this.options.filename||"index.html";l.emitAsset(c,new o.sources.RawSource(r),{javascriptModule:!1})})})}generateDefaultTemplate(){let t=this.generateMetaTags();return`<!DOCTYPE html><html><head><meta charset="utf-8">${t}<title>${this.options.title}</title><link rel="icon" type="image/x-icon" href="${this.faviconPath}"></head><body><div id="root"></div></body></html>`}generateMetaTags(){if(null!==this.cachedMetaTags)return this.cachedMetaTags;if(!this.options.meta)return this.cachedMetaTags="","";let t=Object.entries(this.options.meta).map(([t,e])=>{if("string"==typeof e)return`<meta name="${t}" content="${e}">`;if(void 0===e)return"";let s=Object.entries(e).map(([t,e])=>`${t}="${e}"`).join(" ");return`<meta ${s}>`}).join("");return this.cachedMetaTags=t,t}generateCustomTags(){if(null!==this.cachedCustomTags)return this.cachedCustomTags;let t={head:"",body:""};if(!this.options.tags)return this.cachedCustomTags=t,t;let e=[],s=[];return this.options.tags.forEach(t=>{let{tag:i="script",textContent:n="",inject:o=this.options.inject,...a}=t,h=Object.entries(a).filter(([,t])=>null!=t).map(([t,e])=>!0===e?t:`${t}="${e}"`).join(" "),l=`<${i} ${h}>${n}</${i}>`;"head"===o?e.push(l):s.push(l)}),t.head=e.join(""),t.body=s.join(""),this.cachedCustomTags=t,t}getAssets(t){let e={js:[],css:[]},s=["import-scripts","require","async-node"],i=this.getPublicPath(t);for(let o of t.entrypoints.values())for(let t of o.chunks){let o=t.getEntryOptions(),h=o?.chunkLoading;if(!(o?.asyncChunks||h&&s.includes(h)))for(let s of t.files)s.endsWith(".js")?e.js.push(a(i,s).replaceAll(n,"/")):s.endsWith(".css")&&e.css.push(a(i,s).replaceAll(n,"/"))}return e}injectAssets(t,e,s){let i=e.css.length?e.css.map(t=>`<link href="${t}" rel="stylesheet" />`).join(""):"",n=e.js.length?e.js.map(t=>`<script defer ${this.AddEntry.test(t)?'entry="true" ':""}src="${t}"></script>`).join(""):"",o=this.generateCustomTags(),a=t.split("</head>");if(2===a.length){let[t,e]=a,h=e.split("</body>");return"head"===s?`${t}${i}${n}${o.head}</head>${h[0]}${o.body}</body>${h[1]||""}`:`${t}${o.head}</head>${h[0]}${i}${n}${o.body}</body>${h[1]||""}`}return t}}
1
+ import{existsSync as t,readFileSync as e}from"node:fs";import{basename as s,resolve as i,sep as n}from"node:path";import o from"webpack";import{join as a}from"../commom/posix.mjs";export class HtmlPlugin{constructor(t={}){this.AddEntry=/(?:.*\/)?main\.[a-zA-Z0-9]+\.entry\.js$/,this.faviconPath="",this.name="HtmlPlugin",this.cachedMetaTags=null,this.cachedCustomTags=null,this.options={title:"WebApp",filename:"index.html",inject:"head",...t}}getPublicPath(t){if("string"==typeof this.options.publicPath)return this.options.publicPath;let e=t.getAssetPath(t.outputOptions.publicPath,{hash:t.hash}),s="auto"===e?"/":e;return s.length&&!s.endsWith("/")&&(s+="/"),s}apply(h){h.hooks.compilation.tap(this.name,l=>{l.hooks.processAssets.tap({name:this.name,stage:o.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL},()=>{let r;if(this.options.favicon){let r=i(h.context,this.options.favicon);if(t(r)){let t=s(this.options.favicon),i=e(r);l.emitAsset(t,new o.sources.RawSource(i),{javascriptModule:!1});let h=this.getPublicPath(l);this.faviconPath=a(h,t).replaceAll(n,"/")}else l.warnings.push(new o.WebpackError(`Favicon file ${r} does not exist`))}if(r=this.options.templateContent?this.options.templateContent(this.options):this.options.template?e(i(h.context,this.options.template),{encoding:"utf-8"}):this.generateDefaultTemplate(),this.options.inject){let t=this.getAssets(l);r=this.injectAssets(r,t,this.options.inject)}let c="function"==typeof this.options.filename?this.options.filename("index"):this.options.filename||"index.html";l.emitAsset(c,new o.sources.RawSource(r),{javascriptModule:!1})})})}generateDefaultTemplate(){let t=this.generateMetaTags();return`<!DOCTYPE html><html><head><meta charset="utf-8">${t}<title>${this.options.title}</title><link rel="icon" type="image/x-icon" href="${this.faviconPath}"></head><body><div id="root"></div></body></html>`}generateMetaTags(){if(null!==this.cachedMetaTags)return this.cachedMetaTags;if(!this.options.meta)return this.cachedMetaTags="","";let t=Object.entries(this.options.meta).map(([t,e])=>{if("string"==typeof e)return`<meta name="${t}" content="${e}">`;if(void 0===e)return"";let s=Object.entries(e).map(([t,e])=>`${t}="${e}"`).join(" ");return`<meta ${s}>`}).join("");return this.cachedMetaTags=t,t}generateCustomTags(){if(null!==this.cachedCustomTags)return this.cachedCustomTags;let t={head:"",body:""};if(!this.options.tags)return this.cachedCustomTags=t,t;let e=[],s=[];return this.options.tags.forEach(t=>{let{tag:i="script",textContent:n="",inject:o=this.options.inject,...a}=t,h=Object.entries(a).filter(([,t])=>null!=t).map(([t,e])=>!0===e?t:`${t}="${e}"`).join(" "),l=`<${i} ${h}>${n}</${i}>`;"head"===o?e.push(l):s.push(l)}),t.head=e.join(""),t.body=s.join(""),this.cachedCustomTags=t,t}getAssets(t){let e={js:[],css:[]},s=["import-scripts","require","async-node"],i=this.getPublicPath(t);for(let o of t.entrypoints.values())for(let t of o.chunks){let o=t.getEntryOptions(),h=o?.chunkLoading;if(!(o?.asyncChunks||h&&s.includes(h)))for(let s of t.files)s.endsWith(".js")?e.js.push(a(i,s).replaceAll(n,"/")):s.endsWith(".css")&&e.css.push(a(i,s).replaceAll(n,"/"))}return e}injectAssets(t,e,s){let i=e.css.length?e.css.map(t=>`<link href="${t}" rel="stylesheet" />`).join(""):"",n=e.js.length?e.js.map(t=>`<script defer ${this.AddEntry.test(t)?'entry="true" ':""}src="${t}"></script>`).join(""):"",o=this.generateCustomTags(),a=t.split("</head>");if(2===a.length){let[t,e]=a,h=e.split("</body>");return"head"===s?`${t}${i}${n}${o.head}</head>${h[0]}${o.body}</body>${h[1]||""}`:`${t}${o.head}</head>${h[0]}${i}${n}${o.body}</body>${h[1]||""}`}return t}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moneko/core",
3
- "version": "4.6.2",
3
+ "version": "4.6.4",
4
4
  "description": "core",
5
5
  "main": "lib/index.mjs",
6
6
  "type": "module",