@flatjs/evolve 3.0.15 → 3.1.0-next.1

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.
Files changed (33) hide show
  1. package/README.md +0 -6
  2. package/dist/compiler/create-build-server-compiler.js +1 -1
  3. package/dist/core/rspack/create-plugins.js +1 -1
  4. package/dist/core/rspack/create-rspack-rule-sets.js +1 -1
  5. package/dist/default-options.js +1 -1
  6. package/dist/dev-server/middlewares/get-page-module-html.js +1 -1
  7. package/dist/helpers/assert-multi-html-cdn.d.ts +2 -0
  8. package/dist/helpers/assert-multi-html-cdn.js +1 -0
  9. package/dist/helpers/index.d.ts +1 -0
  10. package/dist/helpers/index.js +1 -1
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.js +1 -1
  13. package/dist/load-config/load-evolve-config.js +1 -1
  14. package/dist/main/create-thread-worker.js +1 -1
  15. package/dist/main/prepare-build.js +1 -1
  16. package/dist/plugins/rspack/circular-dependency-plugin/index.js +1 -1
  17. package/dist/plugins/rspack/module-federation/index.js +1 -1
  18. package/dist/plugins/rspack/multi-html/index.js +1 -1
  19. package/dist/plugins/rspack/multi-html/multi-html-cdn-rspack-plugin.d.ts +1 -1
  20. package/dist/plugins/rspack/multi-html/multi-html-cdn-rspack-plugin.js +1 -1
  21. package/dist/plugins/rspack/multi-html/multi-html-rspack-plugin.js +1 -1
  22. package/dist/plugins/rspack/progress-plugin/index.d.ts +2 -3
  23. package/dist/plugins/webpack/circular-dependency/circular-dependency-webpack-plugin.js +1 -1
  24. package/dist/plugins/webpack/clean-webpack/clean-webpack-plugin.js +1 -1
  25. package/dist/plugins/webpack/module-federation/index.d.ts +2 -2
  26. package/dist/plugins/webpack/module-federation/index.js +1 -1
  27. package/dist/plugins/webpack/multi-html/index.js +1 -1
  28. package/dist/plugins/webpack/multi-html/multi-html-cdn-webpack-plugin.js +1 -1
  29. package/dist/plugins/webpack/multi-html/multi-html-webpack-plugins.js +1 -1
  30. package/dist/rules/rspack/rule-scripts.d.ts +11 -1
  31. package/dist/rules/rspack/rule-scripts.js +1 -1
  32. package/dist/types/types-options.d.ts +7 -1
  33. package/package.json +63 -62
package/README.md CHANGED
@@ -1,11 +1,5 @@
1
1
  # @flatjs/evolve
2
2
 
3
- ## Note: because below configuration of `tsconfig.json `
4
-
5
- ```json
6
- { "baseUrl": "./src" }
7
- ```
8
-
9
3
  We should not create folder name like `webpack` in `src/webpack`;
10
4
 
11
5
  1. while we use `import { moduleX } from webpack`; it will resolve `moduleX` from `src/webpack` instead import from `node_modules`
