moduloze
Version:
Convert CommonJS (CJS) modules to UMD and ESM formats
5 lines • 35.2 kB
JavaScript
/*! Moduloze: bundle.js
v0.9.1 (c) 2022 Kyle Simpson
MIT License: http://getify.mit-license.org
*/
!function UMDBundle(e,t){for(let[r,i,n]of t)"function"==typeof define&&define.amd?(i=Object.values(i),define(r,i,n)):"undefined"!=typeof module&&module.exports?(i=Object.entries(i).map((([e,t])=>module.exports[t]||require(e))),module.exports[r]=n(...i)):(i=Object.values(i).map((t=>e[t])),e[r]=n(...i))}("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:new Function("return this")(),[["Helpers",{path:"NodePath",fs:"NodeFS",os:"NodeOS","@babel/types":"BabelTypes"},function DEF(e,t,r,i){"use strict";var n=e,o=t,s=r,a=i;let p={findParentStatement:function findParentStatement(e){return a.isProgram(e.node)?null:a.isStatement(e.node)?e:findParentStatement(e.parentPath)}};p.isFunction=isFunction,p.isAssignmentTarget=function isAssignmentTarget(e){return!(a.isProgram(e.node)||a.isStatement(e.node)||isFunction(e)||a.isAssignmentPattern(e.node))&&(a.isAssignmentExpression(e.parent)?e.parent.left==e.node:isAssignmentTarget(e.parentPath))},p.expandHomeDir=expandHomeDir,p.addRelativeCurrentDir=function addRelativeCurrentDir(e){return n.isAbsolute(e)||/^(?:(?:\.+[/\\]+)|(?:~(?:[/\\].*)$))/.test(e)?e:`./${e}`},p.rootRelativePath=rootRelativePath,p.qualifyDepPaths=function qualifyDepPaths(e,t){var r=new Set,i={};for(let[o,s]of Object.entries(e)){if(r.has(s))throw new Error(`Dependency-map name conflict: ${s}`);{r.add(s);let e=n.resolve(t,expandHomeDir(o)),a=rootRelativePath(t,e);i[a]=s}}return i},p.isPathBasedSpecifier=function isPathBasedSpecifier(e){return/^(\.{0,2}|([a-z]+:)|~)[\/\\]/i.test(e)&&/\.[a-z]+$/.test(e)},p.isDirectory=function isDirectory(e){return checkPath(e)&&o.lstatSync(e).isDirectory()},p.checkPath=checkPath,p.generateName=function generateName(){do{var e=`Mz_${Math.round(1e9*Math.random())}`}while(e in d);return d[e]=!0,e};var l=s.homedir(),d={};function isFunction(e){return a.isFunctionDeclaration(e.node)||a.isFunctionExpression(e.node)}function expandHomeDir(e){return"~"!=e[0]||1!=e.length&&"/"!=e[1]||(e=e.replace(/^~/,l)),e}function rootRelativePath(e,t){var r=n.resolve(e,t);return n.relative(e,r)}function checkPath(e){return o.existsSync(e)}return p}],["Analysis",{"@babel/traverse":"BabelTraverse","@babel/types":"BabelTypes","@babel/parser":"BableParser","./helpers.js":"Helpers"},function DEF(e,t,r,i){"use strict";var{default:n}=e,o=t,{parse:s}=r,{findParentStatement:a,isFunction:p,isAssignmentTarget:l}=i;let d={};function analyzeRequires(e,t){var r=[];for(let i of e){if(!o.isProgram(i.parent))throw new Error("Require statements must be at the top-level of the program");let e=[...t.get(i)];if(o.isExpressionStatement(i.node)&&o.isCallExpression(i.node.expression)&&1==e.length&&e[0].node==i.node.expression){e[0]=!1;let t=i.node.expression.arguments[0].extra.rawValue;r.push({esmType:"bare-import",umdType:"remove-require-unique",specifier:t,context:{statement:i}})}else if(o.isVariableDeclaration(i.node))for(let[t,n]of i.node.declarations.entries()){if(!hasRequireCalls(i,n.init,e))continue;let s=i.get(`declarations.${t}`);if(o.isIdentifier(n.id)){if(o.isCallExpression(n.init)&&e.find((e=>e.node==n.init))){e[e.findIndex((e=>e.node==n.init))]=!1;let o=s.get("init"),a=o.node.arguments[0].extra.rawValue;r.push({esmType:"default-import",umdType:"default-require",binding:{target:n.id.name},specifier:a,context:{statement:i,declarator:s,declarationIdx:t,requireCall:o}})}else if(isSimpleMemberExpression(n.init,n)&&e.find((e=>e.node==n.init.object))){e[e.findIndex((e=>e.node==n.init.object))]=!1;let a=s.get("init.object"),p=a.node.arguments[0].extra.rawValue,l=n.id.name,d=o.isIdentifier(n.init.property)?n.init.property.name:o.isStringLiteral(n.init.property)?n.init.property.value:void 0;r.push({esmType:"named-import",umdType:"named-dependency",binding:{source:d,target:l},specifier:p,context:{statement:i,declarator:s,declarationIdx:t,requireCall:a}})}}else if(o.isObjectPattern(n.id)&&o.isCallExpression(n.init)&&e.find((e=>e.node==n.init))){e[e.findIndex((e=>e.node==n.init))]=!1;let a=s.get("init"),p=a.node.arguments[0].extra.rawValue,l=n.id,d=[];for(let e of l.properties){if(e.computed||!o.isIdentifier(e.value))throw new Error("Unsupported: destructuring pattern not ESM import-compatible");{let t=o.isIdentifier(e.key)?e.key.name:o.isStringLiteral(e.key)?e.key.value:void 0;d.push({source:t,target:e.value.name})}}r.push({esmType:"named-import",umdType:"destructured-dependency",binding:d,specifier:p,context:{statement:i,declarator:s,declarationIdx:t,requireCall:a}})}}else if(o.isExpressionStatement(i.node)&&o.isAssignmentExpression(i.node.expression)){let t=i.node.expression;if(o.isIdentifier(t.left)){if(e.find((e=>e.node==t.right))){e[e.findIndex((e=>e.node==t.right))]=!1;let n=i.get("expression.right"),o=n.node.arguments[0].extra.rawValue,s=t.left.name;r.push({esmType:"default-import-indirect",umdType:"indirect-target",binding:{source:"default",target:s,uniqueTarget:i.scope.generateUidIdentifier("imp").name},specifier:o,context:{statement:i,requireCall:n}})}else if(isSimpleMemberExpression(t.right,t)&&e.find((e=>e.node==t.right.object))){e[e.findIndex((e=>e.node==t.right.object))]=!1;let n=i.get("expression.right.object"),s=n.node.arguments[0].extra.rawValue,a=t.left.name,p=o.isIdentifier(t.right.property)?t.right.property.name:o.isStringLiteral(t.right.property)?t.right.property.value:void 0;r.push({esmType:"named-import-indirect",umdType:"indirect-source-target",binding:{source:p,target:a,uniqueTarget:i.scope.generateUidIdentifier("imp").name},specifier:s,context:{statement:i,requireCall:n}})}}else if(o.isObjectPattern(t.left)&&e.find((e=>e.node==t.right))){e[e.findIndex((e=>e.node==t.right))]=!1;let n=i.get("expression.right"),s=n.node.arguments[0].extra.rawValue,a=t.left,p=[];for(let e of a.properties){if(e.computed||!o.isIdentifier(e.value))throw new Error("Unsupported: destructuring pattern not ESM import-compatible");{let t=o.isIdentifier(e.key)?e.key.name:o.isStringLiteral(e.key)?e.key.value:void 0;p.push({source:t,target:e.value.name,uniqueTarget:i.scope.generateUidIdentifier("imp").name})}}p.length>0&&r.push({esmType:"named-import-indirect",umdType:"indirect-source-target",binding:p,specifier:s,context:{statement:i,requireCall:n}})}else if(isModuleExports(t.left)||isSimpleMemberExpression(t.left,t)&&isModuleExports(t.left.object)){let n=t.left;if(e.find((e=>e.node==t.right))){e[e.findIndex((e=>e.node==t.right))]=!1;let o=i.get("expression.right"),s=o.node.arguments[0].extra.rawValue;r.push({esmType:"default-import-indirect",umdType:"indirect-target",binding:{source:"default",target:n,uniqueTarget:i.scope.generateUidIdentifier("imp").name},specifier:s,context:{statement:i,requireCall:o}})}else if(isSimpleMemberExpression(t.right,t)&&e.find((e=>e.node==t.right.object))){e[e.findIndex((e=>e.node==t.right.object))]=!1;let s=i.get("expression.right.object"),a=s.node.arguments[0].extra.rawValue,p=o.isIdentifier(t.right.property)?t.right.property.name:o.isStringLiteral(t.right.property)?t.right.property.value:void 0;r.push({esmType:"named-import-indirect",umdType:"indirect-source-target",binding:{source:p,target:n,uniqueTarget:i.scope.generateUidIdentifier("imp").name},specifier:a,context:{statement:i,requireCall:s}})}}}e=e.filter(Boolean),e.length>0&&(r=[...r,...e.map((function handleReqCall(e){return analyzeRequireSubstitutions(i,e)}))])}return r}function analyzeRequireSubstitutions(e,t){var r=t.node.arguments[0].extra.rawValue;if(isSimpleMemberExpression(t.parent,t.parentPath.parent)){return{esmType:"substitute-named-import-indirect",umdType:"substitute-indirect-source-target",binding:{source:o.isIdentifier(t.parent.property)?t.parent.property.name:o.isStringLiteral(t.parent.property)?t.parent.property.value:void 0,uniqueTarget:e.scope.generateUidIdentifier("imp").name},specifier:r,context:{statement:e,requireCall:t,expression:t.parentPath}}}return{esmType:"substitute-default-import-indirect",umdType:"substitute-indirect-target",binding:{source:"default",uniqueTarget:e.scope.generateUidIdentifier("imp").name},specifier:r,context:{statement:e,requireCall:t}}}function analyzeExports(e,t){var r=[];for(let i of e){if(!o.isProgram(i.parent))throw new Error("Exports expressions must be at the top-level of the program");let e=t.get(i),n=e.refs;if("assignment"==e.type){if(o.isExpressionStatement(i.node)&&o.isAssignmentExpression(i.node.expression)&&1==n.length){let e=i.node.expression,t=e.left,s=e.right;if(t==n[0].node){if(o.isIdentifier(s)&&"undefined"!=s.name){r.push({esmType:"default-export",umdType:"default-assignment",binding:{source:s},context:{statement:i,exportsExpression:i.get("expression.left")}});continue}r.push({esmType:"default-export",umdType:"default-assignment",binding:{source:s},context:{statement:i,exportsExpression:i.get("expression.left")}});continue}if(o.isMemberExpression(t,{object:n[0].node})&&isSimpleMemberExpression(t,e)){let n=o.isIdentifier(t.property)?t.property.name:o.isStringLiteral(t.property)?t.property.value:void 0;if(o.isIdentifier(s)&&"undefined"!=s.name){r.push({esmType:"named-export",umdType:"named-export",binding:{source:s.name,target:n},context:{statement:i,exportsExpression:i.get("expression.left.object")}});continue}if(isSimpleMemberExpression(s,e)){let e=o.isIdentifier(s.property)?s.property.name:o.isStringLiteral(s.property)?s.property.value:void 0;r.push({esmType:"destructured-declaration-export",umdType:"named-export",binding:{sourceName:e,source:s.object,target:n},context:{statement:i,exportsExpression:i.get("expression.left.object")}});continue}r.push({esmType:"named-declaration-export",umdType:"named-export",binding:{source:s,target:n,uniqueTarget:i.scope.generateUidIdentifier("exp").name},context:{statement:i,exportsExpression:i.get("expression.left.object")}});continue}}}else if("expression"==e.type){for(let e of n)r.push({esmType:"substitute-module-exports-reference",umdType:"substitute-module-exports-reference",context:{statement:i,exportsExpression:e}});continue}throw new Error("Unsupported: exports expression not ESM export-compatible")}return r}function hasRequireCalls(e,t,r){for(let i of r){let r=i;for(;r&&r!=e;){if(r.node==t)return!0;r=r.parentPath}}return!1}function isModuleExports(e){return o.isIdentifier(e,{name:"exports"})||o.isMemberExpression(e)&&o.isIdentifier(e.object,{name:"module"})&&(!e.computed&&o.isIdentifier(e.property,{name:"exports"})||e.computed&&o.isStringLiteral(e.property,{value:"exports"}))}function isSimpleMemberExpression(e,t){return o.isMemberExpression(e)&&(!e.computed&&o.isIdentifier(e.property)||e.computed&&o.isStringLiteral(e.property))&&!o.isCallExpression(t)}return d.identifyRequiresAndExports=function identifyRequiresAndExports(e,t){var r,i=new Set,d=new Set,u=new WeakMap,c=new WeakMap,f={Program:{exit(e){r=e}},CallExpression:{exit(e){if(o.isIdentifier(e.node.callee,{name:"require"})){if(1!=e.node.arguments.length||!o.isStringLiteral(e.node.arguments[0]))throw new Error("Unsupported: require(..) statement without a single string-literal argument");{let t=a(e.parentPath);t&&(i.add(t),u.has(t)||u.set(t,[]),u.get(t).push(e))}}}},MemberExpression:{exit(e){if(isModuleExports(e.node)){let t=a(e.parentPath);t&&(d.add(t),c.has(t)||c.set(t,{type:l(e)?"assignment":"expression",refs:[]}),c.get(t).refs.push(e))}}},Identifier:{exit(e){if("exports"==e.node.name&&!o.isMemberExpression(e.parent,{property:e.node})&&(l(e)||!p(e.parentPath)&&!o.isObjectProperty(e.parent,{key:e.node}))){let t=a(e.parentPath);t&&(d.add(t),c.has(t)||c.set(t,{type:l(e)?"assignment":"expression",refs:[]}),c.get(t).refs.push(e))}}}},m=s(t,{sourceFilename:e});n(m,f);var g=analyzeRequires(i,u),x=analyzeExports(d,c);return{programAST:m,programPath:r,convertRequires:g,convertExports:x}},d.analyzeRequires=analyzeRequires,d.analyzeExports=analyzeExports,d}],["UMD",{fs:"NodeFS",path:"NodePath","@babel/traverse":"BabelTraverse","@babel/types":"BabelTypes","@babel/generator":"BabelGenerator","@babel/parser":"BableParser",toposort:"TopoSort","./helpers.js":"Helpers","./analysis.js":"Analysis"},function DEF(e,t,r,i,n,o,s,a,p){"use strict";var l=e,d=t,{default:u}=r,c=i,{default:f}=n,{parse:m}=o,g=s,{expandHomeDir:x,addRelativeCurrentDir:h,generateName:b,rootRelativePath:y,qualifyDepPaths:E,isPathBasedSpecifier:v}=a,{identifyRequiresAndExports:D,analyzeRequires:S,analyzeExports:I}=p;let w={};w=build,w.build=build,w.bundle=function bundle(e,t){try{t=sortDependencies(e,t)}catch(t){if(!e.ignoreCircularDependency)throw new Error("Circular dependency not supported in UMD builds/bundles")}var r,i=m(M);u(i,{Program:{exit(e){r=e}}});var n=r.get("body.0.expression.arguments.1");for(let i of t){if(i.autoGenerated)continue;let t=c.clone(i.ast.program.body[0],!0,!0),o=t.expression.arguments[2].properties;if(o.length>0){let t=d.dirname(d.resolve(e.from,i.pathStr));for(let r of o)if(v(r.key.value)){let i=r.key.value,n=d.resolve(t,i),o=h(y(e.from,n));r.key.value=o}}r.pushContainer("body",t);let s=r.get("body.1.expression"),a=c.clone(s.get("arguments.0").node,!0,!0),p=c.clone(s.get("arguments.2").node,!0,!0),l=c.clone(s.get("arguments.3").node,!0,!0);n.pushContainer("elements",c.ArrayExpression([a,p,l])),r.get("body.1").remove()}return f(i)},w.index=function index(e,t,r){try{t=sortDependencies(e,t)}catch(t){if(!e.ignoreCircularDependency)throw new Error("Circular dependency not supported in UMD builds/bundles")}var i=Object.keys(r).find((e=>/\.cjs$/.test(e)))?"cjs":"js",n=`./index.${i}`,o="cjs"==i?"index.js":"index.cjs",s=r[n||o]||"Index",a=Object.entries(r).filter((([e])=>!e.startsWith(":::")&&t.find((t=>t.origPathStr==e))&&![n,o].includes(e)));n=renameCJS(e,n);var p={},l=m(T);return u(l,{Program:{exit(t){var r=t.get("body.0.expression");r.get("arguments.0").replaceWith(c.StringLiteral(s));var i=r.get("arguments.3"),n=i.get("body"),o=[],l=r.get("arguments.2");for(let[t,r]of a){let n,s=r;t.startsWith(":::")?n=t.slice(3):(n=t,n=h(n),n=renameCJS(e,n)),p[n]=n,l.node.properties.push(c.ObjectProperty(c.StringLiteral(n),c.StringLiteral(s))),i.node.params.push(c.Identifier(s)),o.push(c.ObjectProperty(c.Identifier(s),c.Identifier(s),!1,!0))}n.pushContainer("body",c.ReturnStatement(c.ObjectExpression(o))),n.node.directives.push(c.Directive(c.DirectiveLiteral("use strict")))}}}),{autoGenerated:!0,...f(l),ast:l,depMap:r,refDeps:p,pathStr:n,origPathStr:n,name:s}},w.sortDependencies=sortDependencies;var T=l.readFileSync(d.join(__dirname,"umd-template.js"),"utf-8"),M=l.readFileSync(d.join(__dirname,"umd-bundle-template.js"),"utf-8");function build(e,t,r,i){i={...i};var{programAST:n,programPath:o,convertRequires:s,convertExports:a}=D(t,r),p=e.from,l=d.resolve(p,x(t)),g=y(p,l),E=i[g];if(!E){if(!e.ignoreUnknownDependency)throw new Error(`Unknown module: ${t}`);E=b(),i[t]=E,g=t}var S={},I=!1;for(let t of s){let r;if(v(t.specifier)){let n=d.resolve(d.dirname(l),x(t.specifier)),o=y(p,n);if(o==g)throw new Error(`Module dependency is an illegal self-reference: ${t.specifier}`);r=i[o];let s=y(d.dirname(l),x(t.specifier));if(!r){if("remove-require-unique"!=t.umdType&&!e.ignoreUnknownDependency)throw new Error(`Unknown dependency: ${t.specifier}`);r=b(),i[o]=r}S[o]=s}else{let n=`:::${t.specifier}`;if(r=i[n],!r){if("remove-require-unique"!=t.umdType&&!e.ignoreUnknownDependency)throw new Error(`Unknown dependency: ${t.specifier}`);r=b(),i[n]=r}S[n]=n}"remove-require-unique"==t.umdType?t.context.statement.remove():"default-require"==t.umdType?r!=t.binding.target?t.context.requireCall.replaceWith(c.Identifier(r)):t.context.declarator.remove():t.context.requireCall.replaceWith(c.Identifier(r))}if(a.length>0){let e=c.Identifier(o.scope.generateUidIdentifier("exp").name);a[0].context.statement.insertBefore(c.VariableDeclaration("let",[c.VariableDeclarator(e,c.ObjectExpression([]))])),o.pushContainer("body",c.ReturnStatement(e));for(let t of a)"default-assignment"==t.umdType&®isterDefaultExport(t.context.exportsExpression),t.context.exportsExpression.replaceWith(e)}var w=m(T);u(w,{Program:{exit(t){var r=t.get("body.0.expression");r.get("arguments.0").replaceWith(c.StringLiteral(E));var n=Object.entries(S),o=r.get("arguments.3");if(n.length>0){let t=r.get("arguments.2");for(let[r,s]of n){let n,a=i[r];r.startsWith(":::")?n=r.slice(3):(n=s,n=h(n),n=renameCJS(e,n)),t.node.properties.push(c.ObjectProperty(c.StringLiteral(n),c.StringLiteral(a))),o.node.params.push(c.Identifier(a))}}}}});var M=c.clone(w.program.body[0],!0,!0);o.unshiftContainer("body",M);var P=o.get("body.0.expression.arguments.3.body");for(n.program.directives.length>0&&"use strict"==n.program.directives[0].value.value&&(P.node.directives.push(c.Directive(c.DirectiveLiteral("use strict"))),n.program.directives.shift());n.program.body.length>1;){let e=o.get("body.1"),t=c.cloneDeep(e.node);P.pushContainer("body",t),e.remove()}return{...f(n),ast:n,depMap:i,refDeps:S,pathStr:renameCJS(e,g),origPathStr:g,name:E};function registerDefaultExport(e){if(I)throw new Error("Multiple re-assignments of 'module.exports' not allowed in the same module");I=!0}}function sortDependencies(e,t){t=t.filter((e=>!e.autoGenerated));var r={};for(let e of t)r[e.pathStr]=e;var i=[];for(let n of t)for(let t of Object.keys(n.refDeps))t=renameCJS(e,t),t in r&&i.push([n,r[t]]);return g.array(t,i).reverse()}function renameCJS(e,t){return e[".cjs"]?t.replace(/\.cjs$/,".js"):t}return w}],["ESM",{path:"NodePath","@babel/types":"BabelTypes","@babel/template":"BabelTemplate","@babel/generator":"BabelGenerator","./helpers.js":"Helpers","./analysis.js":"Analysis"},function DEF(e,t,r,i,n,o){"use strict";var s=e,a=t,{default:p}=r,{default:l}=i,{expandHomeDir:d,addRelativeCurrentDir:u,generateName:c,rootRelativePath:f,qualifyDepPaths:m,isPathBasedSpecifier:g}=n,{identifyRequiresAndExports:x,analyzeRequires:h,analyzeExports:b}=o;let y={};function build(e,t,r,i){i={...i};var{programAST:n,programPath:o,convertRequires:p,convertExports:m}=x(t,r),h=e.from,b=s.resolve(h,d(t)),y=f(h,b),E=i[y];if(!E){if(!e.ignoreUnknownDependency)throw new Error(`Unknown module: ${t}`);E=c(),i[t]=E,y=t}var v,D={},S=!1,I=new Map,w=new Map;for(let[e,t]of p.entries()){if("substitute-named-import-indirect"==t.esmType||"substitute-default-import-indirect"==t.esmType)continue;I.has(t.context.statement)||I.set(t.context.statement,{reqIdxs:[],reqs:[]});let r=I.get(t.context.statement);r.reqIdxs.push(e),r.reqs.push(t)}for(let[e,t]of m.entries())if(I.has(t.context.statement)){let{reqIdxs:r,reqs:i}=I.get(t.context.statement);for(let e of r)p[e]=!1;m[e]=!1,w.has(t.context.statement)||w.set(t.context.statement,{requires:[...i],exports:[]}),w.get(t.context.statement).exports.push(t)}p=p.filter(Boolean),m=m.filter(Boolean);for(let[t,r]of w.entries()){let n,p=r.requires[0];if(g(p.specifier)){let t=s.resolve(s.dirname(b),d(p.specifier)),r=f(h,t);if(r==y)throw new Error(`Module dependency is an illegal self-reference: ${p.specifier}`);let o=i[r],a=f(s.dirname(b),d(p.specifier));if(!o){if(!e.ignoreUnknownDependency)throw new Error(`Unknown dependency: ${p.specifier}`);o=c(),i[r]=o}D[r]=a,n=u(renameFileExtension(e,a))}else{let t=`:::${p.specifier}`,r=i[t];if(!r){if(!e.ignoreUnknownDependency)throw new Error(`Unknown dependency: ${p.specifier}`);r=c(),i[t]=r}D[t]=t,n=p.specifier}let l=r.exports[0];if("default-import-indirect"!=p.esmType&&"named-import-indirect"!=p.esmType||"named-declaration-export"!=l.esmType&&"destructured-declaration-export"!=l.esmType)if("default-import-indirect"==p.esmType&&"default-export"==l.esmType){registerDefaultExport(l.context.exportsExpression);let r=a.Identifier(p.binding.uniqueTarget);t.replaceWithMultiple([a.ImportDeclaration([e.namespaceImport?a.ImportNamespaceSpecifier(r):a.ImportDefaultSpecifier(r)],a.StringLiteral(n)),a.ExportDefaultDeclaration(r)])}else{if("substitute-module-exports-reference"!=l.esmType)throw new Error("Unsupported: combined import/export form not ESM compatible");if(registerDefaultExport(l.context.exportsExpression),"substitute-default-import-indirect"==p.esmType){let t=a.Identifier(p.binding.uniqueTarget);p.context.statement.insertBefore(a.ImportDeclaration([e.namespaceImport?a.ImportNamespaceSpecifier(t):a.ImportDefaultSpecifier(t)],a.StringLiteral(n))),p.context.requireCall.replaceWith(t)}else if("substitute-named-import-indirect"==p.esmType){let e=a.Identifier(p.binding.uniqueTarget);p.context.statement.insertBefore(a.ImportDeclaration(["default"==p.binding.source?a.ImportDefaultSpecifier(e):a.ImportSpecifier(e,a.Identifier(p.binding.source))],a.StringLiteral(n))),p.context.expression.replaceWith(e)}v||(v=createModuleExports(o,t,m[m.length-1].context.statement)),l.context.exportsExpression.replaceWith(v)}else"default"==l.binding.target&®isterDefaultExport(l.context.exportsExpression),t.replaceWith(a.ExportNamedDeclaration(null,[a.ExportSpecifier(a.Identifier(p.binding.source),a.Identifier(l.binding.target))],a.StringLiteral(n)))}for(let t of p){let r;if(g(t.specifier)){let n=s.resolve(s.dirname(b),d(t.specifier)),o=f(h,n);if(o==y)throw new Error(`Module dependency is an illegal self-reference: ${t.specifier}`);let a=i[o],p=f(s.dirname(b),d(t.specifier));if(!a){if(!e.ignoreUnknownDependency)throw new Error(`Unknown dependency: ${t.specifier}`);a=c(),i[o]=a}D[o]=p,r=u(renameFileExtension(e,p))}else{let n=`:::${t.specifier}`,o=i[n];if(!o){if(!e.ignoreUnknownDependency)throw new Error(`Unknown dependency: ${t.specifier}`);o=c(),i[n]=o}D[n]=n,r=t.specifier}if("bare-import"==t.esmType)t.context.statement.replaceWith(a.ImportDeclaration([],a.StringLiteral(r)));else if("default-import"==t.esmType)t.context.statement.insertBefore(a.ImportDeclaration([e.namespaceImport?a.ImportNamespaceSpecifier(a.Identifier(t.binding.target)):a.ImportDefaultSpecifier(a.Identifier(t.binding.target))],a.StringLiteral(r))),t.context.declarator.remove();else if("named-import"==t.esmType){let e=[];for(let r of Array.isArray(t.binding)?t.binding:[t.binding]){let t=a.Identifier(r.target);e.push("default"==r.source?a.ImportDefaultSpecifier(t):a.ImportSpecifier(t,a.Identifier(r.source)))}t.context.statement.insertBefore(a.ImportDeclaration(e,a.StringLiteral(r))),t.context.declarator.remove()}else if("default-import-indirect"==t.esmType)t.context.statement.replaceWithMultiple([a.ImportDeclaration([e.namespaceImport?a.ImportNamespaceSpecifier(a.Identifier(t.binding.uniqueTarget)):a.ImportDefaultSpecifier(a.Identifier(t.binding.uniqueTarget))],a.StringLiteral(r)),a.ExpressionStatement(a.AssignmentExpression("=",a.Identifier(t.binding.target),a.Identifier(t.binding.uniqueTarget)))]);else if("named-import-indirect"==t.esmType){let e=[],i=[];for(let r of Array.isArray(t.binding)?t.binding:[t.binding]){let t=a.Identifier(r.uniqueTarget);e.push("default"==r.source?a.ImportDefaultSpecifier(t):a.ImportSpecifier(t,a.Identifier(r.source))),i.push(a.ExpressionStatement(a.AssignmentExpression("=",a.Identifier(r.target),t)))}t.context.statement.replaceWithMultiple([a.ImportDeclaration(e,a.StringLiteral(r)),...i])}else if("substitute-default-import-indirect"==t.esmType){let i=a.Identifier(t.binding.uniqueTarget);t.context.statement.insertBefore(a.ImportDeclaration([e.namespaceImport?a.ImportNamespaceSpecifier(i):a.ImportDefaultSpecifier(i)],a.StringLiteral(r))),t.context.requireCall.replaceWith(i)}else if("substitute-named-import-indirect"==t.esmType){let e=a.Identifier(t.binding.uniqueTarget);t.context.statement.insertBefore(a.ImportDeclaration(["default"==t.binding.source?a.ImportDefaultSpecifier(e):a.ImportSpecifier(e,a.Identifier(t.binding.source))],a.StringLiteral(r))),t.context.expression.replaceWith(e)}}for(let e of m)"default-export"==e.esmType?(registerDefaultExport(e.context.exportsExpression),e.context.statement.replaceWith(a.ExportDefaultDeclaration(e.binding.source))):"destructured-declaration-export"==e.esmType?e.context.statement.replaceWith(a.ExportNamedDeclaration(a.VariableDeclaration("let",[a.VariableDeclarator(a.ObjectPattern([a.ObjectProperty(a.Identifier(e.binding.sourceName),a.Identifier(e.binding.target),!1,e.binding.sourceName==e.binding.target)]),e.binding.source)]))):"named-declaration-export"==e.esmType?("default"==e.binding.target&®isterDefaultExport(e.context.exportsExpression),e.context.statement.replaceWithMultiple([a.VariableDeclaration("let",[a.VariableDeclarator(a.Identifier(e.binding.uniqueTarget),e.binding.source)]),"default"==e.binding.target?a.ExportDefaultDeclaration(a.Identifier(e.binding.uniqueTarget)):a.ExportNamedDeclaration(null,[a.ExportSpecifier(a.Identifier(e.binding.uniqueTarget),a.Identifier(e.binding.target))])])):"named-export"==e.esmType?("default"==e.binding.target&®isterDefaultExport(e.context.exportsExpression),e.context.statement.replaceWith("default"==e.binding.target?a.ExportDefaultDeclaration(e.binding.source):a.ExportNamedDeclaration(null,[a.ExportSpecifier(a.Identifier(e.binding.source),a.Identifier(e.binding.target))]))):"substitute-module-exports-reference"==e.esmType&&(registerDefaultExport(e.context.exportsExpression),v||(v=createModuleExports(o,e.context.statement,m[m.length-1].context.statement)),e.context.exportsExpression.replaceWith(v));return n.program.directives.length=0,{...l(n),ast:n,depMap:i,refDeps:D,pathStr:renameFileExtension(e,y),origPathStr:y,name:E};function registerDefaultExport(e){if(S)throw new Error("Multiple default exports not allowed in the same module");S=!0}}function renameFileExtension(e,t){return e[".cjs"]&&(t=t.replace(/\.cjs$/,".js")),e[".mjs"]&&(t=t.replace(/\.c?js$/,".mjs")),t}function createModuleExports(e,t,r){var i=a.Identifier(e.scope.generateUidIdentifier("exp").name);return t.insertBefore(a.VariableDeclaration("let",[a.VariableDeclarator(i,a.ObjectExpression([]))])),r.insertAfter(a.ExportDefaultDeclaration(i)),i}return y=build,y.build=build,y.index=function index(e,t,r){var i=Object.keys(r).find((e=>/\.cjs$/.test(e)))?"cjs":"js",n=`./index.${i}`,o="cjs"==i?"index.js":"index.cjs",s=r[n||o]||"Index",d=Object.entries(r).filter((([e])=>!e.startsWith(":::")&&t.find((t=>t.origPathStr==e))&&![n,o].includes(e)));n=renameFileExtension(e,n);var c=a.File(p.program("")());for(let[t,r]of d){let i,n=r;t.startsWith(":::")?i=t.slice(3):(i=t,i=u(i),i=renameFileExtension(e,i));let o=a.Identifier(n);c.program.body.push(a.ExportNamedDeclaration(null,[e.exportDefaultFrom?a.ExportDefaultSpecifier(o):e.namespaceExport?a.ExportNamespaceSpecifier(o):a.ExportSpecifier(a.Identifier("default"),o)],a.StringLiteral(i)))}return{...l(c),ast:c,depMap:r,refDeps:r,pathStr:n,origPathStr:n,name:s}},y}],["Mz",{path:"NodePath","./helpers.js":"Helpers","./umd.js":"UMD","./esm.js":"ESM"},function DEF(e,t,r,i){"use strict";var n=e,{expandHomeDir:o,qualifyDepPaths:s,isDirectory:a}=t,p=r,{bundle:l,index:d}=r,u=i,{index:c}=i;let f={};function build(e,t,r,i={}){e=defaultLibConfig(e);var l=n.resolve(o(e.from)),d=a(l)?l:n.dirname(l);e.from=d,i=s(i,d);var c={};return e.buildUMD&&(c.umd=p(e,t,r,i),i=c.umd.depMap),e.buildESM&&(c.esm=u(e,t,r,i),i=c.esm.depMap),c}function defaultLibConfig({ignoreUnknownDependency:e=!1,ignoreCircularDependency:t=!1,".mjs":r=!1,".cjs":i=!1,namespaceImport:n=!1,namespaceExport:o=!1,exportDefaultFrom:s=!1,from:a="",...p}={}){return{ignoreUnknownDependency:e,ignoreCircularDependency:t,".mjs":r,".cjs":i,namespaceImport:n,namespaceExport:o,exportDefaultFrom:s,from:a,...p}}return f=build,f.build=build,f.defaultLibConfig=defaultLibConfig,f.bundleUMD=l,f.umdIndex=d,f.esmIndex=c,f}],["CLI",{path:"NodePath",fs:"NodeFS",dotenv:"DotEnv",micromatch:"MicroMatch",minimist:"Minimist",mkdirp:"MkDirP","recursive-readdir-sync":"RecursiveReaddirSync",terser:"Terser","./index.js":"Mz","./helpers.js":"Helpers"},function DEF(e,t,r,i,n,o,s,a,p,l){"use strict";var d,u=e,c=t,f=r,m=i,g=n,x=o,h=s,b=a,{build:y,bundleUMD:E,umdIndex:v,esmIndex:D,defaultLibConfig:S}=p,{expandHomeDir:I,rootRelativePath:w,qualifyDepPaths:T,isDirectory:M,checkPath:P,generateName:j}=l;f.config();var q=g(process.argv.slice(2),{boolean:["help","version","build-esm","build-umd","recursive","minify"],string:["config","from","to","bundle-umd","prepend"],alias:{config:"c",recursive:"r","build-esm":"e","build-umd":"u","bundle-umd":"b","dep-map":"m",minify:"n",prepend:"p"},default:{help:!1,version:!1,recursive:!1,"build-esm":!1,"build-umd":!1,minify:!1,prepend:""}}),C=Boolean(q.config||process.env.RCPATH),U=Boolean(q["dep-map"]||process.env.DEPMAPPATH),k=resolvePath(q.config||process.env.RCPATH||"./.mzrc"),$=resolvePath(q["dep-map"]||process.env.DEPMAPPATH||"./package.json"),F=defaultCLIConfig();let A={};async function CLI(e="0.0.0?"){if(d=e,function loadConfig(){var e;try{e=c.readFileSync(k,"utf-8")}catch(t){e=""}try{e=JSON.parse(e)}catch(e){if(C)return showError(`Invalid config: ${k}`,!0)}return F=S(defaultCLIConfig(e)),function checkArgsAndConfig(){if(q.help)return void printHelp();if(q.version)return void function printVersion(){console.log(`v${d}`)}();if(!F.buildESM&&!F.buildUMD)return showError("Must select at least one output format (ESM or UMD).",!0);if(!P(F.from))return showError(`Input directory (${F.from}) is missing or inaccessible.`);if(!P(F.to)){if(!/\.mz-build$/.test(F.to))return showError(`Output directory (${F.to}) is missing or inaccessible.`);if(!0!==mkdir(F.to))return showError(`Default output directory (${F.to}) could not be created.`);if(F.buildESM){let e=u.join(F.to,"esm");if(!P(e)&&!0!==mkdir(e))return showError(`Output directory (${e}) could not be created.`)}if(F.buildUMD){let e=u.join(F.to,"umd");if(!P(e)&&!0!==mkdir(e))return showError(`Output directory (${e}) could not be created.`)}}if(!F.depMap)if(P(F.depMapPath)){let e;try{if(e=JSON.parse(c.readFileSync(F.depMapPath,"utf-8")),/package\.json$/.test(F.depMapPath)&&(e=e["mz-dependencies"],(!e||"object"!=typeof e)&&F.buildUMD))throw!0}catch(e){return showError(`Invalid/missing dependency map (${F.depMapPath}).`)}F.depMap=e}else{if(U)return showError(`Dependency map (${F.depMapPath}) is missing or inaccessible.`);if(F.buildUMD)return showError("UMD build format requires dependency map.");F.depMap={}}return!0}()}()){var t={};if(F.depMap){let e=resolvePath(F.from);e=M(e)?e:u.dirname(e),t=T(F.depMap,e)}var r=function getInputFiles(){var e;if(M(F.from))if(F.recursive)try{e=h(F.from)}catch(e){return showError(`Failed scanning for input files (${F.from})`)}else e=c.readdirSync(F.from).filter((function skipDirs(e){return!M(e)}));else e=[F.from],F.from=u.dirname(F.from);Array.isArray(F.skip)&&F.skip.length>0&&(e=e.filter((function skipFiles(e){var t=0==m(e,F.skip).length;return!t&&F.copyOnSkip&&(F.copyFiles=F.copyFiles||[],F.copyFiles.push(e)),t})));return e=e.map((function fixPaths(e){return[u.resolve(F.from),w(F.from,e)]}))}();for(let[,e]of r)e in t||(t[e]=j());var i=[],n=[];try{for(let[e,o]of r){let r,s=c.readFileSync(u.join(e,o),"utf-8");try{r=y(F,o,s,t),t=r.esm?r.esm.depMap:r.umd.depMap}catch(t){throw new Error(`${t.toString()} (${u.join(e,o)}) `)}r.umd&&(F.bundleUMDPath||F.generateIndex)&&i.push(r.umd),r.esm&&F.generateIndex&&n.push(r.esm);for(let e of["esm","umd"])if(r[e]){let t=u.join(F.to,e,r[e].pathStr),i=u.dirname(t);if(!0!==mkdir(i))throw new Error(`Output directory (${i}) could not be created.`);let n=await processContents(r[e].code,u.basename(t));try{c.writeFileSync(t,n,"utf-8")}catch(e){throw new Error(`Output file (${t}) could not be created.`)}}}if(F.generateIndex){if(F.buildUMD){let e=v(F,i,t);i.push(e);let r=u.join(F.to,"umd",e.pathStr),n=await processContents(e.code,u.basename(r));try{c.writeFileSync(r,n,"utf-8")}catch(e){throw new Error(`Generated index (${r}) could not be created.`)}}if(F.buildESM){let e=D(F,n,t);n.push(e);let r=u.join(F.to,"esm",e.pathStr),i=await processContents(e.code,u.basename(r));try{c.writeFileSync(r,i,"utf-8")}catch(e){throw new Error(`Generated index (${r}) could not be created.`)}}}if(F.bundleUMDPath&&i.length>0){let e=E(F,i),t=await processContents(e.code,u.basename(F.bundleUMDPath));try{c.writeFileSync(F.bundleUMDPath,t,"utf-8")}catch(e){throw new Error(`UMD bundle (${F.bundleUMDPath}) could not be created.`)}}if(F.copyFiles&&F.copyFiles.length>0)for(let e of F.copyFiles){let t=u.resolve(F.from,e),r=w(F.from,t),i=c.readFileSync(t);for(let e of["esm","umd"])if("esm"==e&&F.buildESM||"umd"==e&&F.buildUMD){let t=u.resolve(u.join(F.to,e),r),n=u.dirname(t);if(!0!==mkdir(n))throw new Error(`While copying skipped file (${t}), directory (${n}) could not be created.`);c.writeFileSync(t,i)}}}catch(e){return showError(e)}}}async function processContents(e,t){if(q.minify){let t=await b.minify(e,{mangle:{keep_fnames:!0},compress:{keep_fnames:!0},output:{comments:/^!/}});if(!t||!t.code)throw t.error?t.error:t;e=t.code}if(""!=q.prepend){e=`${q.prepend.replace(/#FILENAME#/g,t)}${e}`}return e}function printHelp(){console.log("moduloze usage:"),console.log(" mz {OPTIONS}"),console.log(""),console.log("--help print this help"),console.log("--version print version info"),console.log("--config={PATH}, -c path to load config"),console.log(` [${k}]`),console.log("--from={PATH} scan directory for input file(s)"),console.log(` [${F.from}]`),console.log("--to={PATH} target directory for output file(s)"),console.log(` [${F.to}]`),console.log("--dep-map={PATH}, -m dependency map file"),console.log(` [${$}]`),console.log("--recursive, -r scan recursively for input files"),console.log(` [${F.recursive}]`),console.log("--build-esm, -e build ES-Modules format from input file(s)"),console.log(` [${F.buildESM}]`),console.log("--build-umd, -u build UMD format from input file(s)"),console.log(` [${F.buildUMD}]`),console.log("--bundle-umd={PATH}, -b include UMD bundle"),console.log(` [${F.bundleUMDPath||"./umd/bundle.js"}]`),console.log("--minify, -n minify output files"),console.log(` [${F.minify}]`),console.log("--prepend={TEXT}, -p prepend TEXT to each file"),console.log(` [${F.prepend}]`),console.log("")}function showError(e,t=!1){console.error(e.toString()),t&&(console.log(""),printHelp()),process.exit(1)}function defaultCLIConfig({from:e=process.env.FROMPATH,to:t=process.env.TOPATH,depMap:r,bundleUMDPath:i,skip:n=[],copyOnSkip:o=!1,copyFiles:s=[],recursive:a,buildESM:p,buildUMD:l,generateIndex:d=!1,minify:u=!1,prepend:c="",...f}={}){e=resolvePath(q.from||e||"./"),t=resolvePath(q.to||t||"./.mz-build");var m=$;return i=!!("bundle-umd"in q||i||"UMDBUNDLEPATH"in process.env)&&resolvePath(q["bundle-umd"]||i||process.env.UMDBUNDLEPATH||"./umd/bundle.js",t),{from:e,to:t,recursive:a=Boolean(q.recursive||a),buildESM:p=Boolean(q["build-esm"]||p),buildUMD:l=Boolean(q["build-umd"]||l),skip:n,copyOnSkip:o,copyFiles:s,depMap:r,depMapPath:m,bundleUMDPath:i,generateIndex:d,minify:u,prepend:c,...f}}function resolvePath(e,t=process.cwd()){return e=I(e),u.resolve(t,e)}function mkdir(e){try{return x.sync(e),!0}catch(e){return e}}return A=CLI,A.CLI=CLI,A}]]);