UNPKG

webpack-v5-chain

Version:

Use a chaining API to generate and simplify the modification of webpack 5 configurations.

5 lines (4 loc) 15.4 kB
"use strict";var _=require("javascript-stringify"),w=require("deepmerge");const d=t=>class extends t{constructor(e){super(),this.parent=e}batch(e){return e(this),this}end(){return this.parent}},x=t=>class extends t{constructor(...e){super(...e),this.store=new Map}extend(e){return this.shorthands=e,e.forEach(r=>{this[r]=i=>this.set(r,i)}),this}clear(){return this.store.clear(),this}delete(e){return this.store.delete(e),this}order(){const e=[...this.store].reduce((s,[u,l])=>(s[u]=l,s),{}),r=Object.keys(e),i=[...r];return r.forEach(s=>{if(!e[s])return;const{__before:u,__after:l}=e[s];u&&i.includes(u)?(i.splice(i.indexOf(s),1),i.splice(i.indexOf(u),0,s)):l&&i.includes(l)&&(i.splice(i.indexOf(s),1),i.splice(i.indexOf(l)+1,0,s))}),{entries:e,order:i}}entries(){const{entries:e,order:r}=this.order();if(r.length)return e}values(){const{entries:e,order:r}=this.order();return r.map(i=>e[i])}get(e){return this.store.get(e)}getOrCompute(e,r){return this.has(e)||this.set(e,r()),this.get(e)}has(e){return this.store.has(e)}set(e,r){return this.store.set(e,r),this}merge(e,r=[]){return Object.keys(e).forEach(i=>{if(r.includes(i))return;const s=e[i];!Array.isArray(s)&&typeof s!="object"||s===null||!this.has(i)?this.set(i,s):this.set(i,w(this.get(i),s))}),this}clean(e){return Object.keys(e).reduce((r,i)=>{const s=e[i];return s===void 0||Array.isArray(s)&&!s.length||Object.prototype.toString.call(s)==="[object Object]"&&!Object.keys(s).length||(r[i]=s),r},{})}when(e,r=Function.prototype,i=Function.prototype){return e?r(this):i(this),this}},n=x(d(Object)),O=t=>class extends t{constructor(...e){super(...e),this.store=new Set}add(e){return this.store.add(e),this}prepend(e){return this.store=new Set([e,...this.store]),this}clear(){return this.store.clear(),this}delete(e){return this.store.delete(e),this}values(){return[...this.store]}has(e){return this.store.has(e)}merge(e){return this.store=new Set([...this.store,...e]),this}when(e,r=Function.prototype,i=Function.prototype){return e?r(this):i(this),this}},o=O(d(Object));class F extends Function{constructor(){return super(),new Proxy(this,{apply:(e,r,i)=>e.classCall(...i)})}classCall(){throw new Error("not implemented")}}const k=t=>class extends t{constructor(...e){super(...e),this.value=void 0,this.useMap=!0}set(...e){return this.useMap=!0,this.value=void 0,super.set(...e)}clear(){return this.value=void 0,super.clear()}classCall(e){return this.clear(),this.useMap=!1,this.value=e,this.parent}entries(){return this.useMap?super.entries():this.value}values(){return this.useMap?super.values():this.value}},b=k(x(d(F))),m=t=>class extends t{before(e){if(this.__after)throw new Error(`Unable to set .before(${JSON.stringify(e)}) with existing value for .after()`);return this.__before=e,this}after(e){if(this.__before)throw new Error(`Unable to set .after(${JSON.stringify(e)}) with existing value for .before()`);return this.__after=e,this}merge(e,r=[]){return e.before&&this.before(e.before),e.after&&this.after(e.after),super.merge(e,[...r,"before","after"])}};class E extends n{constructor(e){super(e),this.allowedHosts=new o(this),this.extend(["after","before","app","bonjour","client","compress","devMiddleware","headers","historyApiFallback","host","hot","ipc","liveReload","onListening","open","port","proxy","server","setupExitSignals","setupMiddlewares","static","watchFiles","webSocketServer"])}toConfig(){return this.clean({allowedHosts:this.allowedHosts.values(),...this.entries()||{}})}merge(e,r=[]){return!r.includes("allowedHosts")&&"allowedHosts"in e&&this.allowedHosts.merge(e.allowedHosts),super.merge(e,["allowedHosts"])}}const g=m(class extends n{constructor(t,e,r="plugin"){super(t),this.name=e,this.type=r,this.extend(["init"]),this.init((i,s=[])=>typeof i=="function"?new i(...s):i)}use(t,e=[]){return this.set("plugin",t).set("args",e)}tap(t){if(!this.has("plugin"))throw new Error(`Cannot call .tap() on a plugin that has not yet been defined. Call ${this.type}('${this.name}').use(<Plugin>) first.`);return this.set("args",t(this.get("args")||[])),this}set(t,e){if(t==="args"&&!Array.isArray(e))throw new Error("args must be an array of arguments");return super.set(t,e)}merge(t,e=[]){return"plugin"in t&&this.set("plugin",t.plugin),"args"in t&&this.set("args",t.args),super.merge(t,[...e,"args","plugin"])}toConfig(){const t=this.get("init");let e=this.get("plugin");const r=this.get("args");let i=null;if(e===void 0)throw new Error(`Invalid ${this.type} configuration: ${this.type}('${this.name}').use(<Plugin>) was not called to specify the plugin`);typeof e=="string"&&(i=e,e=require(i));const s=e.__expression?`(${e.__expression})`:e.name,u=t(e,r);return Object.defineProperties(u,{__pluginName:{value:this.name},__pluginType:{value:this.type},__pluginArgs:{value:r},__pluginConstructorName:{value:s},__pluginPath:{value:i}}),u}});class f extends n{constructor(e){super(e),this.alias=new n(this),this.aliasFields=new o(this),this.byDependency=new n(this),this.conditionNames=new o(this),this.descriptionFiles=new o(this),this.exportsFields=new o(this),this.extensionAlias=new n(this),this.extensions=new o(this),this.fallback=new n(this),this.importsFields=new o(this),this.mainFields=new o(this),this.mainFiles=new o(this),this.modules=new o(this),this.plugins=new n(this),this.restrictions=new o(this),this.roots=new o(this),this.extend(["cache","cachePredicate","cacheWithContext","enforceExtension","fullySpecified","preferAbsolute","preferRelative","symlinks","unsafeCache","useSyncFileSystemCalls"])}plugin(e){return this.plugins.getOrCompute(e,()=>new g(this,e,"resolve.plugin"))}toConfig(){return this.clean(Object.assign(this.entries()||{},{alias:this.alias.entries(),aliasFields:this.aliasFields.values(),byDependency:this.byDependency.entries(),conditionNames:this.conditionNames.values(),descriptionFiles:this.descriptionFiles.values(),exportsFields:this.exportsFields.values(),extensionAlias:this.extensionAlias.entries(),extensions:this.extensions.values(),fallback:this.fallback.entries(),importsFields:this.importsFields.values(),mainFields:this.mainFields.values(),mainFiles:this.mainFiles.values(),modules:this.modules.values(),plugins:this.plugins.values().map(e=>e.toConfig()),restrictions:this.restrictions.values(),roots:this.roots.values()}))}merge(e,r=[]){const i=["alias","aliasFields","byDependency","conditionNames","descriptionFiles","exportsFields","extensionAlias","extensions","importsFields","mainFields","mainFiles","modules","restrictions","roots"];return!r.includes("plugin")&&"plugin"in e&&Object.keys(e.plugin).forEach(s=>this.plugin(s).merge(e.plugin[s])),i.forEach(s=>{!r.includes(s)&&s in e&&this[s].merge(e[s])}),super.merge(e,[...r,...i,"plugin"])}}const j=m(class extends n{constructor(t,e){super(t),this.name=e,this.extend(["loader","options"])}tap(t){return this.options(t(this.get("options"))),this}merge(t,e=[]){return!e.includes("loader")&&"loader"in t&&this.loader(t.loader),!e.includes("options")&&"options"in t&&this.options(w(this.store.get("options")||{},t.options)),super.merge(t,[...e,"loader","options"])}toConfig(){var t,e;const r=this.clean(this.entries()||{});return Object.defineProperties(r,{__useName:{value:this.name},__ruleNames:{value:(t=this.parent)==null?void 0:t.names},__ruleTypes:{value:(e=this.parent)==null?void 0:e.ruleTypes}}),r}}),C=t=>Array.isArray(t)?t:[t],h=m(class extends n{constructor(t,e,r="rule"){super(t),this.ruleName=e,this.names=[],this.ruleType=r,this.ruleTypes=[];let i=this;for(;i instanceof h;)this.names.unshift(i.ruleName),this.ruleTypes.unshift(i.ruleType),i=i.parent;this.uses=new n(this),this.include=new o(this),this.exclude=new o(this),this.rules=new n(this),this.oneOfs=new n(this),this.resolve=new f(this),this.resolve.extend(["fullySpecified"]),this.extend(["assert","compiler","enforce","issuer","issuerLayer","layer","mimetype","parser","generator","resource","resourceQuery","scheme","sideEffects","test","type","width"])}use(t){return this.uses.getOrCompute(t,()=>new j(this,t))}rule(t){return this.rules.getOrCompute(t,()=>new h(this,t,"rule"))}oneOf(t){return this.oneOfs.getOrCompute(t,()=>new h(this,t,"oneOf"))}pre(){return this.enforce("pre")}post(){return this.enforce("post")}toConfig(){const t=this.clean(Object.assign(this.entries()||{},{include:this.include.values(),exclude:this.exclude.values(),rules:this.rules.values().map(e=>e.toConfig()),oneOf:this.oneOfs.values().map(e=>e.toConfig()),use:this.uses.values().map(e=>e.toConfig()),resolve:this.resolve.toConfig()}));return Object.defineProperties(t,{__ruleNames:{value:this.names},__ruleTypes:{value:this.ruleTypes}}),t}merge(t,e=[]){return!e.includes("include")&&"include"in t&&this.include.merge(C(t.include)),!e.includes("exclude")&&"exclude"in t&&this.exclude.merge(C(t.exclude)),!e.includes("use")&&"use"in t&&Object.keys(t.use).forEach(r=>this.use(r).merge(t.use[r])),!e.includes("rules")&&"rules"in t&&Object.keys(t.rules).forEach(r=>this.rule(r).merge(t.rules[r])),!e.includes("oneOf")&&"oneOf"in t&&Object.keys(t.oneOf).forEach(r=>this.oneOf(r).merge(t.oneOf[r])),!e.includes("resolve")&&"resolve"in t&&this.resolve.merge(t.resolve),!e.includes("test")&&"test"in t&&this.test(t.test instanceof RegExp||typeof t.test=="function"?t.test:new RegExp(t.test)),super.merge(t,[...e,"include","exclude","use","rules","oneOf","resolve","test"])}});class S extends n{constructor(e){super(e),this.rules=new n(this),this.defaultRules=new n(this),this.generator=new n(this),this.parser=new n(this),this.extend(["noParse","unsafeCache","exprContextCritical","exprContextRecursive","exprContextRegExp","unknownContextCritical","unknownContextRecursive","unknownContextRegExp","unknownContextRequest","wrappedContextCritical","wrappedContextRecursive","wrappedContextRegExp","strictExportPresence"])}defaultRule(e){return this.defaultRules.getOrCompute(e,()=>new h(this,e,"defaultRule"))}rule(e){return this.rules.getOrCompute(e,()=>new h(this,e,"rule"))}toConfig(){return this.clean(Object.assign(this.entries()||{},{defaultRules:this.defaultRules.values().map(e=>e.toConfig()),generator:this.generator.entries(),parser:this.parser.entries(),rules:this.rules.values().map(e=>e.toConfig())}))}merge(e,r=[]){return!r.includes("rule")&&"rule"in e&&Object.keys(e.rule).forEach(i=>this.rule(i).merge(e.rule[i])),!r.includes("defaultRule")&&"defaultRule"in e&&Object.keys(e.defaultRule).forEach(i=>this.defaultRule(i).merge(e.defaultRule[i])),super.merge(e,["rule","defaultRule"])}}class R extends n{constructor(e){super(e),this.minimizers=new n(this),this.splitChunks=new b(this),this.extend(["checkWasmTypes","chunkIds","concatenateModules","emitOnErrors","avoidEntryIife","flagIncludedChunks","innerGraph","mangleExports","mangleWasmImports","mergeDuplicateChunks","minimize","moduleIds","nodeEnv","portableRecords","providedExports","realContentHash","removeAvailableModules","removeEmptyChunks","runtimeChunk","sideEffects","usedExports"])}minimizer(e){return this.minimizers.getOrCompute(e,()=>new g(this,e,"optimization.minimizer"))}toConfig(){return this.clean(Object.assign(this.entries()||{},{splitChunks:this.splitChunks.entries(),minimizer:this.minimizers.values().map(e=>e.toConfig())}))}merge(e,r=[]){return!r.includes("minimizer")&&"minimizer"in e&&Object.keys(e.minimizer).forEach(i=>this.minimizer(i).merge(e.minimizer[i])),super.merge(e,[...r,"minimizer"])}}class P extends n{constructor(e){super(e),this.extend(["assetModuleFilename","asyncChunks","auxiliaryComment","charset","chunkFilename","chunkFormat","chunkLoadTimeout","chunkLoadingGlobal","chunkLoading","clean","compareBeforeEmit","crossOriginLoading","cssChunkFilename","cssFilename","devtoolFallbackModuleFilenameTemplate","devtoolModuleFilenameTemplate","devtoolNamespace","enabledChunkLoadingTypes","enabledLibraryTypes","enabledWasmLoadingTypes","environment","filename","globalObject","hashDigest","hashDigestLength","hashFunction","hashSalt","hotUpdateChunkFilename","hotUpdateGlobal","hotUpdateMainFilename","iife","ignoreBrowserWarnings","importFunctionName","importMetaName","library","libraryExport","libraryTarget","module","path","pathinfo","publicPath","scriptType","sourceMapFilename","sourcePrefix","strictModuleErrorHandling","strictModuleExceptionHandling","trustedTypes","umdNamedDefine","uniqueName","wasmLoading","webassemblyModuleFilename","workerChunkLoading","workerPublicPath","workerWasmLoading"])}}class N extends b{constructor(e){super(e),this.extend(["assetFilter","hints","maxAssetSize","maxEntrypointSize"])}}class M extends f{constructor(e){super(e),this.extensions=new o(this),this.mainFields=new o(this),this.modules=new o(this)}toConfig(){return this.clean({extensions:this.extensions.values(),mainFields:this.mainFields.values(),modules:this.modules.values(),...super.toConfig()})}merge(e,r=[]){const i=["extensions","mainFields","modules"];return i.forEach(s=>{!r.includes(s)&&s in e&&this[s].merge(e[s])}),super.merge(e,[...r,...i])}}class v extends n{constructor(){super(),this.entryPoints=new n(this),this.output=new P(this),this.module=new S(this),this.resolve=new f(this),this.resolveLoader=new M(this),this.optimization=new R(this),this.plugins=new n(this),this.devServer=new E(this),this.performance=new N(this),this.extend(["context","mode","cache","devtool","target","watch","watchOptions","externals","externalsType","externalsPresets","node","stats","experiments","infrastructureLogging","amd","bail","dependencies","ignoreWarnings","loader","name","parallelism","profile","recordsInputPath","recordsOutputPath","recordsPath","snapshot"])}static toString(e,{verbose:r=!1,configPrefix:i="config"}={}){return _.stringify(e,(s,u,l)=>{var y;if(s!=null&&s.__pluginName){const a=`/* ${i}.${s.__pluginType}('${s.__pluginName}') */ `,c=s.__pluginPath?`(require(${l(s.__pluginPath)}))`:s.__pluginConstructorName;if(c){const p=l(s.__pluginArgs).slice(1,-1);return`${a}new ${c}(${p})`}return a+l((y=s.__pluginArgs)!=null&&y.length?{args:s.__pluginArgs}:{})}if(s!=null&&s.__ruleNames){const a=s.__ruleTypes;return`/* ${i}.module${s.__ruleNames.map((c,p)=>`.${a?a[p]:"rule"}('${c}')`).join("")}${s.__useName?`.use('${s.__useName}')`:""} */ `+l(s)}return s!=null&&s.__expression?s.__expression:typeof s=="function"&&!r&&s.toString().length>100?"function () { /* omitted long function */ }":l(s)},2)}entry(e){return this.entryPoints.getOrCompute(e,()=>new o(this))}plugin(e){return this.plugins.getOrCompute(e,()=>new g(this,e))}toConfig(){const e=this.entryPoints.entries()||{},r=this.entries()||{};return this.clean(Object.assign(r,{output:this.output.entries(),resolve:this.resolve.toConfig(),resolveLoader:this.resolveLoader.toConfig(),devServer:this.devServer.toConfig(),module:this.module.toConfig(),optimization:this.optimization.toConfig(),plugins:this.plugins.values().map(i=>i.toConfig()),performance:this.performance.entries(),entry:Object.keys(e).reduce((i,s)=>Object.assign(i,{[s]:e[s].values()}),{})}))}toString(e){return v.toString(this.toConfig(),e)}merge(e={},r=[]){const i=["output","resolve","resolveLoader","devServer","optimization","performance","module"];return!r.includes("entry")&&"entry"in e&&Object.keys(e.entry).forEach(s=>this.entry(s).merge([].concat(e.entry[s]))),!r.includes("plugin")&&"plugin"in e&&Object.keys(e.plugin).forEach(s=>this.plugin(s).merge(e.plugin[s])),i.forEach(s=>{!r.includes(s)&&s in e&&this[s].merge(e[s])}),super.merge(e,[...r,...i,"entry","plugin"])}}exports.Config=v; //# sourceMappingURL=index.js.map