@@ -1 +1 @@
1
- import webpack from"webpack";import{ensureSlash,mergeOptions}from"@flatjs/common";import{ignoreEntryOptionKeys}from"../constants.js";import{loadWebpackConfig}from"../core/webpack/load-webpack-config.js";import{EvolveBuildError}from"../errors/evolve-build-error.js";import{assertSingleWebpackCompiler}from"../helpers/assert-single-compiler.js";import{printCompilerError}from"../helpers/print-log.js";import{verifyGroupEntryOptions}from"../helpers/verify-group-entry-options.js";export const createBuildServerCompiler=async(r,o,e)=>{const t=Object.values(r)[0];if(!verifyGroupEntryOptions(r,ignoreEntryOptionKeys,!0))throw new Error("The entry options in a group must be the same.");const i=o.multiHtmlCdn?.prod||[];if(!i.length)throw new Error(`No CDN config for env:"prod", groupName: ${t.groupName}`);const n=ensureSlash(i[Math.floor(Math.random()*i.length)],!0);try{const i=t.options?.useRelativeAssetPath,p=mergeOptions(o,{webpack:{publicPath:i?"auto":n}}),s=await loadWebpackConfig("production",r,p,e),a=assertSingleWebpackCompiler(r,s,p,!1);return webpack(a)}catch(r){const o=printCompilerError(r);throw new EvolveBuildError("BUILD_ERROR",o)}};
1
+ import webpack from"webpack";import{ensureSlash,mergeOptions}from"@flatjs/common";import{ignoreEntryOptionKeys}from"../constants.js";import{loadWebpackConfig}from"../core/webpack/load-webpack-config.js";import{EvolveBuildError}from"../errors/evolve-build-error.js";import{assertMultiHtmlCdn}from"../helpers/assert-multi-html-cdn.js";import{assertSingleWebpackCompiler}from"../helpers/assert-single-compiler.js";import{printCompilerError}from"../helpers/print-log.js";import{verifyGroupEntryOptions}from"../helpers/verify-group-entry-options.js";export const createBuildServerCompiler=async(r,o,e)=>{const t=Object.values(r)[0];if(!verifyGroupEntryOptions(r,ignoreEntryOptionKeys,!0))throw new Error("The entry options in a group must be the same.");const s=assertMultiHtmlCdn(o)?.prod||[];if(!s.length)throw new Error(`No CDN config for env:"prod", groupName: ${t.groupName}`);const i=ensureSlash(s[Math.floor(Math.random()*s.length)],!0);try{const s=t.options?.useRelativeAssetPath,n=mergeOptions(o,{webpack:{publicPath:s?"auto":i}}),p=await loadWebpackConfig("production",r,n,e),a=assertSingleWebpackCompiler(r,p,n,!1);return webpack(a)}catch(r){const o=printCompilerError(r);throw new EvolveBuildError("BUILD_ERROR",o)}};
@@ -1 +1 @@
1
- import CaseSensitivePathsPlugin from"case-sensitive-paths-webpack-plugin";import{logger}from"@flatjs/common";import{RsdoctorRspackPlugin}from"@rsdoctor/rspack-plugin";import rspack from"@rspack/core";import ReactRefreshPlugin from"@rspack/plugin-react-refresh";import{assertChunkFilename}from"../../helpers/assert-chunk-filename.js";import{enableBundleHashNameForModule}from"../../helpers/enable-bundle-hashname-for-module.js";import{getBundleFileName}from"../../helpers/get-bundle-file-name.js";import{shouldEnableReactFastRefresh}from"../../helpers/should-enable-react-fast-refresh.js";import{createCircularDependencyRspackPlugins}from"../../plugins/rspack/circular-dependency-plugin/index.js";import{createBuiltinDefineVariablesRspackPlugins}from"../../plugins/rspack/define-variable/index.js";import{createModuleFederationRspackPlugins}from"../../plugins/rspack/module-federation/index.js";import{createHtmlRspackPlugins}from"../../plugins/rspack/multi-html/index.js";import{createProgressRspackPlugins}from"../../plugins/rspack/progress-plugin/index.js";import{createCleanWebpackPlugins}from"../../plugins/webpack/clean-webpack/index.js";import{createCodeCheckerWebpackPlugins}from"../../plugins/webpack/code-checker/index.js";import{createStatsWebpackPlugins}from"../../plugins/webpack/stats-webpack/index.js";export const createRspackPlugins=async(e,s,a,r)=>{const n=s[0],[i,l]=n,c=enableBundleHashNameForModule(a,l?.options),o=[...createProgressRspackPlugins(e,s),new rspack.IgnorePlugin({resourceRegExp:/\.d\.[cm]ts$/}),new CaseSensitivePathsPlugin,...createCircularDependencyRspackPlugins(e,a),new rspack.CssExtractRspackPlugin({filename:`[name]/${getBundleFileName("css",e,c)}`,chunkFilename:assertChunkFilename(a,n,"css")}),...await createBuiltinDefineVariablesRspackPlugins(e,a),...createCleanWebpackPlugins(e,s,a),...createModuleFederationRspackPlugins(e,s,a),...await createHtmlRspackPlugins(e,s,a),...createStatsWebpackPlugins(e,a,r),...createCodeCheckerWebpackPlugins(e,a)],t=shouldEnableReactFastRefresh(e,n,a);t&&o.push(new ReactRefreshPlugin({overlay:!1,exclude:[/node_modules/]})),!t&&e&&(a.devServer?.liveReload?logger.warn('The HMR disabled cause of "liveReload" specificed'):logger.warn(`The HMR disabled cause of \`"moduleFederation":"${i}"\``)),a.openRsdoctor&&o.push(new RsdoctorRspackPlugin);const p=a.webpack?.plugins||[];return o.concat(p)};
1
+ import CaseSensitivePathsPlugin from"case-sensitive-paths-webpack-plugin";import{logger}from"@flatjs/common";import{RsdoctorRspackPlugin}from"@rsdoctor/rspack-plugin";import rspack from"@rspack/core";import{ReactRefreshRspackPlugin}from"@rspack/plugin-react-refresh";import{assertChunkFilename}from"../../helpers/assert-chunk-filename.js";import{enableBundleHashNameForModule}from"../../helpers/enable-bundle-hashname-for-module.js";import{getBundleFileName}from"../../helpers/get-bundle-file-name.js";import{shouldEnableReactFastRefresh}from"../../helpers/should-enable-react-fast-refresh.js";import{createCircularDependencyRspackPlugins}from"../../plugins/rspack/circular-dependency-plugin/index.js";import{createBuiltinDefineVariablesRspackPlugins}from"../../plugins/rspack/define-variable/index.js";import{createModuleFederationRspackPlugins}from"../../plugins/rspack/module-federation/index.js";import{createHtmlRspackPlugins}from"../../plugins/rspack/multi-html/index.js";import{createProgressRspackPlugins}from"../../plugins/rspack/progress-plugin/index.js";import{createCleanWebpackPlugins}from"../../plugins/webpack/clean-webpack/index.js";import{createCodeCheckerWebpackPlugins}from"../../plugins/webpack/code-checker/index.js";import{createStatsWebpackPlugins}from"../../plugins/webpack/stats-webpack/index.js";export const createRspackPlugins=async(e,s,a,r)=>{const n=s[0],[i,c]=n,l=enableBundleHashNameForModule(a,c?.options),t=[...createProgressRspackPlugins(e,s),new rspack.IgnorePlugin({resourceRegExp:/\.d\.[cm]ts$/}),new CaseSensitivePathsPlugin,...createCircularDependencyRspackPlugins(e,a),new rspack.CssExtractRspackPlugin({filename:`[name]/${getBundleFileName("css",e,l)}`,chunkFilename:assertChunkFilename(a,n,"css")}),...await createBuiltinDefineVariablesRspackPlugins(e,a),...createCleanWebpackPlugins(e,s,a),...createModuleFederationRspackPlugins(e,s,a),...await createHtmlRspackPlugins(e,s,a),...createStatsWebpackPlugins(e,a,r),...createCodeCheckerWebpackPlugins(e,a)],o=shouldEnableReactFastRefresh(e,n,a);o&&t.push(new ReactRefreshRspackPlugin({exclude:[/node_modules/]})),!o&&e&&(a.devServer?.liveReload?logger.warn('The HMR disabled cause of "liveReload" specificed'):logger.warn(`The HMR disabled cause of \`"moduleFederation":"${i}"\``)),a.openRsdoctor&&t.push(new RsdoctorRspackPlugin);const p=a.webpack?.plugins||[];return t.concat(p)};
@@ -1 +1 @@
1
- import{rspackRuleAssets,rspackRuleCss,rspackRuleLess,rspackRuleScripts,rspackRuleSvgIcon}from"../../rules/index.js";export const createRspackRuleSets=(s,e,c)=>{const r=e[0],p=[rspackRuleSvgIcon(),rspackRuleAssets(e,c),rspackRuleCss(s,r,c,!1),rspackRuleCss(s,r,c,!0),rspackRuleLess(s,r,c),rspackRuleScripts(s,r,c)],a=c.webpack?.ruleSets||[];return p.concat(a)};
1
+ import{rspackRuleAssets,rspackRuleCss,rspackRuleLess,rspackRuleScripts,rspackRuleSvgIcon}from"../../rules/index.js";export const createRspackRuleSets=(s,e,c)=>{const r=e[0],p=[rspackRuleSvgIcon(),rspackRuleAssets(e,c),rspackRuleCss(s,r,c,!1),rspackRuleCss(s,r,c,!0),rspackRuleLess(s,r,c),...rspackRuleScripts(s,r,c)],a=c.webpack?.ruleSets||[];return p.concat(a)};
@@ -1 +1 @@
1
- export const defaultEvolveOptions={projectCwd:process.cwd(),projectVirtualPath:"flatjs/evolve",routeBaseName:"/pages",rejectWarnings:!1,devServer:{autoOpen:!0,mockOptions:{mockBaseDir:"mocks"},clientOverlay:{errors:!0,warnings:!1},webSocketURL:"localIp",middlewares:[],watchOptions:{poll:1e3,ignored:["**/node_modules","**/mocks"],aggregateTimeout:500},defaultServeGlobalData:()=>Promise.resolve({}),bundleDirResolver:e=>e},webpack:{target:["web","es5"],plugins:[],ruleSets:[],publicPath:"auto",resolve:{},externals:{},outputDir:"public",enableBundleHashName:!0},pluginOptions:{},loaderOptions:{assetDataUrlMaxSize:4096,babelOptions:{usePreset:"react",plugins:[],presets:[]},lessOptions:{},postcssOptions:{cssnanoOptions:{}},pixelOptions:{rootValue:{px:100,rpx:1},outputUnit:"rem"},modularImports:[]},globalCompilerOptions:{runTsChecker:!0},entryMap:{},multiHtmlCdn:{},multiHtmlCdnEnvResolver:function cdnResolver(){},needVerifyPackages:{},packageInstallChecker:{enabled:!1,detectModules:["@dimjs/*"],throwError:!1,showAllInstalledGraph:!0},ci:{basedBranch:"origin/master"},isolation:!1,maxEntryGroupSize:10,compiler:"webpack",openRsdoctor:!1,inspector:{keys:["$mod","i"],customLaunchEditorEndpoint:"/__hps_inspector",trustedEditor:"code",injectClient:!0}};
1
+ export const defaultEvolveOptions={projectCwd:process.cwd(),projectVirtualPath:"flatjs/evolve",routeBaseName:"/pages",rejectWarnings:!1,channel:"default",devServer:{autoOpen:!0,mockOptions:{mockBaseDir:"mocks"},clientOverlay:{errors:!0,warnings:!1},webSocketURL:"localIp",middlewares:[],watchOptions:{poll:1e3,ignored:["**/node_modules","**/mocks"],aggregateTimeout:500},defaultServeGlobalData:()=>Promise.resolve({}),bundleDirResolver:e=>e},webpack:{target:["web","es5"],plugins:[],ruleSets:[],publicPath:"auto",resolve:{},externals:{},outputDir:"public",enableBundleHashName:!0},pluginOptions:{},loaderOptions:{assetDataUrlMaxSize:4096,babelOptions:{usePreset:"react",plugins:[],presets:[]},lessOptions:{},postcssOptions:{cssnanoOptions:{}},pixelOptions:{rootValue:{px:100,rpx:1},outputUnit:"rem"},modularImports:[]},globalCompilerOptions:{runTsChecker:!0},entryMap:{},multiHtmlCdn:{},multiHtmlCdnEnvResolver:function cdnResolver(){},needVerifyPackages:{},packageInstallChecker:{enabled:!1,detectModules:["@dimjs/*"],throwError:!1,showAllInstalledGraph:!0},ci:{basedBranch:"origin/master"},isolation:!1,maxEntryGroupSize:10,compiler:"webpack",openRsdoctor:!1,inspector:{keys:["$mod","i"],customLaunchEditorEndpoint:"/__hps_inspector",trustedEditor:"code",injectClient:!0}};
@@ -1 +1 @@
1
- import{existsSync,readFileSync}from"node:fs";import{isAbsolute,join}from"node:path";import{ensureSlash,urlJoin}from"@flatjs/common";import{parseTemplate}from"@hyperse/html-webpack-plugin-loader";import{envVariablesName}from"../../constants.js";import{allowPx2remForModule}from"../../helpers/allow-px2rem-for-module.js";import{checkHtmlTemplateOptions}from"../../helpers/check-html-template-options.js";import{getHtmlMaxOrder,getHtmlMinOrder}from"../../helpers/get-html-max-order.js";import{getHtmlPluginConfig}from"../../helpers/get-html-plugin-config.js";import{getPackageDir}from"../../helpers/get-pacakge-dir.js";import{getRuntimeCDNBase}from"../../helpers/get-runtime-cdn-base.js";import{loadEnvConfig}from"../../helpers/load-env-config.js";import{normalizeEvolveEntryName}from"../../helpers/normalize-entry-map.js";import{normalizePageProxy}from"../../helpers/normalize-page-proxy.js";import{normalizeTemplateInjectTokens}from"../../helpers/normalize-template-inject-tokens.js";import{injectFederationScripts}from"../../helpers/script-injects.js";import{ErrorModuleParser}from"./error-module-parser.js";import{getBundleAsset}from"./get-bundle-asset.js";import{getDevServerHostUri}from"./get-dev-server-host-uri.js";import{getHmrRuntimeChunks}from"./get-hmr-runtime-chunks.js";import{getNormalizedEntryName}from"./get-normalized-entry-name.js";export const getPageModuleHtml=async(e,t,r,o,n)=>{const{entryMap:s,projectVirtualPath:i}=n,a=Object.keys(s).sort((e,t)=>t.length-e.length),l=getPackageDir(),m=a.find(e=>{const r=normalizeEvolveEntryName(e,i);return ensureSlash(t.path.replace(/^\//,""),!0).startsWith(ensureSlash(r,!0))});if(!m){const e=readFileSync(join(l,"./templates/module-404.html"),"utf-8");return new ErrorModuleParser(e,{title:"404 Not Found",errorMeta:[{name:"@flatjs/evolve workspace",value:l},{name:"served entry names",value:JSON.stringify(a)},{name:"module path",value:`${t.path}`}]}).serialize()}const p=s[m],d=p.options,u=getDevServerHostUri(e,m,r),c=d?.templatePath||"./templates/module.html",g=join(n.projectCwd,"./templates/module.html"),h=readFileSync(isAbsolute(c)?c:existsSync(g)?g:join(l,"./templates/module.html"),"utf-8"),f=n.devServer,v=f?.defaultServeGlobalData?await f.defaultServeGlobalData(p,r):{},j={mode:"development",envCdn:urlJoin(r,["public"])},y=getNormalizedEntryName(m,i,e,f),S=normalizePageProxy(n.routeBaseName||"/pages"),H=normalizeTemplateInjectTokens(j,d);checkHtmlTemplateOptions(H);const N=parseTemplate(h);N.upsertTitleTag(getHtmlPluginConfig("title",j,d?.title));const M=H.favicon;M&&N.upsertFaviconTag(M.href,M.rel,M.attributes);const P=H.headMetaTags||[];N.upsertHeadMetaTags(P);const b=H.headStyles||[],w=getHtmlMaxOrder(b),k=getBundleAsset(u,y,".css");b.push({id:k,href:k,position:"end",order:w+1}),N.upsertHeadStyles(b);const C=H.headScripts||[],x=getHtmlMinOrder(C);getHmrRuntimeChunks(e,m,y,p,n,u).forEach(e=>{C.unshift({id:e,src:e,position:"end",order:x-1})}),N.upsertHeadScripts(C);const z=H.headInlineScripts||[],O=getHtmlMaxOrder(z),E=getHtmlMinOrder(z),T=Math.min(E,x),B=await loadEnvConfig("me",n)||{};z.push({id:"envVariables",content:`window.${envVariablesName}=${JSON.stringify({env:"me",appName:n.projectVirtualPath,routeBaseName:n.routeBaseName,projectVirtualPath:i,moduleName:m.replace(i,"").replace(/^\//,""),...B})}`,position:"beginning",order:-99});const D={hostUrl:r,apiBase:urlJoin(r,[o]),virtualPath:join(S,i),moduleName:m.replace(i,"").replace(/^\//,""),...v,...d?.serveGlobalData||{}};z.push({id:"globalData",content:`window.GLOBAL=${JSON.stringify(D)}`,position:"end",order:T-2}),allowPx2remForModule([m,p],n)&&z.push({id:"viewport",content:getHtmlPluginConfig("viewport",j,d?.viewport),position:"end",order:E-1});const F=getRuntimeCDNBase(n.multiHtmlCdn,n.multiHtmlCdnEnvResolver||function cdnResolver(){});z.push({id:"flatjsMultiCdn",content:F,position:"end",order:O+1});const J=injectFederationScripts({me:[urlJoin(r,["public"])]},n.multiHtmlCdnEnvResolver);z.push({id:"evolveFetchMicroWidgets",content:J,position:"end",order:O+2}),N.upsertHeadInlineScripts(z);const R=H.headInlineStyles||[];N.upsertHeadInlineStyles(R);const A=H.bodyScripts||[],I=getHtmlMaxOrder(A),V=getBundleAsset(u,y,".js");return A.push({id:V,src:V,position:"end",order:I+1}),N.upsertBodyScripts(A),N.serialize()};
1
+ import{existsSync,readFileSync}from"node:fs";import{isAbsolute,join}from"node:path";import{ensureSlash,urlJoin}from"@flatjs/common";import{parseTemplate}from"@hyperse/html-webpack-plugin-loader";import{envVariablesName}from"../../constants.js";import{allowPx2remForModule}from"../../helpers/allow-px2rem-for-module.js";import{assertMultiHtmlCdn}from"../../helpers/assert-multi-html-cdn.js";import{checkHtmlTemplateOptions}from"../../helpers/check-html-template-options.js";import{getHtmlMaxOrder,getHtmlMinOrder}from"../../helpers/get-html-max-order.js";import{getHtmlPluginConfig}from"../../helpers/get-html-plugin-config.js";import{getPackageDir}from"../../helpers/get-pacakge-dir.js";import{getRuntimeCDNBase}from"../../helpers/get-runtime-cdn-base.js";import{loadEnvConfig}from"../../helpers/load-env-config.js";import{normalizeEvolveEntryName}from"../../helpers/normalize-entry-map.js";import{normalizePageProxy}from"../../helpers/normalize-page-proxy.js";import{normalizeTemplateInjectTokens}from"../../helpers/normalize-template-inject-tokens.js";import{injectFederationScripts}from"../../helpers/script-injects.js";import{ErrorModuleParser}from"./error-module-parser.js";import{getBundleAsset}from"./get-bundle-asset.js";import{getDevServerHostUri}from"./get-dev-server-host-uri.js";import{getHmrRuntimeChunks}from"./get-hmr-runtime-chunks.js";import{getNormalizedEntryName}from"./get-normalized-entry-name.js";export const getPageModuleHtml=async(e,t,r,o,n)=>{const{entryMap:s,projectVirtualPath:i}=n,a=Object.keys(s).sort((e,t)=>t.length-e.length),l=getPackageDir(),m=a.find(e=>{const r=normalizeEvolveEntryName(e,i);return ensureSlash(t.path.replace(/^\//,""),!0).startsWith(ensureSlash(r,!0))});if(!m){const e=readFileSync(join(l,"./templates/module-404.html"),"utf-8");return new ErrorModuleParser(e,{title:"404 Not Found",errorMeta:[{name:"@flatjs/evolve workspace",value:l},{name:"served entry names",value:JSON.stringify(a)},{name:"module path",value:`${t.path}`}]}).serialize()}const p=s[m],d=p.options,u=getDevServerHostUri(e,m,r),c=d?.templatePath||"./templates/module.html",g=join(n.projectCwd,"./templates/module.html"),h=readFileSync(isAbsolute(c)?c:existsSync(g)?g:join(l,"./templates/module.html"),"utf-8"),f=n.devServer,v=f?.defaultServeGlobalData?await f.defaultServeGlobalData(p,r):{},j={mode:"development",envCdn:urlJoin(r,["public"])},y=getNormalizedEntryName(m,i,e,f),S=normalizePageProxy(n.routeBaseName||"/pages"),H=normalizeTemplateInjectTokens(j,d);checkHtmlTemplateOptions(H);const M=parseTemplate(h);M.upsertTitleTag(getHtmlPluginConfig("title",j,d?.title));const N=H.favicon;N&&M.upsertFaviconTag(N.href,N.rel,N.attributes);const P=H.headMetaTags||[];M.upsertHeadMetaTags(P);const b=H.headStyles||[],w=getHtmlMaxOrder(b),C=getBundleAsset(u,y,".css");b.push({id:C,href:C,position:"end",order:w+1}),M.upsertHeadStyles(b);const k=H.headScripts||[],x=getHtmlMinOrder(k);getHmrRuntimeChunks(e,m,y,p,n,u).forEach(e=>{k.unshift({id:e,src:e,position:"end",order:x-1})}),M.upsertHeadScripts(k);const z=H.headInlineScripts||[],O=getHtmlMaxOrder(z),E=getHtmlMinOrder(z),T=Math.min(E,x),B=await loadEnvConfig("me",n)||{};z.push({id:"envVariables",content:`window.${envVariablesName}=${JSON.stringify({env:"me",appName:n.projectVirtualPath,routeBaseName:n.routeBaseName,projectVirtualPath:i,moduleName:m.replace(i,"").replace(/^\//,""),...B})}`,position:"beginning",order:-99});const D={hostUrl:r,apiBase:urlJoin(r,[o]),virtualPath:join(S,i),moduleName:m.replace(i,"").replace(/^\//,""),...v,...d?.serveGlobalData||{}};z.push({id:"globalData",content:`window.GLOBAL=${JSON.stringify(D)}`,position:"end",order:T-2}),allowPx2remForModule([m,p],n)&&z.push({id:"viewport",content:getHtmlPluginConfig("viewport",j,d?.viewport),position:"end",order:E-1});const F=getRuntimeCDNBase(assertMultiHtmlCdn(n),n.multiHtmlCdnEnvResolver||function cdnResolver(){});z.push({id:"flatjsMultiCdn",content:F,position:"end",order:O+1});const J=injectFederationScripts({me:[urlJoin(r,["public"])]},n.multiHtmlCdnEnvResolver);z.push({id:"evolveFetchMicroWidgets",content:J,position:"end",order:O+2}),M.upsertHeadInlineScripts(z);const R=H.headInlineStyles||[];M.upsertHeadInlineStyles(R);const A=H.bodyScripts||[],I=getHtmlMaxOrder(A),V=getBundleAsset(u,y,".js");return A.push({id:V,src:V,position:"end",order:I+1}),M.upsertBodyScripts(A),M.serialize()};
@@ -0,0 +1,2 @@
1
+ import type { FlatEvolveOptions } from '../types/types-options.js';
2
+ export declare const assertMultiHtmlCdn: (evolveOptions: FlatEvolveOptions) => import("../types/types-multi-html.js").EvolveMultiCDNConfig;
@@ -0,0 +1 @@
1
+ export const assertMultiHtmlCdn=t=>{const{multiHtmlCdn:n,channel:e="default"}=t;return"function"==typeof n?n(e):n};
@@ -1,5 +1,6 @@
1
1
  export * from './allow-px2rem-for-module.js';
2
2
  export * from './assert-group-entry-item.js';
3
+ export * from './assert-multi-html-cdn.js';
3
4
  export * from './assert-single-compiler.js';
4
5
  export * from './check-runtime-env.js';
5
6
  export * from './chunk-entry-map.js';
@@ -1 +1 @@
1
- export*from"./allow-px2rem-for-module.js";export*from"./assert-group-entry-item.js";export*from"./assert-single-compiler.js";export*from"./check-runtime-env.js";export*from"./chunk-entry-map.js";export*from"./custom-listr-renderer.js";export*from"./delete-object-keys.js";export*from"./enable-bundle-hashname-for-module.js";export*from"./flat-entry-map.js";export*from"./format-spinner-text.js";export*from"./get-bundle-file-name.js";export*from"./get-html-plugin-config.js";export*from"./get-pacakge-dir.js";export*from"./get-runtime-cdn-base.js";export*from"./get-stats-file-name.js";export*from"./is-deep-equal.js";export*from"./json-serializer.js";export*from"./merge-babel-options.js";export*from"./normalize-check-entry-options.js";export*from"./normalize-entry-map.js";export*from"./normalize-group-name.js";export*from"./normalize-page-proxy.js";export*from"./normalize-resolve-alias.js";export*from"./normalize-template-inject-tokens.js";export*from"./open-page.js";export*from"./print-log.js";export*from"./refresh-evolve-mock-options.js";export*from"./script-injects.js";export*from"./should-enable-react-fast-refresh.js";export*from"./split-to-entry-group.js";export*from"./verify-group-entry-options.js";
1
+ export*from"./allow-px2rem-for-module.js";export*from"./assert-group-entry-item.js";export*from"./assert-multi-html-cdn.js";export*from"./assert-single-compiler.js";export*from"./check-runtime-env.js";export*from"./chunk-entry-map.js";export*from"./custom-listr-renderer.js";export*from"./delete-object-keys.js";export*from"./enable-bundle-hashname-for-module.js";export*from"./flat-entry-map.js";export*from"./format-spinner-text.js";export*from"./get-bundle-file-name.js";export*from"./get-html-plugin-config.js";export*from"./get-pacakge-dir.js";export*from"./get-runtime-cdn-base.js";export*from"./get-stats-file-name.js";export*from"./is-deep-equal.js";export*from"./json-serializer.js";export*from"./merge-babel-options.js";export*from"./normalize-check-entry-options.js";export*from"./normalize-entry-map.js";export*from"./normalize-group-name.js";export*from"./normalize-page-proxy.js";export*from"./normalize-resolve-alias.js";export*from"./normalize-template-inject-tokens.js";export*from"./open-page.js";export*from"./print-log.js";export*from"./refresh-evolve-mock-options.js";export*from"./script-injects.js";export*from"./should-enable-react-fast-refresh.js";export*from"./split-to-entry-group.js";export*from"./verify-group-entry-options.js";
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './build-server/index.js';
2
2
  export * from './define-config/index.js';
3
+ export * from './helpers/assert-multi-html-cdn.js';
3
4
  export * from './load-config/index.js';
4
5
  export * from './main/index.js';
5
6
  export * from './types/types-build.js';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export*from"./build-server/index.js";export*from"./define-config/index.js";export*from"./load-config/index.js";export*from"./main/index.js";export*from"./types/types-build.js";export*from"./types/types-cli-options.js";export*from"./types/types-entry-map.js";export*from"./types/types-options.js";
1
+ export*from"./build-server/index.js";export*from"./define-config/index.js";export*from"./helpers/assert-multi-html-cdn.js";export*from"./load-config/index.js";export*from"./main/index.js";export*from"./types/types-build.js";export*from"./types/types-cli-options.js";export*from"./types/types-entry-map.js";export*from"./types/types-options.js";
@@ -1 +1 @@
1
- import{logger,mergeOptions}from"@flatjs/common";import{searchConfig}from"@hyperse/config-loader";import{configFileName,moduleName}from"../constants.js";import{defaultEvolveOptions}from"../default-options.js";import{normalizeResolveAlias}from"../helpers/normalize-resolve-alias.js";import{refreshEvolveMockOptions}from"../helpers/refresh-evolve-mock-options.js";export const loadEvolveConfig=async(o,e,i={},l={configFile:configFileName,loaderOptions:{externals:[/^@flatjs\/.*/]}})=>{const{configFile:r,loaderOptions:s}=l,a=await searchConfig(r,e,{...s,projectCwd:e});let n={};n="function"==typeof a?.config?await(a?.config(o)):a?.config||{};const t=mergeOptions(defaultEvolveOptions,n),m=mergeOptions(t,i),f=mergeOptions(m,{projectCwd:e}),p="build"===o.command?f:await refreshEvolveMockOptions(e,f,l);return logger.debug(`Load evolve config:\n${JSON.stringify(p,null,2)}`,moduleName),p.webpack?.resolve?.alias&&(p.webpack.resolve.alias=normalizeResolveAlias(e,p.webpack?.resolve?.alias)),p};
1
+ import{logger,mergeOptions}from"@flatjs/common";import{searchConfig}from"@hyperse/config-loader";import{configFileName,moduleName}from"../constants.js";import{defaultEvolveOptions}from"../default-options.js";import{normalizeResolveAlias}from"../helpers/normalize-resolve-alias.js";import{refreshEvolveMockOptions}from"../helpers/refresh-evolve-mock-options.js";export const loadEvolveConfig=async(o,e,i={},l={configFile:configFileName,loaderOptions:{externals:[/^@flatjs\/.*/]}})=>{const{configFile:r,loaderOptions:s}=l,a=await searchConfig(r,e,{...s,projectCwd:e});let n;n="function"==typeof a?.config?await(a?.config(o)):a?.config||{};const t=mergeOptions(defaultEvolveOptions,n),m=mergeOptions(t,i),f=mergeOptions(m,{projectCwd:e}),p="build"===o.command?f:await refreshEvolveMockOptions(e,f,l);return logger.debug(`Load evolve config:\n${JSON.stringify(p,null,2)}`,moduleName),p.webpack?.resolve?.alias&&(p.webpack.resolve.alias=normalizeResolveAlias(e,p.webpack?.resolve?.alias)),p};
@@ -1 +1 @@
1
- import Tinypool from"tinypool";import{mergeOptions}from"@flatjs/common";import{customMessageChannel}from"../helpers/custom-message-channel.js";import{getWorkerPath}from"./get-worker-path.js";import startBuildWorker from"./start-build-worker.js";class ThreadPoolForUnittest{startBuildWorker(e){return startBuildWorker(e)}terminate(){console.warn('[WARNING] Using fake "terminate" for unittest!')}}class ThreadPoolForTinyPool{constructor(e,r){const{idleTimeout:o=6e4,minThreads:t=1,maxThreads:s}=r||{};this.pool=new Tinypool({runtime:"worker_threads",filename:e,minThreads:t,maxThreads:s,idleTimeout:o})}startBuildWorker(e){const{port1:r}=customMessageChannel.createMessageChannel(),o=mergeOptions(e,{messagePort:r});return this.pool.run(o,{transferList:[r]})}terminate(){this.pool.destroy(),customMessageChannel.dispose()}}export const createThreadWorker=e=>{const r=getWorkerPath();return"test"===process.env.NODE_ENV?(console.warn("[WARNING] Using fake thread pool worker for unittest!"),new ThreadPoolForUnittest):new ThreadPoolForTinyPool(r,e)};
1
+ import Tinypool from"tinypool";import{mergeOptions}from"@flatjs/common";import{customMessageChannel}from"../helpers/custom-message-channel.js";import{getWorkerPath}from"./get-worker-path.js";import startBuildWorker from"./start-build-worker.js";class ThreadPoolForUnittest{startBuildWorker(e){return startBuildWorker(e)}terminate(){console.warn('[WARNING] Using fake "terminate" for unittest!')}}class ThreadPoolForTinyPool{constructor(e,o){const{idleTimeout:r=6e4,minThreads:t=1,maxThreads:s}=o||{};this.pool=new Tinypool({runtime:"worker_threads",filename:e,minThreads:t,maxThreads:s,idleTimeout:r})}startBuildWorker(e){const{port1:o}=customMessageChannel.createMessageChannel(),r=mergeOptions(e,{messagePort:Tinypool.move(o)});return this.pool.run(r)}terminate(){this.pool.destroy(),customMessageChannel.dispose()}}export const createThreadWorker=e=>{const o=getWorkerPath();return"test"===process.env.NODE_ENV?(console.warn("[WARNING] Using fake thread pool worker for unittest!"),new ThreadPoolForUnittest):new ThreadPoolForTinyPool(o,e)};
@@ -1 +1 @@
1
- import{ensureSlash,mergeOptions}from"@flatjs/common";import{ignoreEntryOptionKeys}from"../constants.js";import{startRspackBuild}from"../core/rspack/start-rspack-build.js";import{startWebpackBuild}from"../core/webpack/index.js";import{EvolveBuildError}from"../errors/evolve-build-error.js";import{printCompilerError}from"../helpers/print-log.js";import{verifyGroupEntryOptions}from"../helpers/verify-group-entry-options.js";export const prepareBuild=async(r,o,t)=>{const{compiler:e}=o,s=Object.values(r)[0];if(!verifyGroupEntryOptions(r,ignoreEntryOptionKeys,!0))throw new Error("The entry options in a group must be the same.");const i=o.multiHtmlCdn?.prod||[];if(!i.length)throw new Error(`No CDN config for env:"prod", groupName: ${s.groupName}`);const p=ensureSlash(i[Math.floor(Math.random()*i.length)],!0);try{const i=s.options?.useRelativeAssetPath,n=mergeOptions(o,{webpack:{publicPath:i?"auto":p}});return"webpack"===e?await startWebpackBuild(r,n,t):await startRspackBuild(r,n,t)}catch(r){const o=printCompilerError(r);throw new EvolveBuildError("BUILD_ERROR",o)}};
1
+ import{ensureSlash,mergeOptions}from"@flatjs/common";import{ignoreEntryOptionKeys}from"../constants.js";import{startRspackBuild}from"../core/rspack/start-rspack-build.js";import{startWebpackBuild}from"../core/webpack/index.js";import{EvolveBuildError}from"../errors/evolve-build-error.js";import{assertMultiHtmlCdn}from"../helpers/assert-multi-html-cdn.js";import{printCompilerError}from"../helpers/print-log.js";import{verifyGroupEntryOptions}from"../helpers/verify-group-entry-options.js";export const prepareBuild=async(r,o,t)=>{const{compiler:e}=o,s=Object.values(r)[0];if(!verifyGroupEntryOptions(r,ignoreEntryOptionKeys,!0))throw new Error("The entry options in a group must be the same.");const i=assertMultiHtmlCdn(o)?.prod||[];if(!i.length)throw new Error(`No CDN config for env:"prod", groupName: ${s.groupName}`);const p=ensureSlash(i[Math.floor(Math.random()*i.length)],!0);try{const i=s.options?.useRelativeAssetPath,n=mergeOptions(o,{webpack:{publicPath:i?"auto":p}});return"webpack"===e?await startWebpackBuild(r,n,t):await startRspackBuild(r,n,t)}catch(r){const o=printCompilerError(r);throw new EvolveBuildError("BUILD_ERROR",o)}};
@@ -1 +1 @@
1
- import{logger}from"@flatjs/common";import{CircularDependencyRspackPlugin}from"@rspack/core";const cutBefore=(e,r)=>{const n=new RegExp(`^[\\s\\S]*?${r}`),c=e.replace(n,"");return c.includes("!/")?`/${c.split("!/")[1]}`:c};export const createCircularDependencyRspackPlugins=(e,r)=>{if(!e)return[];const{projectCwd:n}=r;return[new CircularDependencyRspackPlugin({exclude:/node_modules/,failOnError:!1,onDetected(e,r){const c=r.map(e=>cutBefore(e,n)).join(" -> ");logger.warn(`Circular dependency detected:\r\n ${c}`)}})]};
1
+ import{logger}from"@flatjs/common";import{CircularCheckRspackPlugin}from"@rspack/core";const cutBefore=(e,r)=>{const c=new RegExp(`^[\\s\\S]*?${r}`),n=e.replace(c,"");return n.includes("!/")?`/${n.split("!/")[1]}`:n};export const createCircularDependencyRspackPlugins=(e,r)=>{if(!e)return[];const{projectCwd:c}=r;return[new CircularCheckRspackPlugin({exclude:/node_modules/,failOnError:!1,onDetected({paths:e}){const r=e.map(e=>cutBefore(e,c)).join(" -> ");logger.warn(`Circular dependency detected:\r\n ${r}`)}})]};
@@ -1 +1 @@
1
- import{join}from"node:path";import{ensureSlash}from"@flatjs/common";import rspack from"@rspack/core";import{normalizeEvolveEntryName}from"../../../helpers/normalize-entry-map.js";import{injectFederationScripts}from"../../../helpers/script-injects.js";import{HtmlInjectScriptWebpackPlugin}from"../../webpack/html-inject-scripts/index.js";import{ExternalTemplateRemotesRspackPlugin}from"./external-template-remotes-rspack-plugin.js";const normalizeWidgetName=(e="")=>e.replace(/[/-]/g,"_").toLowerCase(),remoteFileName=e=>join(e,"micro-remote-module.js");export const createModuleFederationRspackPlugins=(e,t,r)=>{const o=r.projectVirtualPath,n=r.multiHtmlCdn,i=r.multiHtmlCdnEnvResolver,m=[];for(const r of t){const[t,a]=r,s=a.options?.moduleFederation;if(s){const{remotes:r,exposes:a,...l}=s,c=remoteFileName(t),p=normalizeWidgetName(t),u=(a?Array.isArray(a)?a:[a]:[]).map(e=>{const r={};for(const[o,n]of Object.entries(e))r[o]={...n,name:join(t,n.name.replace(/^\//,""))};return r}),d=(r||[]).map(({name:e,endpoint:t})=>{const r=normalizeEvolveEntryName(e,o),n=normalizeWidgetName(r),i=remoteFileName(r),m=t?ensureSlash(t(e,r),!1):"[window.evolveFetchMicroWidgets()]";return{[n]:`${n}@${m}/${i}`}});m.push(new rspack.container.ModuleFederationPlugin({...l,name:p,filename:c,remotes:d,exposes:u}),new ExternalTemplateRemotesRspackPlugin),e||m.unshift(new HtmlInjectScriptWebpackPlugin([injectFederationScripts(n,i)]))}}return m};
1
+ import{join}from"node:path";import{ensureSlash}from"@flatjs/common";import rspack from"@rspack/core";import{assertMultiHtmlCdn}from"../../../helpers/assert-multi-html-cdn.js";import{normalizeEvolveEntryName}from"../../../helpers/normalize-entry-map.js";import{injectFederationScripts}from"../../../helpers/script-injects.js";import{HtmlInjectScriptWebpackPlugin}from"../../webpack/html-inject-scripts/index.js";import{ExternalTemplateRemotesRspackPlugin}from"./external-template-remotes-rspack-plugin.js";const normalizeWidgetName=(e="")=>e.replace(/[/-]/g,"_").toLowerCase(),remoteFileName=e=>join(e,"micro-remote-module.js");export const createModuleFederationRspackPlugins=(e,t,r)=>{const o=r.projectVirtualPath,n=assertMultiHtmlCdn(r),m=r.multiHtmlCdnEnvResolver,i=[];for(const r of t){const[t,s]=r,a=s.options?.moduleFederation;if(a){const{remotes:r,exposes:s,...l}=a,p=remoteFileName(t),c=normalizeWidgetName(t),u=(s?Array.isArray(s)?s:[s]:[]).map(e=>{const r={};for(const[o,n]of Object.entries(e))r[o]={...n,name:join(t,n.name.replace(/^\//,""))};return r}),d=(r||[]).map(({name:e,endpoint:t})=>{const r=normalizeEvolveEntryName(e,o),n=normalizeWidgetName(r),m=remoteFileName(r),i=t?ensureSlash(t(e,r),!1):"[window.evolveFetchMicroWidgets()]";return{[n]:`${n}@${i}/${m}`}});i.push(new rspack.container.ModuleFederationPlugin({...l,name:c,filename:p,remotes:d,exposes:u}),new ExternalTemplateRemotesRspackPlugin),e||i.unshift(new HtmlInjectScriptWebpackPlugin([injectFederationScripts(n,m)]))}}return i};
@@ -1 +1 @@
1
- import{FlatEvolveMultiCdnRspackPlugin}from"./multi-html-cdn-rspack-plugin.js";import{createMultiHtmlRspackPlugins}from"./multi-html-rspack-plugin.js";export const createHtmlRspackPlugins=async(t,l,s)=>{const i=[];if(t)return i;const n=Object.keys(s.multiHtmlCdn);return i.push(...await createMultiHtmlRspackPlugins(t,s,l,n)),i.push(new FlatEvolveMultiCdnRspackPlugin(s,l)),i};
1
+ import{assertMultiHtmlCdn}from"../../../helpers/assert-multi-html-cdn.js";import{FlatEvolveMultiCdnRspackPlugin}from"./multi-html-cdn-rspack-plugin.js";import{createMultiHtmlRspackPlugins}from"./multi-html-rspack-plugin.js";export const createHtmlRspackPlugins=async(t,l,s)=>{const i=[];if(t)return i;const n=Object.keys(assertMultiHtmlCdn(s));return i.push(...await createMultiHtmlRspackPlugins(t,s,l,n)),i.push(new FlatEvolveMultiCdnRspackPlugin(s,l)),i};
@@ -1,4 +1,4 @@
1
- import type { Compiler } from 'webpack';
1
+ import type { Compiler } from '@rspack/core';
2
2
  import type { EntryMapItem, FlatEvolveOptions } from '../../../types/index.js';
3
3
  export declare class FlatEvolveMultiCdnRspackPlugin {
4
4
  private pluginName;
@@ -1 +1 @@
1
- import HtmlWebpackPlugin from"html-webpack-plugin";import{basename}from"node:path";import{ensureSlash}from"@flatjs/common";import rspack from"@rspack/core";import{getRuntimeCDNBase}from"../../../helpers/get-runtime-cdn-base.js";import{findEnvCdn,httpUrlJoin}from"../../../helpers/script-injects.js";export class FlatEvolveMultiCdnRspackPlugin{constructor(e,t){if(this.pluginName="FlatEvolveMultiCdnRspackPlugin",this.requireFn=rspack.RuntimeGlobals.publicPath,this.config=e.multiHtmlCdn,this.entryMapItemList=t,this.cdnResolver=e.multiHtmlCdnEnvResolver||function cdnResolver(){},!this.config?.prod)throw new Error("We must setup `prod` for each CDN config node!")}apply(e){e.hooks.compilation.tap(this.pluginName,e=>{e.hooks.runtimeModule.tap(this.pluginName,(e,t)=>{const s=this.entryMapItemList.find(e=>e[0]===t.name);if("public_path"===e.name&&s){const t=[];t.push("\n"),t.push("// Dynamic assets path override(`@flatjs/evolve`) plugin-multi-html-cdn`)"),t.push(getRuntimeCDNBase(this.config,this.cdnResolver,this.requireFn)),e.source.source=Buffer.from(t.join("\n"),"utf-8")}})}),e.hooks.compilation.tap(this.pluginName,t=>{HtmlWebpackPlugin.getHooks(t).beforeAssetTagGeneration.tap(this.pluginName,e=>{const{assets:t,plugin:s,outputName:n}=e,i=s?.options?.chunks||[],o=Array.isArray(i)?i.find(e=>n.includes(ensureSlash(e,!0))):i,{userOptions:r}=e.plugin;if(!o)throw new Error("We must have current chunk!");const a=t.js.filter(e=>e.includes(ensureSlash(o,!0))),l=t.css.filter(e=>e.includes(ensureSlash(o,!0))),p=r.multiCdn,u=t.publicPath,c=a.map(e=>{if(p.disabled)return basename(e);const t=findEnvCdn(this.config,p.env);return httpUrlJoin(t,e.replace(u,""))}),m=l.map(e=>{if(p.disabled)return basename(e);const t=findEnvCdn(this.config,p.env);return httpUrlJoin(t,e.replace(u,""))});return e.assets.js=c,e.assets.css=m,e}),t.hooks.processAssets.tap({name:this.pluginName,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},s=>{if(e.options.output.library)for(const e of Object.keys(s))e.endsWith(".html")&&delete t.assets[e]})})}}
1
+ import HtmlWebpackPlugin from"html-webpack-plugin";import{basename}from"node:path";import{ensureSlash}from"@flatjs/common";import rspack from"@rspack/core";import{assertMultiHtmlCdn}from"../../../helpers/assert-multi-html-cdn.js";import{getRuntimeCDNBase}from"../../../helpers/get-runtime-cdn-base.js";import{findEnvCdn,httpUrlJoin}from"../../../helpers/script-injects.js";export class FlatEvolveMultiCdnRspackPlugin{constructor(t,e){if(this.pluginName="FlatEvolveMultiCdnRspackPlugin",this.requireFn=rspack.RuntimeGlobals.publicPath,this.config=assertMultiHtmlCdn(t),this.entryMapItemList=e,this.cdnResolver=t.multiHtmlCdnEnvResolver||function cdnResolver(){},!this.config?.prod)throw new Error("We must setup `prod` for each CDN config node!")}apply(t){t.hooks.compilation.tap(this.pluginName,t=>{t.hooks.runtimeModule.tap(this.pluginName,(t,e)=>{const s=this.entryMapItemList.find(t=>t[0]===e.name);if("public_path"===t.name&&s&&t.source){const e=t.source.source.toString("utf-8"),s=["","// Dynamic assets path override...",getRuntimeCDNBase(this.config,this.cdnResolver,this.requireFn)].join("\n");t.source.source=Buffer.from(`${e}\n${s}`,"utf-8")}})}),t.hooks.compilation.tap(this.pluginName,e=>{HtmlWebpackPlugin.getHooks(e).beforeAssetTagGeneration.tap(this.pluginName,t=>{const{assets:e,plugin:s,outputName:n}=t,i=s?.options?.chunks||[],r=Array.isArray(i)?i.find(t=>n.includes(ensureSlash(t,!0))):i,{userOptions:o}=t.plugin;if(!r)throw new Error("We must have current chunk!");const a=e.js.filter(t=>t.includes(ensureSlash(r,!0))),l=e.css.filter(t=>t.includes(ensureSlash(r,!0))),p=o.multiCdn,u=e.publicPath,c=a.map(t=>{if(p.disabled)return basename(t);const e=findEnvCdn(this.config,p.env);return httpUrlJoin(e,t.replace(u,""))}),m=l.map(t=>{if(p.disabled)return basename(t);const e=findEnvCdn(this.config,p.env);return httpUrlJoin(e,t.replace(u,""))});return t.assets.js=c,t.assets.css=m,t}),e.hooks.processAssets.tap({name:this.pluginName,stage:t.webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},s=>{if(t.options.output.library)for(const t of Object.keys(s))t.endsWith(".html")&&delete e.assets[t]})})}}
@@ -1 +1 @@
1
- import HtmlWebpackPlugin from"html-webpack-plugin";import{existsSync}from"node:fs";import{logger,requireResolve}from"@flatjs/common";import{allowPx2remForModule}from"../../../helpers/allow-px2rem-for-module.js";import{checkHtmlTemplateOptions}from"../../../helpers/check-html-template-options.js";import{getHtmlMinOrder}from"../../../helpers/get-html-max-order.js";import{getHtmlPluginConfig}from"../../../helpers/get-html-plugin-config.js";import{normalizeTemplateInjectTokens}from"../../../helpers/normalize-template-inject-tokens.js";import{findEnvCdn}from"../../../helpers/script-injects.js";import{MultiHtmlModifyRspackPlugin}from"./multi-html-modify-rspack-plugin.js";const minifyOpts={minifyJS:!0,removeComments:!0,collapseWhitespace:!0,collapseBooleanAttributes:!1};export const createMultiHtmlRspackPlugins=async(e,t,l,i)=>{const o=l[0],[,n]=o,m=[new MultiHtmlModifyRspackPlugin(t,l)],{options:r}=n,p=e?"development":"production",s=l.map(e=>e[0]);for(const e of i){const l={mode:p,envCdn:findEnvCdn(t.multiHtmlCdn,e)},i=normalizeTemplateInjectTokens(l,r);checkHtmlTemplateOptions(i);const n=i?.headInlineScripts||[];if(allowPx2remForModule(o,t)){const e=getHtmlMinOrder(n),t=getHtmlPluginConfig("viewport",l,r?.viewport);n.push({id:"viewport",content:t,position:"end",order:e-1})}let a=getHtmlPluginConfig("templatePath",l,r?.templatePath).replace("{0}",e.trim());existsSync(a)||(logger.warn(`The template file ${a} is not exists, use \`prod\` instead!`),a=getHtmlPluginConfig("templatePath",l,r?.templatePath).replace("{0}","prod"));a=`${requireResolve(import.meta.url,"@hyperse/html-webpack-plugin-loader/loader")}!${a}`,m.push(new HtmlWebpackPlugin({inject:"body",title:getHtmlPluginConfig("title",l,r?.title),chunks:s,minify:!1!==r?.htmlMinify&&!["me","dev"].includes(e)&&minifyOpts,filename:t=>`${t}/index${"prod"===e?"":`-${e}`}.html`,template:a,templateParameters:{title:"",...i,headInlineScripts:n},multiCdn:{env:e,disabled:(r?.excludeCdnEnvs||["me","dev","ntv"]).includes(e)}}))}return m};
1
+ import HtmlWebpackPlugin from"html-webpack-plugin";import{existsSync}from"node:fs";import{logger,requireResolve}from"@flatjs/common";import{allowPx2remForModule}from"../../../helpers/allow-px2rem-for-module.js";import{assertMultiHtmlCdn}from"../../../helpers/assert-multi-html-cdn.js";import{checkHtmlTemplateOptions}from"../../../helpers/check-html-template-options.js";import{getHtmlMinOrder}from"../../../helpers/get-html-max-order.js";import{getHtmlPluginConfig}from"../../../helpers/get-html-plugin-config.js";import{normalizeTemplateInjectTokens}from"../../../helpers/normalize-template-inject-tokens.js";import{findEnvCdn}from"../../../helpers/script-injects.js";import{MultiHtmlModifyRspackPlugin}from"./multi-html-modify-rspack-plugin.js";const minifyOpts={minifyJS:!0,removeComments:!0,collapseWhitespace:!0,collapseBooleanAttributes:!1};export const createMultiHtmlRspackPlugins=async(e,t,l,i)=>{const o=l[0],[,n]=o,m=[new MultiHtmlModifyRspackPlugin(t,l)],{options:r}=n,s=e?"development":"production",p=l.map(e=>e[0]);for(const e of i){const l={mode:s,envCdn:findEnvCdn(assertMultiHtmlCdn(t),e)},i=normalizeTemplateInjectTokens(l,r);checkHtmlTemplateOptions(i);const n=i?.headInlineScripts||[];if(allowPx2remForModule(o,t)){const e=getHtmlMinOrder(n),t=getHtmlPluginConfig("viewport",l,r?.viewport);n.push({id:"viewport",content:t,position:"end",order:e-1})}let a=getHtmlPluginConfig("templatePath",l,r?.templatePath).replace("{0}",e.trim());existsSync(a)||(logger.warn(`The template file ${a} is not exists, use \`prod\` instead!`),a=getHtmlPluginConfig("templatePath",l,r?.templatePath).replace("{0}","prod"));a=`${requireResolve(import.meta.url,"@hyperse/html-webpack-plugin-loader/loader")}!${a}`,m.push(new HtmlWebpackPlugin({inject:"body",title:getHtmlPluginConfig("title",l,r?.title),chunks:p,minify:!1!==r?.htmlMinify&&!["me","dev"].includes(e)&&minifyOpts,filename:t=>`${t}/index${"prod"===e?"":`-${e}`}.html`,template:a,templateParameters:{title:"",...i,headInlineScripts:n},multiCdn:{env:e,disabled:(r?.excludeCdnEnvs||["me","dev","ntv"]).includes(e)}}))}return m};
@@ -1,4 +1,3 @@
1
- import type { Plugin as RspackPlugin } from '@rspack/core';
2
- import { type ProgressPluginArgument } from '@rspack/core';
1
+ import type { Plugin as RspackPlugin, ProgressPluginOptions } from '@rspack/core';
3
2
  import type { EntryMapItem } from '../../../types/types-entry-map.js';
4
- export declare const createProgressRspackPlugins: (serveMode: boolean, entryMapItemList: EntryMapItem[], pluginOptions?: ProgressPluginArgument) => RspackPlugin[];
3
+ export declare const createProgressRspackPlugins: (serveMode: boolean, entryMapItemList: EntryMapItem[], pluginOptions?: ProgressPluginOptions) => RspackPlugin[];
@@ -1 +1 @@
1
- import{relative}from"node:path";import Graph from"tarjan-graph";import webpack from"webpack";import{mergeOptions}from"@flatjs/common";const BASE_ERROR="Circular dependency detected:\r\n",PLUGIN_TITLE="CircularDependencyWebpackPlugin";export class CircularDependencyWebpackPlugin{constructor(o={}){this.options=mergeOptions({exclude:/node_modules/,include:/.*/,failOnError:!1,allowAsyncCycles:!1,projectCwd:process.cwd()},o)}apply(o){const e=this.options.projectCwd;o.hooks.compilation.tap(PLUGIN_TITLE,o=>{o.hooks.optimizeModules.tap(PLUGIN_TITLE,t=>{this.options.onStart&&this.options.onStart({compilation:o});const n=new(Graph.default||Graph);for(const e of t){const t=[];for(const n of e.dependencies){if(n.constructor&&"CommonJsSelfReferenceDependency"===n.constructor.name)continue;let r=null;r=o.moduleGraph?o.moduleGraph.getModule(n):n.module,r&&(r instanceof webpack.NormalModule&&r.resource&&(this.options.allowAsyncCycles&&n.weak||e!==r&&t.push(r.identifier())))}n.add(e.identifier(),t)}const r=n.getCycles();this.isCyclic(r,o,e),this.options.onEnd&&this.options.onEnd({compilation:o})})})}isCyclic(o,e,t){o.forEach(o=>{const n=o.slice().reverse().map(o=>{const t=e.findModule(o.name);return t instanceof webpack.NormalModule&&t.resource||null});if(n.every(o=>!o||this.options.exclude.test(o)||!this.options.include.test(o)))return;const r=n.map(o=>relative(t,o));if(this.options.onDetected){try{this.options.onDetected({paths:r.concat([r[0]]),compilation:e})}catch(o){e.errors.push(o)}return}const s=new Error(BASE_ERROR.concat(r.concat([r[0]]).join(" -> ")));this.options.failOnError?e.errors.push(s):e.warnings.push(s)})}}
1
+ import{relative}from"node:path";import Graph from"tarjan-graph";import webpack from"webpack";import{mergeOptions}from"@flatjs/common";const BASE_ERROR="Circular dependency detected:\r\n",PLUGIN_TITLE="CircularDependencyWebpackPlugin";export class CircularDependencyWebpackPlugin{constructor(o={}){this.options=mergeOptions({exclude:/node_modules/,include:/.*/,failOnError:!1,allowAsyncCycles:!1,projectCwd:process.cwd()},o)}apply(o){const e=this.options.projectCwd;o.hooks.compilation.tap(PLUGIN_TITLE,o=>{o.hooks.optimizeModules.tap(PLUGIN_TITLE,t=>{this.options.onStart&&this.options.onStart({compilation:o});const n=new(Graph.default||Graph);for(const e of t){const t=[];for(const n of e.dependencies){if(n.constructor&&"CommonJsSelfReferenceDependency"===n.constructor.name)continue;let r;r=o.moduleGraph?o.moduleGraph.getModule(n):n.module,r&&(r instanceof webpack.NormalModule&&r.resource&&(this.options.allowAsyncCycles&&"weak"in n&&n.weak||e!==r&&t.push(r.identifier())))}n.add(e.identifier(),t)}const r=n.getCycles();this.isCyclic(r,o,e),this.options.onEnd&&this.options.onEnd({compilation:o})})})}isCyclic(o,e,t){o.forEach(o=>{const n=o.slice().reverse().map(o=>{const t=e.findModule(o.name);return t instanceof webpack.NormalModule&&t.resource||null});if(n.every(o=>!o||this.options.exclude.test(o)||!this.options.include.test(o)))return;const r=n.map(o=>relative(t,o));if(this.options.onDetected){try{this.options.onDetected({paths:r.concat([r[0]]),compilation:e})}catch(o){e.errors.push(o)}return}const s=new Error(BASE_ERROR.concat(r.concat([r[0]]).join(" -> ")));this.options.failOnError?e.errors.push(s):e.warnings.push(s)})}}
@@ -1 +1 @@
1
- import{rmSync}from"node:fs";import{relative}from"node:path";import{fileWalkSync}from"@armit/file-utility";import{logger}from"@flatjs/common";import{moduleName}from"../../../constants.js";export class CleanWebpackPlugin{constructor(e={}){this.verbose=!0===e.verbose||!1,this.projectCwd=e.projectCwd||process.cwd(),this.cleanStaleWebpackAssets=!0!==e.cleanStaleWebpackAssets&&!1!==e.cleanStaleWebpackAssets||e.cleanStaleWebpackAssets,this.protectWebpackAssets=!0!==e.protectWebpackAssets&&!1!==e.protectWebpackAssets||e.protectWebpackAssets,this.cleanAfterEveryBuildPatterns=Array.isArray(e.cleanAfterEveryBuildPatterns)?e.cleanAfterEveryBuildPatterns:[],this.cleanOnceBeforeBuildPatterns=Array.isArray(e.cleanOnceBeforeBuildPatterns)?e.cleanOnceBeforeBuildPatterns:["**/*"],this.currentAssets=[],this.initialClean=!1,this.outputPath="",this.apply=this.apply.bind(this),this.handleInitial=this.handleInitial.bind(this),this.handleDone=this.handleDone.bind(this),this.removeFiles=this.removeFiles.bind(this)}apply(e){if(!e.options.output||!e.options.output.path)return void logger.warn("clean-webpack-plugin: options.output.path not defined. Plugin disabled...",moduleName);this.outputPath=e.options.output.path;const t=e.hooks;0!==this.cleanOnceBeforeBuildPatterns.length&&t.emit.tap("clean-webpack-plugin",e=>{this.handleInitial(e)}),t.done.tap("clean-webpack-plugin",e=>{logger.info("start clean cache..."),this.handleDone(e)})}handleInitial(e){if(this.initialClean)return;e.getStats().hasErrors()||(this.initialClean=!0,this.removeFiles(this.cleanOnceBeforeBuildPatterns))}handleDone(e){if(e.hasErrors())return void(this.verbose&&logger.warn("clean-webpack-plugin: pausing due to webpack errors",moduleName));const t=(e.toJson({assets:!0}).assets||[]).map(e=>e.name),s=this.currentAssets.filter(e=>!1===t.includes(e));this.currentAssets=t.sort();const i=[];!0===this.cleanStaleWebpackAssets&&0!==s.length&&i.push(...s),0!==this.cleanAfterEveryBuildPatterns.length&&i.push(...this.cleanAfterEveryBuildPatterns),0!==i.length&&this.removeFiles(i)}removeFiles(e){try{const t=fileWalkSync(e,{absolute:!0,unique:!0,cwd:this.outputPath,dot:!0,ignore:this.protectWebpackAssets?this.currentAssets:[]});for(const e of t)rmSync(e,{force:!0,recursive:!0});this.verbose&&t.forEach(e=>{const t=relative(this.projectCwd,e);logger.debug(`clean-webpack-plugin: removed ${t}`,moduleName)})}catch(e){if(/Cannot delete files\/folders outside the current working directory\./.test(e.message)){throw new Error("clean-webpack-plugin: Cannot delete files/folders outside the current working directory. Can be overridden with the `dangerouslyAllowCleanPatternsOutsideProject` option.")}throw e}}}
1
+ import{rmSync}from"node:fs";import{relative}from"node:path";import{fileWalkSync}from"@armit/file-utility";import{logger}from"@flatjs/common";import{moduleName}from"../../../constants.js";export class CleanWebpackPlugin{constructor(e={}){this.verbose=!0===e.verbose||!1,this.projectCwd=e.projectCwd||process.cwd(),this.cleanStaleWebpackAssets=!0!==e.cleanStaleWebpackAssets&&!1!==e.cleanStaleWebpackAssets||e.cleanStaleWebpackAssets,this.protectWebpackAssets=!0!==e.protectWebpackAssets&&!1!==e.protectWebpackAssets||e.protectWebpackAssets,this.cleanAfterEveryBuildPatterns=Array.isArray(e.cleanAfterEveryBuildPatterns)?e.cleanAfterEveryBuildPatterns:[],this.cleanOnceBeforeBuildPatterns=Array.isArray(e.cleanOnceBeforeBuildPatterns)?e.cleanOnceBeforeBuildPatterns:["**/*"],this.currentAssets=[],this.initialClean=!1,this.outputPath="",this.apply=this.apply.bind(this),this.handleInitial=this.handleInitial.bind(this),this.handleDone=this.handleDone.bind(this),this.removeFiles=this.removeFiles.bind(this)}apply(e){if(!e.options.output||!e.options.output.path)return void logger.warn("clean-webpack-plugin: options.output.path not defined. Plugin disabled...",moduleName);this.outputPath=e.options.output.path;const t=e.hooks;0!==this.cleanOnceBeforeBuildPatterns.length&&t.emit.tap("clean-webpack-plugin",e=>{this.handleInitial(e)}),t.done.tap("clean-webpack-plugin",e=>{logger.info("start clean cache..."),this.handleDone(e)})}handleInitial(e){if(this.initialClean)return;e.getStats().hasErrors()||(this.initialClean=!0,this.removeFiles(this.cleanOnceBeforeBuildPatterns))}handleDone(e){if(e.hasErrors())return void(this.verbose&&logger.warn("clean-webpack-plugin: pausing due to webpack errors",moduleName));const t=(e.toJson({assets:!0}).assets||[]).map(e=>e.name),s=this.currentAssets.filter(e=>!1===t.includes(e));this.currentAssets=t.sort();const i=[];!0===this.cleanStaleWebpackAssets&&0!==s.length&&i.push(...s),0!==this.cleanAfterEveryBuildPatterns.length&&i.push(...this.cleanAfterEveryBuildPatterns),0!==i.length&&this.removeFiles(i)}removeFiles(e){try{const t=fileWalkSync(e,{absolute:!0,unique:!0,cwd:this.outputPath,dot:!0,ignore:this.protectWebpackAssets?this.currentAssets:[]});for(const e of t)rmSync(e,{force:!0,recursive:!0});this.verbose&&t.forEach(e=>{const t=relative(this.projectCwd,e);logger.debug(`clean-webpack-plugin: removed ${t}`,moduleName)})}catch(e){if(/Cannot delete files\/folders outside the current working directory\./.test(e.message)){const t="clean-webpack-plugin: Cannot delete files/folders outside the current working directory. Can be overridden with the `dangerouslyAllowCleanPatternsOutsideProject` option.";throw Object.assign(new Error(t),{cause:e})}throw e}}}
@@ -1,4 +1,4 @@
1
- import { type WebpackPluginInstance } from 'webpack';
1
+ import webpack from 'webpack';
2
2
  import { type EntryMapItem } from '../../../types/types-entry-map.js';
3
3
  import { type FlatEvolveOptions } from '../../../types/types-options.js';
4
- export declare const createModuleFederationWebpackPlugins: (serveMode: boolean, entryMapItemList: EntryMapItem[], evolveOptions: FlatEvolveOptions) => WebpackPluginInstance[];
4
+ export declare const createModuleFederationWebpackPlugins: (serveMode: boolean, entryMapItemList: EntryMapItem[], evolveOptions: FlatEvolveOptions) => webpack.WebpackPluginInstance[];
@@ -1 +1 @@
1
- import{join}from"node:path";import webpack from"webpack";import{ensureSlash}from"@flatjs/common";import{normalizeEvolveEntryName}from"../../../helpers/normalize-entry-map.js";import{injectFederationScripts}from"../../../helpers/script-injects.js";import{HtmlInjectScriptWebpackPlugin}from"../html-inject-scripts/index.js";import{ExternalTemplateRemotesWebpackPlugin}from"./external-template-remotes-webpack-plugin.js";const normalizeWidgetName=(e="")=>e.replace(/[/-]/g,"_").toLowerCase(),remoteFileName=e=>join(e,"micro-remote-module.js");export const createModuleFederationWebpackPlugins=(e,t,o)=>{const r=o.projectVirtualPath,n=o.multiHtmlCdn,i=o.multiHtmlCdnEnvResolver,m=[];for(const o of t){const[t,a]=o,l=a.options?.moduleFederation;if(l){const{remotes:o,exposes:a,...s}=l,p=remoteFileName(t),c=normalizeWidgetName(t),u=(a?Array.isArray(a)?a:[a]:[]).map(e=>{const o={};for(const[r,n]of Object.entries(e))o[r]={...n,name:join(t,n.name.replace(/^\//,""))};return o}),d=(o||[]).map(({name:e,endpoint:t})=>{const o=normalizeEvolveEntryName(e,r),n=normalizeWidgetName(o),i=remoteFileName(o),m=t?ensureSlash(t(e,o),!1):"[window.evolveFetchMicroWidgets()]";return{[n]:`${n}@${m}/${i}`}});m.push(new webpack.container.ModuleFederationPlugin({...s,name:c,filename:p,remotes:d,exposes:u}),new ExternalTemplateRemotesWebpackPlugin),e||m.unshift(new HtmlInjectScriptWebpackPlugin([injectFederationScripts(n,i)]))}}return m};
1
+ import{join}from"node:path";import webpack from"webpack";import{ensureSlash}from"@flatjs/common";import{assertMultiHtmlCdn}from"../../../helpers/assert-multi-html-cdn.js";import{normalizeEvolveEntryName}from"../../../helpers/normalize-entry-map.js";import{injectFederationScripts}from"../../../helpers/script-injects.js";import{HtmlInjectScriptWebpackPlugin}from"../html-inject-scripts/index.js";import{ExternalTemplateRemotesWebpackPlugin}from"./external-template-remotes-webpack-plugin.js";const normalizeWidgetName=(e="")=>e.replace(/[/-]/g,"_").toLowerCase(),remoteFileName=e=>join(e,"micro-remote-module.js");export const createModuleFederationWebpackPlugins=(e,t,r)=>{const o=r.projectVirtualPath,n=assertMultiHtmlCdn(r),m=r.multiHtmlCdnEnvResolver,i=[];for(const r of t){const[t,a]=r,s=a.options?.moduleFederation;if(s){const{remotes:r,exposes:a,...l}=s,p=remoteFileName(t),c=normalizeWidgetName(t),u=(a?Array.isArray(a)?a:[a]:[]).map(e=>{const r={};for(const[o,n]of Object.entries(e))r[o]={...n,name:join(t,n.name.replace(/^\//,""))};return r}),d=(r||[]).map(({name:e,endpoint:t})=>{const r=normalizeEvolveEntryName(e,o),n=normalizeWidgetName(r),m=remoteFileName(r),i=t?ensureSlash(t(e,r),!1):"[window.evolveFetchMicroWidgets()]";return{[n]:`${n}@${i}/${m}`}});i.push(new webpack.container.ModuleFederationPlugin({...l,name:c,filename:p,remotes:d,exposes:u}),new ExternalTemplateRemotesWebpackPlugin),e||i.unshift(new HtmlInjectScriptWebpackPlugin([injectFederationScripts(n,m)]))}}return i};
@@ -1 +1 @@
1
- import{FlatEvolveMultiCdnWebpackPlugin}from"./multi-html-cdn-webpack-plugin.js";import{createMultiHtmlWebpackPlugins}from"./multi-html-webpack-plugins.js";export const createHtmlWebpackPlugins=async(t,l,e)=>{const i=[];if(t)return i;const n=Object.keys(e.multiHtmlCdn);return i.push(...await createMultiHtmlWebpackPlugins(t,e,l,n)),i.push(new FlatEvolveMultiCdnWebpackPlugin(e)),i};
1
+ import{assertMultiHtmlCdn}from"../../../helpers/assert-multi-html-cdn.js";import{FlatEvolveMultiCdnWebpackPlugin}from"./multi-html-cdn-webpack-plugin.js";import{createMultiHtmlWebpackPlugins}from"./multi-html-webpack-plugins.js";export const createHtmlWebpackPlugins=async(t,l,e)=>{const i=[];if(t)return i;const s=Object.keys(assertMultiHtmlCdn(e));return i.push(...await createMultiHtmlWebpackPlugins(t,e,l,s)),i.push(new FlatEvolveMultiCdnWebpackPlugin(e)),i};
@@ -1 +1 @@
1
- import HtmlWebpackPlugin from"html-webpack-plugin";import{basename}from"node:path";import webpack from"webpack";import{ensureSlash}from"@flatjs/common";import{getRuntimeCDNBase}from"../../../helpers/get-runtime-cdn-base.js";import{findEnvCdn,httpUrlJoin}from"../../../helpers/script-injects.js";export class FlatEvolveMultiCdnWebpackPlugin{constructor(e){if(this.pluginName="FlatEvolveMultiCdnWebpackPlugin",this.requireFn=webpack.RuntimeGlobals.publicPath,this.config=e.multiHtmlCdn,this.cdnResolver=e.multiHtmlCdnEnvResolver||function cdnResolver(){},!this.config?.prod)throw new Error("We must setup `prod` for each CDN config node!")}apply(e){e.hooks.thisCompilation.tap(this.pluginName,e=>{e.mainTemplate.hooks.requireExtensions.tap(this.pluginName,(t,s)=>{const n=[];n.push("// Dynamic assets path override(`@flatjs/evolve`) plugin-multi-html-cdn`)");const i=e.chunkGraph?.getTreeRuntimeRequirements(s);return i&&i.has(webpack.RuntimeGlobals.requireScope)&&n.push(webpack.Template.indent(getRuntimeCDNBase(this.config,this.cdnResolver,this.requireFn))),webpack.Template.asString(n)})}),e.hooks.compilation.tap(this.pluginName,t=>{HtmlWebpackPlugin.getHooks(t).beforeAssetTagGeneration.tap(this.pluginName,e=>{const{assets:t,plugin:s,outputName:n}=e,i=s?.options?.chunks||[],r=Array.isArray(i)?i.find(e=>n.includes(ensureSlash(e,!0))):i,{userOptions:o}=e.plugin;if(!r)throw new Error("We must have current chunk!");const a=t.js.filter(e=>e.includes(ensureSlash(r,!0))),l=t.css.filter(e=>e.includes(ensureSlash(r,!0))),p=o.multiCdn,u=t.publicPath,c=a.map(e=>{if(p.disabled)return basename(e);const t=findEnvCdn(this.config,p.env);return httpUrlJoin(t,e.replace(u,""))}),m=l.map(e=>{if(p.disabled)return basename(e);const t=findEnvCdn(this.config,p.env);return httpUrlJoin(t,e.replace(u,""))});return e.assets.js=c,e.assets.css=m,e}),t.hooks.processAssets.tap({name:this.pluginName,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},s=>{if(e.options.output.library)for(const e of Object.keys(s))e.endsWith(".html")&&delete t.assets[e]})})}}
1
+ import HtmlWebpackPlugin from"html-webpack-plugin";import{basename}from"node:path";import webpack from"webpack";import{ensureSlash}from"@flatjs/common";import{assertMultiHtmlCdn}from"../../../helpers/assert-multi-html-cdn.js";import{getRuntimeCDNBase}from"../../../helpers/get-runtime-cdn-base.js";import{findEnvCdn,httpUrlJoin}from"../../../helpers/script-injects.js";export class FlatEvolveMultiCdnWebpackPlugin{constructor(e){if(this.pluginName="FlatEvolveMultiCdnWebpackPlugin",this.requireFn=webpack.RuntimeGlobals.publicPath,this.config=assertMultiHtmlCdn(e),this.cdnResolver=e.multiHtmlCdnEnvResolver||function cdnResolver(){},!this.config?.prod)throw new Error("We must setup `prod` for each CDN config node!")}apply(e){e.hooks.thisCompilation.tap(this.pluginName,e=>{e.mainTemplate.hooks.requireExtensions.tap(this.pluginName,(t,s)=>{const n=[];n.push("// Dynamic assets path override(`@flatjs/evolve`) plugin-multi-html-cdn`)");const i=e.chunkGraph?.getTreeRuntimeRequirements(s);return i&&i.has(webpack.RuntimeGlobals.requireScope)&&n.push(webpack.Template.indent(getRuntimeCDNBase(this.config,this.cdnResolver,this.requireFn))),webpack.Template.asString(n)})}),e.hooks.compilation.tap(this.pluginName,t=>{HtmlWebpackPlugin.getHooks(t).beforeAssetTagGeneration.tap(this.pluginName,e=>{const{assets:t,plugin:s,outputName:n}=e,i=s?.options?.chunks||[],r=Array.isArray(i)?i.find(e=>n.includes(ensureSlash(e,!0))):i,{userOptions:o}=e.plugin;if(!r)throw new Error("We must have current chunk!");const a=t.js.filter(e=>e.includes(ensureSlash(r,!0))),l=t.css.filter(e=>e.includes(ensureSlash(r,!0))),p=o.multiCdn,u=t.publicPath,m=a.map(e=>{if(p.disabled)return basename(e);const t=findEnvCdn(this.config,p.env);return httpUrlJoin(t,e.replace(u,""))}),c=l.map(e=>{if(p.disabled)return basename(e);const t=findEnvCdn(this.config,p.env);return httpUrlJoin(t,e.replace(u,""))});return e.assets.js=m,e.assets.css=c,e}),t.hooks.processAssets.tap({name:this.pluginName,stage:e.webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE},s=>{if(e.options.output.library)for(const e of Object.keys(s))e.endsWith(".html")&&delete t.assets[e]})})}}
@@ -1 +1 @@
1
- import HtmlWebpackPlugin from"html-webpack-plugin";import{existsSync}from"node:fs";import{logger,requireResolve}from"@flatjs/common";import{allowPx2remForModule}from"../../../helpers/allow-px2rem-for-module.js";import{checkHtmlTemplateOptions}from"../../../helpers/check-html-template-options.js";import{getHtmlMinOrder}from"../../../helpers/get-html-max-order.js";import{getHtmlPluginConfig}from"../../../helpers/get-html-plugin-config.js";import{normalizeTemplateInjectTokens}from"../../../helpers/normalize-template-inject-tokens.js";import{findEnvCdn}from"../../../helpers/script-injects.js";import{MultiHtmlModifyWebpackPlugin}from"./multi-html-modify-webpack-plugin.js";const minifyOpts={minifyJS:!0,removeComments:!0,collapseWhitespace:!0,collapseBooleanAttributes:!1};export const createMultiHtmlWebpackPlugins=async(e,t,l,i)=>{const o=l[0],[,n]=o,m=[new MultiHtmlModifyWebpackPlugin(t,l)],{options:r}=n,p=e?"development":"production",s=l.map(e=>e[0]);for(const e of i){const l={mode:p,envCdn:findEnvCdn(t.multiHtmlCdn,e)},i=normalizeTemplateInjectTokens(l,r);checkHtmlTemplateOptions(i);const n=i?.headInlineScripts||[],a=getHtmlMinOrder(n);if(allowPx2remForModule(o,t)){const e=getHtmlPluginConfig("viewport",l,r?.viewport);n.unshift({id:"viewport",content:e,position:"end",order:a-1})}let c=getHtmlPluginConfig("templatePath",l,r?.templatePath).replace("{0}",e.trim());existsSync(c)||(logger.warn(`The template file ${c} is not exists, use \`prod\` instead!`),c=getHtmlPluginConfig("templatePath",l,r?.templatePath).replace("{0}","prod"));c=`${requireResolve(import.meta.url,"@hyperse/html-webpack-plugin-loader/loader")}!${c}`,m.push(new HtmlWebpackPlugin({inject:"body",title:getHtmlPluginConfig("title",l,r?.title),chunks:s,minify:!1!==r?.htmlMinify&&!["me","dev"].includes(e)&&minifyOpts,filename:t=>`${t}/index${"prod"===e?"":`-${e}`}.html`,template:c,templateParameters:{title:"",...i,headInlineScripts:n},multiCdn:{env:e,disabled:(r?.excludeCdnEnvs||["me","dev","ntv"]).includes(e)}}))}return m};
1
+ import HtmlWebpackPlugin from"html-webpack-plugin";import{existsSync}from"node:fs";import{logger,requireResolve}from"@flatjs/common";import{allowPx2remForModule}from"../../../helpers/allow-px2rem-for-module.js";import{assertMultiHtmlCdn}from"../../../helpers/assert-multi-html-cdn.js";import{checkHtmlTemplateOptions}from"../../../helpers/check-html-template-options.js";import{getHtmlMinOrder}from"../../../helpers/get-html-max-order.js";import{getHtmlPluginConfig}from"../../../helpers/get-html-plugin-config.js";import{normalizeTemplateInjectTokens}from"../../../helpers/normalize-template-inject-tokens.js";import{findEnvCdn}from"../../../helpers/script-injects.js";import{MultiHtmlModifyWebpackPlugin}from"./multi-html-modify-webpack-plugin.js";const minifyOpts={minifyJS:!0,removeComments:!0,collapseWhitespace:!0,collapseBooleanAttributes:!1};export const createMultiHtmlWebpackPlugins=async(e,t,l,i)=>{const o=l[0],[,n]=o,m=[new MultiHtmlModifyWebpackPlugin(t,l)],{options:r}=n,p=e?"development":"production",s=l.map(e=>e[0]);for(const e of i){const l={mode:p,envCdn:findEnvCdn(assertMultiHtmlCdn(t),e)},i=normalizeTemplateInjectTokens(l,r);checkHtmlTemplateOptions(i);const n=i?.headInlineScripts||[],a=getHtmlMinOrder(n);if(allowPx2remForModule(o,t)){const e=getHtmlPluginConfig("viewport",l,r?.viewport);n.unshift({id:"viewport",content:e,position:"end",order:a-1})}let c=getHtmlPluginConfig("templatePath",l,r?.templatePath).replace("{0}",e.trim());existsSync(c)||(logger.warn(`The template file ${c} is not exists, use \`prod\` instead!`),c=getHtmlPluginConfig("templatePath",l,r?.templatePath).replace("{0}","prod"));c=`${requireResolve(import.meta.url,"@hyperse/html-webpack-plugin-loader/loader")}!${c}`,m.push(new HtmlWebpackPlugin({inject:"body",title:getHtmlPluginConfig("title",l,r?.title),chunks:s,minify:!1!==r?.htmlMinify&&!["me","dev"].includes(e)&&minifyOpts,filename:t=>`${t}/index${"prod"===e?"":`-${e}`}.html`,template:c,templateParameters:{title:"",...i,headInlineScripts:n},multiCdn:{env:e,disabled:(r?.excludeCdnEnvs||["me","dev","ntv"]).includes(e)}}))}return m};
@@ -1,3 +1,13 @@
1
1
  import type { RuleSetRule } from '@rspack/core';
2
2
  import { type EntryMapItem, type FlatEvolveOptions } from '../../types/index.js';
3
- export declare const rspackRuleScripts: (serveMode: boolean, entryMapItem: EntryMapItem, evolveOptions: FlatEvolveOptions) => RuleSetRule;
3
+ /**
4
+ * SWC script rules for rspack.
5
+ *
6
+ * Build: transpile all scripts (incl. `node_modules`) for IE11 / ES5 — unchanged.
7
+ *
8
+ * Serve + HMR: React refresh must NOT run on `node_modules` because
9
+ * `@rspack/plugin-react-refresh` excludes them; otherwise SWC injects
10
+ * `$RefreshReg$` without a definition (e.g. `@rspack/core/hot/emitter.js`).
11
+ * Dependencies are still transpiled, just with `refresh: false`.
12
+ */
13
+ export declare const rspackRuleScripts: (serveMode: boolean, entryMapItem: EntryMapItem, evolveOptions: FlatEvolveOptions) => RuleSetRule[];
@@ -1 +1 @@
1
- import{assertSwcImportOptions}from"@flatjs/babel-plugin-import/helpers";import{requireResolve}from"@flatjs/common";import{shouldEnableReactFastRefresh}from"../../helpers/should-enable-react-fast-refresh.js";export const rspackRuleScripts=(e,r,t)=>{const{loaderOptions:s,projectCwd:o,inspector:a}=t,{modularImports:p=[]}=s,l=assertSwcImportOptions(o,p),m=shouldEnableReactFastRefresh(e,r,t),n=[];return n.push([requireResolve(import.meta.url,"@flatjs/swc-plugin-import"),{modularImports:l}]),e&&a&&n.push(["@hyperse/inspector-swc-plugin",{projectCwd:o}]),{test:/\.(jsx|tsx|ts|js|mjs|cjs|mts|cts)$/,use:[{loader:"builtin:swc-loader",options:{isModule:"unknown",jsc:{parser:{decorators:!0,syntax:"typescript",tsx:!0},externalHelpers:!0,experimental:{keepImportAttributes:!0,plugins:[...n]},transform:{legacyDecorator:!0,react:{runtime:"automatic",pragma:"React.createElement",pragmaFrag:"React.Fragment",throwIfNamespace:!0,development:m,refresh:m}}},env:{mode:"entry",targets:{browsers:["ie >= 11","safari > 10"]}}}}]}};
1
+ import{assertSwcImportOptions}from"@flatjs/babel-plugin-import/helpers";import{requireResolve}from"@flatjs/common";import{shouldEnableReactFastRefresh}from"../../helpers/should-enable-react-fast-refresh.js";const scriptTest=/\.(jsx|tsx|ts|js|mjs|cjs|mts|cts)$/,nodeModules=/[\\/]node_modules[\\/]/;export const rspackRuleScripts=(e,s,t)=>{const{loaderOptions:r,projectCwd:o,inspector:a}=t,{modularImports:p=[]}=r,l=assertSwcImportOptions(o,p),n=shouldEnableReactFastRefresh(e,s,t),c=[];c.push([requireResolve(import.meta.url,"@flatjs/swc-plugin-import"),{modularImports:l}]),e&&a&&c.push(["@hyperse/inspector-swc-plugin",{projectCwd:o}]);const createSwcRule=(e,s={})=>({test:scriptTest,...s,use:[{loader:"builtin:swc-loader",options:{isModule:"unknown",jsc:{parser:{decorators:!0,syntax:"typescript",tsx:!0},externalHelpers:!0,experimental:{keepImportAttributes:!0,plugins:[...c]},transform:{legacyDecorator:!0,react:{runtime:"automatic",pragma:"React.createElement",pragmaFrag:"React.Fragment",throwIfNamespace:!0,development:e,refresh:e}}},env:{mode:"entry",targets:{browsers:["ie >= 11","safari > 10"]}}}}]});return e?[createSwcRule(n,{exclude:nodeModules}),createSwcRule(!1,{include:nodeModules})]:[createSwcRule(!1)]};
@@ -71,12 +71,17 @@ export interface FlatEvolveOptions {
71
71
  * The configurations of `dev-server`.
72
72
  */
73
73
  devServer?: FlatEvolveDevServerOptions;
74
+ /**
75
+ * The channel of build environment.
76
+ * @default 'default'
77
+ */
78
+ channel?: FlatEvolveChannel;
74
79
  /**
75
80
  * We can define multiple `CDN` for my project.
76
81
  * --
77
82
  * Note: We do not support `//` as prefix please use `https://` or `http://`
78
83
  */
79
- multiHtmlCdn: EvolveMultiCDNConfig;
84
+ multiHtmlCdn: EvolveMultiCDNConfig | ((channel: FlatEvolveChannel) => EvolveMultiCDNConfig);
80
85
  /**
81
86
  * Allow us customized to resolve current runtime environment.
82
87
  * ignore resolver if return undefined, otherwise use it to match environment.
@@ -191,3 +196,4 @@ export interface FlatEvolveOptions {
191
196
  */
192
197
  codeChecker?: CodeCheckerPluginOptions;
193
198
  }
199
+ export type FlatEvolveChannel = 'default' | string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flatjs/evolve",
3
- "version": "3.0.15",
3
+ "version": "3.1.0-next.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -47,82 +47,83 @@
47
47
  "@armit/git": "^0.3.0",
48
48
  "@armit/package": "^0.3.1",
49
49
  "@babel/core": "^7.28.4",
50
- "@clack/prompts": "^0.11.0",
51
- "@discoveryjs/json-ext": "0.6.3",
52
- "@flatjs/babel-plugin-import": "2.2.10",
53
- "@flatjs/common": "2.2.5",
54
- "@flatjs/evolve-preset-babel": "2.2.5",
55
- "@flatjs/forge-postcss-plugin-pixel": "2.2.5",
56
- "@flatjs/forge-ts-checker": "1.1.3",
57
- "@flatjs/graph": "2.2.10",
58
- "@flatjs/mock": "2.4.2",
59
- "@flatjs/swc-plugin-import": "1.0.4",
60
- "@hyperse/config-loader": "^1.0.8",
61
- "@hyperse/html-webpack-plugin-loader": "^1.0.7",
62
- "@hyperse/inspector": "^2.0.1",
63
- "@hyperse/inspector-babel-plugin": "^2.0.1",
64
- "@hyperse/inspector-common": "^2.0.1",
65
- "@hyperse/inspector-middleware": "^2.0.1",
66
- "@hyperse/inspector-swc-plugin": "^2.0.1",
67
- "@pmmmwh/react-refresh-webpack-plugin": "^0.6.1",
68
- "@rsdoctor/rspack-plugin": "^1.3.2",
69
- "@rspack/core": "~1.7.1",
70
- "@rspack/dev-server": "~1.1.5",
71
- "@rspack/plugin-react-refresh": "^1.6.0",
72
- "@swc/helpers": "^0.5.17",
50
+ "@clack/prompts": "^1.6.0",
51
+ "@discoveryjs/json-ext": "1.1.0",
52
+ "@flatjs/babel-plugin-import": "2.3.0-next.0",
53
+ "@flatjs/common": "2.3.0-next.0",
54
+ "@flatjs/evolve-preset-babel": "2.3.0-next.0",
55
+ "@flatjs/forge-postcss-plugin-pixel": "2.3.0-next.0",
56
+ "@flatjs/forge-ts-checker": "1.2.0-next.0",
57
+ "@flatjs/graph": "2.3.0-next.0",
58
+ "@flatjs/mock": "2.5.0-next.0",
59
+ "@flatjs/swc-plugin-import": "1.1.0-next.0",
60
+ "@hyperse/config-loader": "^1.0.9",
61
+ "@hyperse/html-webpack-plugin-loader": "^1.0.8",
62
+ "@hyperse/inspector": "^2.0.3",
63
+ "@hyperse/inspector-babel-plugin": "^2.0.3",
64
+ "@hyperse/inspector-common": "^2.0.3",
65
+ "@hyperse/inspector-middleware": "^2.0.3",
66
+ "@hyperse/inspector-swc-plugin": "^2.0.3",
67
+ "@module-federation/runtime-tools": "^2.8.0",
68
+ "@pmmmwh/react-refresh-webpack-plugin": "^0.6.2",
69
+ "@rsdoctor/rspack-plugin": "^1.5.17",
70
+ "@rspack/core": "~2.1.4",
71
+ "@rspack/dev-server": "~2.1.0",
72
+ "@rspack/plugin-react-refresh": "^2.0.2",
73
+ "@swc/helpers": "^0.5.23",
73
74
  "@types/babel__core": "^7.20.5",
74
- "babel-loader": "^10.0.0",
75
+ "babel-loader": "^10.1.1",
75
76
  "better-opn": "^3.0.2",
76
77
  "case-sensitive-paths-webpack-plugin": "^2.4.0",
77
- "chokidar": "^4.0.3",
78
- "ci-info": "^4.3.1",
79
- "css-loader": "^7.1.2",
80
- "cssnano": "^7.1.1",
81
- "express": "^5.1.0",
78
+ "chokidar": "^5.0.0",
79
+ "ci-info": "^4.4.0",
80
+ "css-loader": "^7.1.4",
81
+ "cssnano": "^8.0.2",
82
+ "express": "^5.2.1",
82
83
  "fast-glob": "^3.3.3",
83
84
  "fork-ts-checker-webpack-plugin": "^9.1.0",
84
- "happy-dom": "^20.0.1",
85
- "html-webpack-plugin": "^5.6.4",
86
- "image-minimizer-webpack-plugin": "^4.1.4",
87
- "less": "^4.4.2",
88
- "less-loader": "^12.3.0",
85
+ "happy-dom": "^20.10.6",
86
+ "html-webpack-plugin": "^5.6.7",
87
+ "image-minimizer-webpack-plugin": "^5.0.0",
88
+ "less": "^4.6.7",
89
+ "less-loader": "^13.0.0",
89
90
  "listr": "^0.14.3",
90
- "lodash": "^4.17.21",
91
- "log-update": "^7.0.1",
92
- "mini-css-extract-plugin": "^2.9.4",
93
- "postcss": "^8.5.6",
94
- "postcss-loader": "^8.2.0",
91
+ "lodash": "^4.18.1",
92
+ "log-update": "^8.0.0",
93
+ "mini-css-extract-plugin": "^2.10.2",
94
+ "postcss": "8.5.16",
95
+ "postcss-loader": "^8.2.1",
95
96
  "react-refresh": "^0.18.0",
96
- "svgo": "^4.0.0",
97
+ "svgo": "^4.0.1",
97
98
  "tarjan-graph": "^3.0.0",
98
- "terser-webpack-plugin": "^5.3.15",
99
- "tinypool": "^2.0.0",
99
+ "terser-webpack-plugin": "^5.6.1",
100
+ "tinypool": "2.0.0",
100
101
  "tsconfig-paths-webpack-plugin": "^4.2.0",
101
- "type-fest": "^4.41.0",
102
- "typescript": "^5.9.3",
103
- "webpack": "5.103.0",
104
- "webpack-bundle-analyzer": "^5.1.0",
105
- "webpack-dev-server": "^5.2.2",
106
- "webpack-sources": "^3.3.3"
102
+ "type-fest": "^5.7.0",
103
+ "typescript": "^6.0.3",
104
+ "webpack": "5.108.3",
105
+ "webpack-bundle-analyzer": "^5.3.1",
106
+ "webpack-dev-server": "^5.2.5",
107
+ "webpack-sources": "^3.5.0"
107
108
  },
108
109
  "devDependencies": {
109
- "@flatjs/testing": "2.2.5",
110
- "@hyperse/eslint-config-hyperse": "^1.4.8",
111
- "@swc/core": "1.15.5",
112
- "@types/express": "5.0.3",
113
- "@types/listr": "0.14.9",
114
- "@types/node": "24.7.2",
115
- "@types/react": "19.2.2",
116
- "eslint": "^9.37.0",
110
+ "@flatjs/testing": "2.3.0-next.0",
111
+ "@hyperse/eslint-config-hyperse": "^1.7.3",
112
+ "@swc/core": "1.15.43",
113
+ "@types/express": "5.0.6",
114
+ "@types/listr": "0.14.10",
115
+ "@types/node": "26.0.1",
116
+ "@types/react": "19.2.17",
117
+ "@types/react-dom": "19.2.3",
118
+ "eslint": "^10.6.0",
117
119
  "imagemin-gifsicle": "7.0.0",
118
120
  "imagemin-jpegtran": "8.0.0",
119
121
  "imagemin-pngquant": "10.0.0",
120
- "imagemin-svgo": "11.0.1",
122
+ "imagemin-svgo": "12.0.0",
121
123
  "npm-run-all": "4.1.5",
122
- "react": "19.2.3",
123
- "rimraf": "6.0.1",
124
- "vite-tsconfig-paths": "5.1.4",
125
- "vitest": "3.2.4",
124
+ "react": "19.2.7",
125
+ "rimraf": "6.1.3",
126
+ "vitest": "4.1.9",
126
127
  "vue-loader": "17.4.2"
127
128
  },
128
129
  "peerDependencies": {