@tochii/build 2.5.0 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-S6QAP2TG.mjs +16 -0
- package/dist/cli.mjs +9 -26
- package/dist/index.d.mts +1318 -5
- package/dist/index.mjs +1 -44
- package/package.json +27 -23
- package/dist/chunk-4IB5MIMZ.mjs +0 -15
- package/dist/tsup@8.4.0-minified/chunk-BMINWOCT.js +0 -5
- package/dist/tsup@8.4.0-minified/chunk-SP4XNZBT.js +0 -40
- package/dist/tsup@8.4.0-minified/cli-node.js +0 -2
- package/dist/tsup@8.4.0-minified/index.js +0 -1
- package/dist/tsup@8.4.0-minified/rollup.js +0 -46
- package/dist/utils-dsfZeRyj.d.mts +0 -117
- package/dist/utils.d.mts +0 -5
- package/dist/utils.mjs +0 -1
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import{defineConfig as J,build as re}from"tsup";import L from"chalk";import b from"node:fs";import G from"node:path";import W from"deepmerge";import y from"chalk";import X from"node:path";var k="tochibuild",V=y.cyan(k),P=[V,y.blue("CLI")],O=class{static initialize(e,n){["log","debug","info","warn","error"].forEach(i=>{let d=console[i];console[i]=function(...r){let o=r?.[0]||"",s=r?.[1]||"",u=!!o&&typeof o=="string",a=!!s&&typeof s=="string";if(o&&u&&!o.includes("tochibuild")){let p=[];switch(i){case"error":p.push(y.red(k),y.red("CLI"));break;default:p.push(V);break}if(p.concat(r||[]),a&&s.toLowerCase().includes("using tsup config")){let l=r[1].split(": ")[1],f=X.relative(e,l);r[1]=`Using config: ${y.gray(f)}`}a&&s.toLowerCase().includes("tsup v")&&(r[1]=`tochibuild v${n}`),d.apply(console,[...p,...r]);return}d.apply(console,r)}})}};O.custom=(e,...n)=>{console[e](...P,...n)},O.log=(...e)=>{console.log(...P,...e)},O.debug=(...e)=>{console.debug(...P,...e)},O.info=(...e)=>{console.info(...P,...e)},O.warn=(...e)=>{console.warn(...P,...[...e].map(n=>y.yellow(n)))},O.error=(e,...n)=>{console.error(y.red(k),y.blue("CLI"),y.bgRed(...n),e?.stack?`
|
|
2
|
+
${y.gray(e.stack)}`:"")},O.success=(...e)=>{console.log(y.green(k),y.blue("CLI"),...e)};var g=O;import N from"node:path";function B(t){let e=N.resolve(process.cwd(),t||".");return t&&N.isAbsolute(t||".")?t:e}import I from"node:fs/promises";import v from"node:path";import{create as Z}from"tar";import _ from"@npmcli/arborist";import U from"npm-packlist";import h from"node:fs";import D from"node:path";var Y=(t,e)=>S(D.join(C(t,e),".tochibuild")),j=(t,e)=>{let n=Y(t,e);if(!n)return n;let i=D.join(n,"tmp");return h.existsSync(i)||h.mkdirSync(i,{recursive:!0}),i},ye=(t,e,n)=>{if(!t)return t;let i=j(e,n);return i&&D.join(i,t)};var Oe=(t,e)=>$(j(t,e));function C(t,e){let n=D.resolve(e||process.cwd(),t||".");return t&&D.isAbsolute(t||".")?t:n}function S(t){return t&&(h.existsSync(t)||h.mkdirSync(t,{recursive:!0}),t)}function he(t,e,n){if(!t)return t;let i=n?.overwrite??!0;return(!h.existsSync(t)||i)&&h.writeFileSync(t,e),t}function $(t){return t&&(h.existsSync(t)&&h.rmSync(t,{recursive:!0,force:!0}),t)}async function ee({packageDir:t,packageJsonData:e,outputTarballPath:n="tochibuild.package.tgz"}){let i=C(t),d=C(n).replace(/\\/g,"/"),o=await new _({path:i}).loadActual(),s=await U(o),u=j(t);if(!u)throw new Error("Could not get tmp dir");let a=S(v.join(u,`publish-${Date.now()}-`));if(!a)throw new Error("Could not create tmp dir");if(await Promise.all(s.filter(l=>e?l!=="package.json":!0).map(async l=>{let f=v.join(i,l),m=v.join(a,l);await I.mkdir(v.dirname(m),{recursive:!0}),await I.copyFile(f,m)})),e){let l=v.join(a,"package.json");await I.writeFile(l,JSON.stringify(e,null,2))}let p=v.relative(process.cwd(),d).replace(/\\/g,"/");return await Z({cwd:a,file:p,gzip:!0,prefix:"package/"},["."]),$(a),{name:e?.name||"unknown",tarballRelativePath:p,tarballPath:d,fileList:s}}var M=ee;import E from"node:fs";import x from"node:path";import A from"chalk";import ne from"fast-glob";async function z(t,e,n){let i=process.cwd();g.info("merging files..."),g.info("outFile:",A.gray(x.relative(i,e)));let d=C(e),r=x.relative(i,d).replace(/\\/g,"/"),o=await ne(t,{absolute:!0});if(!o.length)throw new Error(`no files found matching: ${t.join(", ")}`);let s=o.filter(l=>!E.existsSync(l));if(s.length)throw new Error(`files not found: ${s.join(", ")}`);n?.(o),g.info(`files to be merged:
|
|
3
|
+
${o.map(l=>x.relative(i,l)).map(l=>`- ${A.gray(l)}`).join(`
|
|
4
|
+
`)}`),o.reduce((l,f)=>l&&x.extname(f)===x.extname(o[0]),!0)||g.warn("file extensions do not match!");let a=o.map(l=>{let f=E.readFileSync(l,"utf8");return`// ---- ${x.basename(l)} ----
|
|
5
|
+
${f}`}).join(`
|
|
6
|
+
|
|
7
|
+
`),p=x.dirname(d);E.existsSync(p)||E.mkdirSync(x.dirname(d),{recursive:!0}),E.writeFileSync(d,a,"utf8"),g.success(`successfully merged ${o.length} files into ${A.gray(r)}`)}var te=(t,e)=>{let n=[];return n.push((e?.prefix??"")+t+(e?.suffix??"")),n.push((e?.prefix??"")+`**/${t}`+(e?.suffix??"")),n},c=class c{};c.defaultConfigOptions={tsconfig:"tsconfig.json",dts:!0,format:["esm"],minify:!0},c.ignoredEntries=[...["*.d.ts","{tochibuild,tsup}.*","build","build/**","dist","dist/**","node_modules","node_modules/**"].flatMap(e=>te(e,{prefix:"!"}))].sort().reverse(),c.entriesCommon=["*.{js,ts}","**/*.{js,ts}"],c.entriesIndex=["index.{js,ts}","**/index.{js,ts}"],c.defaultEntriesIndex=[...c.ignoredEntries,...c.entriesIndex],c.defaultEntriesCommon=[...c.ignoredEntries,...c.entriesCommon],c.handleOptions=(e,n,i,d)=>c.mergeBuildOptions(e,{overrideOptions:r=>{let o=F(r.entry,n?.excludeIgnoredEntries?[]:["ignoredEntries"]);return{...n?.defaultBuildOptions||c.defaultConfigOptions,...e,...r,noExternal:[...r.noExternal||[],...c.getPackageJsonDepsEntriesFromConfig(n)].filter(u=>!r?.external?.includes(u)),entry:o,tochibuildConfig:n}}},i,d),c.handleOptionsWithIndexEntries=(e,n,i,d)=>c.mergeBuildOptions(e,{overrideOptions:r=>{let o=n?.excludeIgnoredEntries?["entriesIndex"]:["ignoredEntries","entriesIndex"],s=F(r.entry,o);return{...n?.defaultBuildOptions||c.defaultConfigOptions,...e,...r,noExternal:[...r.noExternal||[],...c.getPackageJsonDepsEntriesFromConfig(n)].filter(a=>!r?.external?.includes(a)),entry:s,tochibuildConfig:n}}},i,d),c.handleOptionsWithCommonEntries=(e,n,i,d)=>c.mergeBuildOptions(e,{overrideOptions:r=>{let o=n?.excludeIgnoredEntries?["entriesCommon"]:["ignoredEntries","entriesCommon"],s=F(r.entry,o);return{...n?.defaultBuildOptions||c.defaultConfigOptions,...e,...r,noExternal:[...r.noExternal||[],...c.getPackageJsonDepsEntriesFromConfig(n)].filter(a=>!r?.external?.includes(a)),entry:s,tochibuildConfig:n}}},i,d),c.generateConfig=ie,c.ensureEntries=F,c.createTarball=M,c.mergeFiles=z,c.mergeBuildOptions=(e,n,i,d)=>{if(typeof e=="function")return async a=>{let p=await e(a);return s(p,n.overrideOptionsCustom)};return s(e,n.overrideOptionsCustom);function o(u,a){let p=n.overrideOptions(a||{}),l=Object.entries(p);for(let[f,m]of l)m===void 0&&delete p[f];return W(u,p)}function s(u,a){if(Array.isArray(u))return u.map(p=>o(p,a));if(typeof u!="object"){if(i)throw new Error(`Invalid configuration options type: ${typeof u}`);return g.error(void 0,`Invalid configuration options type: ${typeof u}`),d&&process.exit(1),{}}return o(u,a)}},c.mergeBuildOptionsAsync=async(e,n,i,d)=>{if(typeof e=="function")return n.execute?await e(n.overrideOptions):async u=>{let a=await e(u);return r(a,n.overrideOptionsCustom)};if(n.execute)return r(e,n.overrideOptions);return r(e,n.overrideOptionsCustom);function r(s,u){if(Array.isArray(s))return s.map(a=>o(a,u));if(typeof s!="object"){if(i)throw new Error(`Invalid configuration options type: ${typeof s}`);return g.error(void 0,`Invalid configuration options type: ${typeof s}`),d&&process.exit(1),{}}return o(s,u)}function o(s,u){if(n.execute){let l=u||{},f=Object.entries(l);for(let[m,w]of f)w===void 0&&delete l[m];return W(s,l)}let a=n.overrideOptions(u||{}),p=Object.entries(a);for(let[l,f]of p)f===void 0&&delete a[l];return W(s,a)}},c.getPackageJson=(e,n)=>{let i,d;try{return i=G.join(B(e),"package.json"),b.existsSync(i)&&(d=JSON.parse(b.readFileSync(i,"utf-8"))),{filePath:i,data:d}}catch(r){if(n)throw r;return{filePath:i,data:d}}},c.getPackageJsonDepsEntriesFromConfig=(e,n)=>{let i=e?.includePackageJsonDeps??!1,d=e?.includePackageJsonDevDeps??!1,r=e?.includePackageJsonPeerDeps??!1,o=[];return i&&o.push("dependencies"),d&&o.push("devDependencies"),r&&o.push("peerDependencies"),c.getPackageJsonDepsEntries(n??c.getPackageJson().filePath,o)},c.getPackageJsonDepsEntries=(e,n=["dependencies","devDependencies","peerDependencies"])=>c.getPackageJsonDeps(e).toArray(n),c.getPackageJsonDeps=e=>{let n={},i={},d={},r={dependencies:n,devDependencies:i,peerDependencies:d,toArray:(o=["dependencies","devDependencies","peerDependencies"])=>[]};try{if(!e)return r;if(!b.existsSync(e))return g.error(void 0,`could not find package.json at ${e}`),r;let o=b.readFileSync(e,"utf-8"),s=JSON.parse(o),u={dependencies:s.dependencies||{},devDependencies:s.devDependencies||{},peerDependencies:s.peerDependencies||{}};return{...u,toArray:(a=["dependencies","devDependencies","peerDependencies"])=>a.flatMap(p=>Object.keys(u[p]))}}catch(o){g.error(o,`could not read package.json at ${e}`);let s={dependencies:n||{},devDependencies:i||{},peerDependencies:d||{}};return{...s,toArray:(u=["dependencies","devDependencies","peerDependencies"])=>u.flatMap(a=>Object.keys(s[a]))}}};var R=c,T=R;function F(t,e){if(Array.isArray(t)){let n=[],i=[];return e.forEach(d=>i.push(...R[d])),n.push(...Array.from(new Set([...i,...t]))),n}return t}function ie(t,e,n,i){let d="";try{let r=e?.ext||".ts",s=`${e?.filename||"tochibuild.config"}${r}`;(e?.outDir?.length?e.outDir:["."]).forEach(a=>{d=B(a),b.existsSync(a)||b.mkdirSync(a,{recursive:!0});let p=G.join(d,s),l=b.existsSync(p);if(!e?.overwrite&&l){g.warn(`the config '${s}' file already exists for this project.`),i&&process.exit(1);return}let f=" ",m="",w={clean:!1,splitting:!0},q=K=>{m+=K==="esm"?`import build from '${t}';
|
|
8
|
+
|
|
9
|
+
`:`const build = require('${t}');
|
|
10
|
+
|
|
11
|
+
`,m+=K==="esm"?`export default build.defineConfigWithIndexEntries({
|
|
12
|
+
`:`cliModule.exports = build.defineConfigWithIndexEntries({
|
|
13
|
+
`,Object.entries(w).forEach(([H,Q])=>{m+=`${f}${H}: ${JSON.stringify(Q)},
|
|
14
|
+
`}),m+=`});
|
|
15
|
+
`};switch(r){case".ts":case".js":q("esm");break;case".cjs":q("cjs");break;case".json":m+=`${JSON.stringify({...w,entry:R.defaultEntriesIndex},null,2)}
|
|
16
|
+
`;break;default:g.error(void 0,`unsupported extension: ${r}`),i&&process.exit(1);return}b.writeFileSync(p,m),g.success(L.cyan("the config file has been created at:"),L.gray(p))})}catch(r){if(n)throw r;g.error(r,r.message?`failed to generate config file in ${d}: ${r.message}`:`failed to generate config file in ${d}`),i&&process.exit(1)}}var Le=T,se=re,Ge={utils:T,build:se,defineConfig:oe,defineConfigWithIndexEntries:ae,defineConfigWithCommonEntries:ce};async function oe(t,e){return J(T.handleOptions(t,e,!1,!0))}async function ae(t,e){return J(T.handleOptionsWithIndexEntries(t,e,!1,!0))}async function ce(t,e){return J(T.handleOptionsWithCommonEntries(t,e,!1,!0))}export{g as a,ye as b,Oe as c,he as d,M as e,z as f,T as g,Le as h,se as i,Ge as j,oe as k,ae as l,ce as m};
|
package/dist/cli.mjs
CHANGED
|
@@ -1,27 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as E,b as y,c as xt,d as C,e as x,g as F}from"./chunk-4IB5MIMZ.mjs";var v=y(I=>{"use strict";var S=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}},j=class extends S{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};I.CommanderError=S;I.InvalidArgumentError=j});var V=y(q=>{"use strict";var{InvalidArgumentError:wt}=v(),N=class{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:e.concat(t)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new wt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,i):e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Et(u){let t=u.name()+(u.variadic===!0?"...":"");return u.required?"<"+t+">":"["+t+"]"}q.Argument=N;q.humanReadableArgName=Et});var L=y(R=>{"use strict";var{humanReadableArgName:vt}=V(),M=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let e=t.commands.filter(s=>!s._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((s,n)=>s.name().localeCompare(n.name())),e}compareOptions(t,e){let i=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(s=>!s.hidden),i=t._getHelpOption();if(i&&!i.hidden){let s=i.short&&t._findOption(i.short),n=i.long&&t._findOption(i.long);!s&&!n?e.push(i):i.long&&!n?e.push(t.createOption(i.long,i.description)):i.short&&!s&&e.push(t.createOption(i.short,i.description))}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let e=[];for(let i=t.parent;i;i=i.parent){let s=i.options.filter(n=>!n.hidden);e.push(...s)}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||""}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>vt(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,s)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(s)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,s)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,s)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(s)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,s)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(s)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let s=t.parent;s;s=s.parent)i=s.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];return t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0?`${t.description} (${e.join(", ")})`:t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatHelp(t,e){let i=e.padWidth(t,e),s=e.helpWidth??80;function n(c,p){return e.formatItem(c,i,p,e)}let r=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(r=r.concat([e.boxWrap(e.styleCommandDescription(a),s),""]));let o=e.visibleArguments(t).map(c=>n(e.styleArgumentTerm(e.argumentTerm(c)),e.styleArgumentDescription(e.argumentDescription(c))));o.length>0&&(r=r.concat([e.styleTitle("Arguments:"),...o,""]));let h=e.visibleOptions(t).map(c=>n(e.styleOptionTerm(e.optionTerm(c)),e.styleOptionDescription(e.optionDescription(c))));if(h.length>0&&(r=r.concat([e.styleTitle("Options:"),...h,""])),e.showGlobalOptions){let c=e.visibleGlobalOptions(t).map(p=>n(e.styleOptionTerm(e.optionTerm(p)),e.styleOptionDescription(e.optionDescription(p))));c.length>0&&(r=r.concat([e.styleTitle("Global Options:"),...c,""]))}let l=e.visibleCommands(t).map(c=>n(e.styleSubcommandTerm(e.subcommandTerm(c)),e.styleSubcommandDescription(e.subcommandDescription(c))));return l.length>0&&(r=r.concat([e.styleTitle("Commands:"),...l,""])),r.join(`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
`)
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
- too many long flags`):new Error(`${a}
|
|
12
|
-
- unrecognised flag format`)}if(t===void 0&&e===void 0)throw new Error(`option creation failed due to no flags found in '${u}'.`);return{shortFlag:t,longFlag:e}}B.Option=U;B.DualOptions=G});var rt=y(nt=>{"use strict";function Vt(u,t){if(Math.abs(u.length-t.length)>3)return Math.max(u.length,t.length);let e=[];for(let i=0;i<=u.length;i++)e[i]=[i];for(let i=0;i<=t.length;i++)e[0][i]=i;for(let i=1;i<=t.length;i++)for(let s=1;s<=u.length;s++){let n=1;u[s-1]===t[i-1]?n=0:n=1,e[s][i]=Math.min(e[s-1][i]+1,e[s][i-1]+1,e[s-1][i-1]+n),s>1&&i>1&&u[s-1]===t[i-2]&&u[s-2]===t[i-1]&&(e[s][i]=Math.min(e[s][i],e[s-2][i-2]+1))}return e[u.length][t.length]}function kt(u,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let e=u.startsWith("--");e&&(u=u.slice(2),t=t.map(r=>r.slice(2)));let i=[],s=3,n=.4;return t.forEach(r=>{if(r.length<=1)return;let a=Vt(u,r),o=Math.max(u.length,r.length);(o-a)/o>n&&(a<s?(s=a,i=[r]):a===s&&i.push(r))}),i.sort((r,a)=>r.localeCompare(a)),e&&(i=i.map(r=>`--${r}`)),i.length>1?`
|
|
13
|
-
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
14
|
-
(Did you mean ${i[0]}?)`:""}nt.suggestSimilar=kt});var ut=y(X=>{"use strict";var Ht=E("node:events").EventEmitter,K=E("node:child_process"),A=E("node:path"),k=E("node:fs"),d=E("node:process"),{Argument:Tt,humanReadableArgName:Pt}=V(),{CommanderError:Y}=v(),{Help:Wt,stripColor:Dt}=L(),{Option:ot,DualOptions:Ft}=J(),{suggestSimilar:at}=rt(),z=class u extends Ht{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:e=>d.stdout.write(e),writeErr:e=>d.stderr.write(e),outputError:(e,i)=>i(e),getOutHelpWidth:()=>d.stdout.isTTY?d.stdout.columns:void 0,getErrHelpWidth:()=>d.stderr.isTTY?d.stderr.columns:void 0,getOutHasColors:()=>Q()??(d.stdout.isTTY&&d.stdout.hasColors?.()),getErrHasColors:()=>Q()??(d.stderr.isTTY&&d.stderr.hasColors?.()),stripColor:e=>Dt(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,i){let s=e,n=i;typeof s=="object"&&s!==null&&(n=s,s=null),n=n||{};let[,r,a]=t.match(/([^ ]+) *(.*)/),o=this.createCommand(r);return s&&(o.description(s),o._executableHandler=!0),n.isDefault&&(this._defaultCommandName=o._name),o._hidden=!!(n.noHelp||n.hidden),o._executableFile=n.executableFile||null,a&&o.arguments(a),this._registerCommand(o),o.parent=this,o.copyInheritedSettings(this),s?this:o}createCommand(t){return new u(t)}createHelp(){return Object.assign(new Wt,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
15
|
-
- specify the name in Command constructor or using .name()`);return e=e||{},e.isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new Tt(t,e)}argument(t,e,i,s){let n=this.createArgument(t,e);return typeof i=="function"?n.default(s).argParser(i):n.default(i),this.addArgument(n),this}arguments(t){return t.trim().split(/ +/).forEach(e=>{this.argument(e)}),this}addArgument(t){let e=this.registeredArguments.slice(-1)[0];if(e&&e.variadic)throw new Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,this;t=t??"help [command]";let[,i,s]=t.match(/([^ ]+) *(.*)/),n=e??"display help for command",r=this.createCommand(i);return r.helpOption(!1),s&&r.arguments(s),n&&r.description(n),this._addImplicitHelpCommand=!0,this._helpCommand=r,this}addHelpCommand(t,e){return typeof t!="object"?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,e){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
|
|
16
|
-
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync")throw e},this}_exit(t,e,i){this._exitCallback&&this._exitCallback(new Y(t,e,i)),d.exit(t)}action(t){let e=i=>{let s=this.registeredArguments.length,n=i.slice(0,s);return this._storeOptionsAsProperties?n[s]=this:n[s]=this.opts(),n.push(this),t.apply(this,n)};return this._actionHandler=e,this}createOption(t,e){return new ot(t,e)}_callParseArg(t,e,i,s){try{return t.parseArg(e,i)}catch(n){if(n.code==="commander.invalidArgument"){let r=`${s} ${n.message}`;this.error(r,{exitCode:n.exitCode,code:n.code})}throw n}}_registerOption(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
17
|
-
- already used by option '${e.flags}'`)}this.options.push(t)}_registerCommand(t){let e=s=>[s.name()].concat(s.aliases()),i=e(t).find(s=>this._findCommand(s));if(i){let s=e(this._findCommand(i)).join("|"),n=e(t).join("|");throw new Error(`cannot add command '${n}' as already have command '${s}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let e=t.name(),i=t.attributeName();if(t.negate){let n=t.long.replace(/^--no-/,"--");this._findOption(n)||this.setOptionValueWithSource(i,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(i,t.defaultValue,"default");let s=(n,r,a)=>{n==null&&t.presetArg!==void 0&&(n=t.presetArg);let o=this.getOptionValue(i);n!==null&&t.parseArg?n=this._callParseArg(t,n,o,r):n!==null&&t.variadic&&(n=t._concatValue(n,o)),n==null&&(t.negate?n=!1:t.isBoolean()||t.optional?n=!0:n=""),this.setOptionValueWithSource(i,n,a)};return this.on("option:"+e,n=>{let r=`error: option '${t.flags}' argument '${n}' is invalid.`;s(n,r,"cli")}),t.envVar&&this.on("optionEnv:"+e,n=>{let r=`error: option '${t.flags}' value '${n}' from env '${t.envVar}' is invalid.`;s(n,r,"env")}),this}_optionEx(t,e,i,s,n){if(typeof e=="object"&&e instanceof ot)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(e,i);if(r.makeOptionMandatory(!!t.mandatory),typeof s=="function")r.default(n).argParser(s);else if(s instanceof RegExp){let a=s;s=(o,h)=>{let l=a.exec(o);return l?l[0]:h},r.default(n).argParser(s)}else r.default(s);return this.addOption(r)}option(t,e,i,s){return this._optionEx({},t,e,i,s)}requiredOption(t,e,i,s){return this._optionEx({mandatory:!0},t,e,i,s)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,i){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(t)!==void 0&&(e=i.getOptionValueSource(t))}),e}_prepareUserArgs(t,e){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},t===void 0&&e.from===void 0){d.versions?.electron&&(e.from="electron");let s=d.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(e.from="eval")}t===void 0&&(t=d.argv),this.rawArgs=t.slice();let i;switch(e.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":d.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return this._parseCommand([],i),this}async parseAsync(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
18
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,e,i){if(k.existsSync(t))return;let s=e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",n=`'${t}' does not exist
|
|
19
|
-
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
|
-
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
-
- ${s}`;throw new Error(n)}_executeSubCommand(t,e){e=e.slice();let i=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function n(l,c){let p=A.resolve(l,c);if(k.existsSync(p))return p;if(s.includes(A.extname(c)))return;let m=s.find(H=>k.existsSync(`${p}${H}`));if(m)return`${p}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let l;try{l=k.realpathSync(this._scriptPath)}catch{l=this._scriptPath}a=A.resolve(A.dirname(l),a)}if(a){let l=n(a,r);if(!l&&!t._executableFile&&this._scriptPath){let c=A.basename(this._scriptPath,A.extname(this._scriptPath));c!==this._name&&(l=n(a,`${c}-${t._name}`))}r=l||r}i=s.includes(A.extname(r));let o;d.platform!=="win32"?i?(e.unshift(r),e=lt(d.execArgv).concat(e),o=K.spawn(d.argv[0],e,{stdio:"inherit"})):o=K.spawn(r,e,{stdio:"inherit"}):(this._checkForMissingExecutable(r,a,t._name),e.unshift(r),e=lt(d.execArgv).concat(e),o=K.spawn(d.execPath,e,{stdio:"inherit"})),o.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(c=>{d.on(c,()=>{o.killed===!1&&o.exitCode===null&&o.kill(c)})});let h=this._exitCallback;o.on("close",l=>{l=l??1,h?h(new Y(l,"commander.executeSubCommandAsync","(close)")):d.exit(l)}),o.on("error",l=>{if(l.code==="ENOENT")this._checkForMissingExecutable(r,a,t._name);else if(l.code==="EACCES")throw new Error(`'${r}' not executable`);if(!h)d.exit(1);else{let c=new Y(1,"commander.executeSubCommandAsync","(error)");c.nestedError=l,h(c)}}),this.runningCommand=o}_dispatchSubcommand(t,e,i){let s=this._findCommand(t);s||this.help({error:!0}),s._prepareForParse();let n;return n=this._chainOrCallSubCommandHook(n,s,"preSubcommand"),n=this._chainOrCall(n,()=>{if(s._executableHandler)this._executeSubCommand(s,e.concat(i));else return s._parseCommand(e,i)}),n}_dispatchHelpCommand(t){t||this.help();let e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&this.args[e]==null&&this.missingArgument(t.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let t=(i,s,n)=>{let r=s;if(s!==null&&i.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${i.name()}'.`;r=this._callParseArg(i,s,n,a)}return r};this._checkNumberOfArguments();let e=[];this.registeredArguments.forEach((i,s)=>{let n=i.defaultValue;i.variadic?s<this.args.length?(n=this.args.slice(s),i.parseArg&&(n=n.reduce((r,a)=>t(i,a,r),i.defaultValue))):n===void 0&&(n=[]):s<this.args.length&&(n=this.args[s],i.parseArg&&(n=t(i,n,i.defaultValue))),e[s]=n}),this.processedArgs=e}_chainOrCall(t,e){return t&&t.then&&typeof t.then=="function"?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let i=t,s=[];return this._getCommandAndAncestors().reverse().filter(n=>n._lifeCycleHooks[e]!==void 0).forEach(n=>{n._lifeCycleHooks[e].forEach(r=>{s.push({hookedCommand:n,callback:r})})}),e==="postAction"&&s.reverse(),s.forEach(n=>{i=this._chainOrCall(i,()=>n.callback(n.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,e,i){let s=t;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(n=>{s=this._chainOrCall(s,()=>n(this,e))}),s}_parseCommand(t,e){let i=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),e=i.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},n=`command:${this.name()}`;if(this._actionHandler){s(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(n,t,e)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent&&this.parent.listenerCount(n))s(),this._processArguments(),this.parent.emit(n,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(e=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find(e=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(e=>{e.mandatory&&t.getOptionValue(e.attributeName())===void 0&&t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(i=>{let s=i.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});t.filter(i=>i.conflictsWith.length>0).forEach(i=>{let s=t.find(n=>i.conflictsWith.includes(n.attributeName()));s&&this._conflictingOption(i,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let e=[],i=[],s=e,n=t.slice();function r(o){return o.length>1&&o[0]==="-"}let a=null;for(;n.length;){let o=n.shift();if(o==="--"){s===i&&s.push(o),s.push(...n);break}if(a&&!r(o)){this.emit(`option:${a.name()}`,o);continue}if(a=null,r(o)){let h=this._findOption(o);if(h){if(h.required){let l=n.shift();l===void 0&&this.optionMissingArgument(h),this.emit(`option:${h.name()}`,l)}else if(h.optional){let l=null;n.length>0&&!r(n[0])&&(l=n.shift()),this.emit(`option:${h.name()}`,l)}else this.emit(`option:${h.name()}`);a=h.variadic?h:null;continue}}if(o.length>2&&o[0]==="-"&&o[1]!=="-"){let h=this._findOption(`-${o[1]}`);if(h){h.required||h.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${h.name()}`,o.slice(2)):(this.emit(`option:${h.name()}`),n.unshift(`-${o.slice(2)}`));continue}}if(/^--[^=]+=/.test(o)){let h=o.indexOf("="),l=this._findOption(o.slice(0,h));if(l&&(l.required||l.optional)){this.emit(`option:${l.name()}`,o.slice(h+1));continue}}if(r(o)&&(s=i),(this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(o)){e.push(o),n.length>0&&i.push(...n);break}else if(this._getHelpCommand()&&o===this._getHelpCommand().name()){e.push(o),n.length>0&&e.push(...n);break}else if(this._defaultCommandName){i.push(o),n.length>0&&i.push(...n);break}}if(this._passThroughOptions){s.push(o),n.length>0&&s.push(...n);break}s.push(o)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let i=0;i<e;i++){let s=this.options[i].attributeName();t[s]=s===this._versionOptionName?this._version:this[s]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t}
|
|
22
|
-
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
|
-
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
24
|
-
`),this.outputHelp({error:!0}));let i=e||{},s=i.exitCode||1,n=i.code||"commander.error";this._exit(s,n,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in d.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,d.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new Ft(this.options),e=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(s=>!e(s)).forEach(s=>{this.setOptionValueWithSource(s,i.implied[s],"implied")})})}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){let i=r=>{let a=r.attributeName(),o=this.getOptionValue(a),h=this.options.find(c=>c.negate&&a===c.attributeName()),l=this.options.find(c=>!c.negate&&a===c.attributeName());return h&&(h.presetArg===void 0&&o===!1||h.presetArg!==void 0&&o===h.presetArg)?h:l||r},s=r=>{let a=i(r),o=a.attributeName();return this.getOptionValueSource(o)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},n=`error: ${s(t)} cannot be used with ${s(e)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let s=[],n=this;do{let r=n.createHelp().visibleOptions(n).filter(a=>a.long).map(a=>a.long);s=s.concat(r),n=n.parent}while(n&&!n._enablePositionalOptions);e=at(t,s)}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=e===1?"":"s",n=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${e} argument${i} but got ${t.length}.`;this.error(n,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(n=>{s.push(n.name()),n.alias()&&s.push(n.alias())}),e=at(t,s)}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let s=this.createOption(e,i);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
25
|
-
`),this._exit(0,"commander.version",t)}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let s=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${s}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(i=>Pt(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=A.basename(t,A.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let s=e.formatHelp(this,e);return i.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(t){t=t||{};let e=!!t.error,i,s,n;return e?(i=a=>this._outputConfiguration.writeErr(a),s=this._outputConfiguration.getErrHasColors(),n=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),s=this._outputConfiguration.getOutHasColors(),n=this._outputConfiguration.getOutHelpWidth()),{error:e,write:a=>(s||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:s,helpWidth:n}}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let i=this._getOutputContext(t),s={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let n=this.helpInformation({error:i.error});if(e&&(n=e(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",s))}helpOption(t,e){return typeof t=="boolean"?(t?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(t=t??"-h, --help",e=e??"display help for command",this._helpOption=this.createOption(t,e),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this}help(t){this.outputHelp(t);let e=Number(d.exitCode??0);e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
|
|
26
|
-
Expecting one of '${i.join("', '")}'`);let s=`${t}Help`;return this.on(s,n=>{let r;typeof e=="function"?r=e({error:n.error,command:n.command}):r=e,r&&n.write(`${r}
|
|
27
|
-
`)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(s=>e.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function lt(u){return u.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",s="9229",n;return(n=t.match(/^(--inspect(-brk)?)$/))!==null?e=n[1]:(n=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=n[1],/^\d+$/.test(n[3])?s=n[3]:i=n[3]):(n=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=n[1],i=n[3],s=n[4]),e&&s!=="0"?`${e}=${i}:${parseInt(s)+1}`:t})}function Q(){if(d.env.NO_COLOR||d.env.FORCE_COLOR==="0"||d.env.FORCE_COLOR==="false")return!1;if(d.env.FORCE_COLOR||d.env.CLICOLOR_FORCE!==void 0)return!0}X.Command=z;X.useColor=Q});var pt=y(_=>{"use strict";var{Argument:ht}=V(),{Command:Z}=ut(),{CommanderError:jt,InvalidArgumentError:ct}=v(),{Help:It}=L(),{Option:dt}=J();_.program=new Z;_.createCommand=u=>new Z(u);_.createOption=(u,t)=>new dt(u,t);_.createArgument=(u,t)=>new ht(u,t);_.Command=Z;_.Option=dt;_.Argument=ht;_.Help=It;_.CommanderError=jt;_.InvalidArgumentError=ct;_.InvalidOptionArgumentError=ct});import _t from"node:fs";import w from"node:path";import{fileURLToPath as qt}from"node:url";import{spawn as Mt}from"node:child_process";var mt=xt(pt(),1),{program:Qt,createCommand:Xt,createArgument:Zt,createOption:te,CommanderError:ee,InvalidArgumentError:ie,InvalidOptionArgumentError:se,Command:ft,Argument:ne,Option:re,Help:oe}=mt.default;var gt={name:"tochibuild",version:"2.5.0",description:"An extremely fast JavaScript/Typescript and CSS bundler with minimal configuration.",repository:"https://github.com/tochiResources/project/tree/main/packages/build/tochibuild.git",license:"MIT",keywords:["bundler","build","typescript","javascript","tsup","esbuild","glob","cli","node","tochi","tochiResources"],bin:"./dist/cli.mjs",scripts:{dev:"tsx cli.ts",copybundler:"copyfiles ./tsup@8.4.0-minified/* ./dist",build:"tsx cli.ts && bun run copybundler","build:release":"bun run build && bun run release",release:"bun publish --access public --no-private"},dependencies:{chalk:"^5.4.1",commander:"^13.1.0",deepmerge:"^4.3.1",tsup:"8.4.0"},devDependencies:{"@types/node":"^22.15.17",copyfiles:"^2.4.1",tsx:"^4.19.4",typescript:"^5.8.3"},main:"dist/index.mjs",types:"dist/index.d.mts",exports:{".":{types:"./dist/index.d.mts",require:"./dist/index.mjs",import:"./dist/index.mjs"},"./utils":{types:"./dist/utils.d.mts",import:"./dist/utils.mjs",require:"./dist/utils.mjs"}},engines:{node:">=18.17.0"},files:["dist"]};var Rt=qt(import.meta.url),Lt=w.dirname(Rt),Ct=w.resolve(process.cwd(),"."),Ot=Ct.replace(/\\/g,"/").includes("packages/build");async function bt(u){let t={node:w.join(Lt,"tsup@8.4.0-minified/cli-node.js")},e=process.cwd(),i=[...[".ts",".js",".cjs",".json"].map(p=>w.join(e,`tochibuild.config${p}`)),...[".ts",".js",".cjs",".json"].map(p=>w.join(e,`tsup.config${p}`))],s=F.getPackageJson(),n=s.data?.tochibuild,r=s.data?.tsup,a=!!Object.keys(n||{}).length||!!Object.keys(r||{}).length,o=i.find(p=>_t.existsSync(p)),h=a||o,l=new ft("tochibuild").name("tochibuild <command>").description("bundle a Node.js project powered by tsup (https://tsup.egoist.dev)").allowUnknownOption(!0).version(gt.version).argument("[args...]","arguments to pass to tsup").action(async(...p)=>c(p));l.command("config").description("generate config files").option("--ext <string>","the file extension to use excluding the file extension (defaults to .ts)",".ts").option("-f, --filename <string>","the file name to use (defaults to tochibuild.config)","tochibuild.config").option("-o, --overwrite","whether or not to overwrite the config file if it already exists (defaults to false)",!1).option("--outDir <string...>","the absolute/relative output directory paths to create the config files in (defaults to the working directory)").action(p=>F.generateConfig(u,p,!1,!0)),l.parseAsync(process.argv);async function c(p){let[m]=p;return new Promise((H,$)=>{try{let T="node",f=[],P=m.includes("--config"),tt=m.includes("--no-config"),W=P?m.findIndex(g=>g==="--config")+1:void 0;if(!P&&!tt&&!h){if(m[0]==null||m[0]?.startsWith("-")){x.custom("error",`${C.red("No input files, try")} '${C.magenta(u)} ${C.gray("[...files]")}' ${C.red("instead")}`),$();return}f.push(...m)}else if(!P&&!tt&&h)if(a){let g=n||r;m.filter(O=>O.startsWith("-")).forEach(O=>{let b=m.findIndex(yt=>yt===O),At=O.startsWith("--")?O.slice(2):O.slice(1);if(g[At]||(f.push(O),f[b+1]?.startsWith("-")))return;let et=f[b+1];et&&f.push(et)}),Object.entries(g).forEach(([O,b])=>{typeof b=="boolean"||b==="true"||b==="false"?b&&f.push(`--${O}`):typeof b=="string"&&f.push(`--${O}`,b)}),f.push("--no-config")}else if(o){let g=w.relative(Ct,o).replace(/\\/g,"/");x.log(`using existing configuration file: ${C.gray(g)}`),f.push("--config",g),f.push(...m)}else f.push(...m);else{if(W!=null&&W>=0){let g=m[W]||"unspecified";_t.existsSync(g)||(x.error(void 0,`config file '${g}' does not exist`),x.info(`try running '${C.magenta(u)} ${C.blue("config")} ${C.gray("-h")}' to get help on how to generate a config file`),process.exit(1))}f.push(...m)}x.log(`running build${Ot||s.data?.name?` for ${C.magenta(Ot?u:s.data.name)}`:""}...`);let D=Mt("node",[t[T],...f],{stdio:"inherit",shell:!0,cwd:process.cwd(),env:process.env});D.on("exit",g=>{process.exit(g??1)}),process.on("SIGINT",()=>{$(),D.kill("SIGINT")}),process.on("SIGTERM",()=>{$(),D.kill("SIGTERM")}),H()}catch(T){$(T)}})}}bt("@tochii/build");
|
|
2
|
+
import{a as r,b as V,c as N,d as Y,e as T,f as Z,g as ee,h as D}from"./chunk-S6QAP2TG.mjs";import Ce from"node:fs";import ve from"node:path";import I from"chalk";import{Command as Le}from"commander";import{build as Be}from"tsup";var J={name:"tochibuild",version:"2.6.0",description:"An extremely fast JavaScript/Typescript and CSS bundler with minimal configuration.",repository:"https://github.com/tochiResources/project/tree/main/packages/build/tochibuild.git",license:"MIT",keywords:["bundler","build","typescript","javascript","tsup","esbuild","glob","cli","node","tochi","tochiResources"],bin:"./dist/cli.mjs",scripts:{dev:"tsx cli.ts",copybundler:"copyfiles ./tsup@8.4.0-minified/* ./dist",build:"tsx cli.ts && bun run copybundler","build:release":"bun run build && bun run release",release:"bun publish --access public --no-private"},dependencies:{"@npmcli/arborist":"^9.1.1","bundle-require":"5.1.0",chalk:"^5.4.1",commander:"^13.1.0","cross-spawn":"^7.0.6",deepmerge:"^4.3.1","fast-glob":"^3.3.3",joycon:"3.1.1","npm-packlist":"^10.0.0","strip-json-comments":"5.0.1",tar:"^7.4.3",tsup:"8.4.0"},devDependencies:{"@types/cross-spawn":"^6.0.6","@types/node":"^22.15.17",copyfiles:"^2.4.1",tsx:"^4.19.4",typescript:"^5.8.3"},engines:{node:">=18.17.0"},files:["dist","types"]};function A(e,n){return n.command("[files...]","Bundle files").option("--entry <file>","Use a key-value pair as entry files").option("-d, --out-dir <dir>","Output directory").option("--format <format...>",'Bundle format, "cjs", "iife", "esm"').option("--minify [terser]","Minify bundle").option("--minify-whitespace","Minify whitespace").option("--minify-identifiers","Minify identifiers").option("--minify-syntax","Minify syntax").option("--keep-names","Keep original function and class names in minified code").option("--target <target...>",'Bundle target, "es20XX" or "esnext"').option("--legacy-output","Output different formats to different folder instead of using different extensions").option("--dts [entry]","Generate declaration file").option("--dts-resolve","Resolve externals types used for d.ts files").option("--dts-only","Emit declaration files only").option("--experimental-dts [entry]","Generate declaration file (experimental)").option("--sourcemap [inline]","Generate external sourcemap, or inline source: --sourcemap inline").option("--watch [path...]",'Watch mode, if path is not specified, it watches the current folder ".". Repeat "--watch" for more than one path').option("--ignore-watch <path...>","Ignore custom paths in watch mode").option("--onSuccess <command>","Execute command after successful build, specially useful for watch mode").option("--env.* <value>","Define compile-time env variables").option("--inject <file>","Replace a global variable with an import from another file").option("--define.* <value>","Define compile-time constants").option("--external <name>","Mark specific packages / package.json (dependencies and peerDependencies) as external").option("--global-name <name>","Global variable name for iife format").option("--jsxFactory <jsxFactory>","Name of JSX factory function").option("--jsxFragment <jsxFragment>","Name of JSX fragment function").option("--replaceNodeEnv","Replace process.env.NODE_ENV").option("--no-splitting","Disable code splitting").option("--clean","Clean output directory").option("--silent",'Suppress non-error logs (excluding "onSuccess" process output)').option("--pure <express...>","Mark specific expressions as pure").option("--metafile","Emit esbuild metafile (a JSON file)").option("--platform <platform>","Target platform").option("--loader <ext=loader>","Specify the loader for a file extension").option("--tsconfig <filename>","Use a custom tsconfig").option("--config <filename>","Use a custom config file").option("--no-config","Disable config file").option("--shims","Enable cjs and esm shims").option("--inject-style","Inject style tag to document head").option("--treeshake [strategy]",'Using Rollup for treeshaking instead, "recommended" or "smallest" or "safest"').option("--publicDir [dir]","Copy public directory to output directory").option("--killSignal <signal>",'Signal to kill child process, "SIGTERM" or "SIGKILL"').option("--cjsInterop","Enable cjs interop")}function H(e,n){n.command("config").description("Generate config files").option("--ext <string>","the file extension to use excluding the file extension (defaults to .ts)",".ts").option("-f, --filename <string>","the file name to use (defaults to tochibuild.config)","tochibuild.config").option("-o, --overwrite","whether or not to overwrite the config file if it already exists (defaults to false)",!1).option("--outDir <string...>","the absolute/relative output directory paths to create the config files in (defaults to the working directory)").action(s=>D.generateConfig(e,s,!1,!0))}import we from"node:path";import E from"chalk";import W from"node:fs";import C from"node:path";import w from"chalk";import oe from"joycon";import{bundleRequire as ge}from"bundle-require";import me from"strip-json-comments";import M from"chalk";var te={"--format":"esm","--minify":!1,"--sourcemap":!1,"--watch":!1,"--clean":!1,"--silent":!1,"--shims":!0,"--no-splitting":!1,"--treeshake":!0,"--cjsInterop":!0,"--platform":"neutral","--target":"esnext"};async function ie(e,n,s,o){let t={},i=[...n],f=a=>Array.isArray(a)?a:a.split(","),l=a=>a==="true"?!0:a==="false"?!1:isNaN(Number(a))?a:Number(a),p=a=>{let d=i.findIndex(L=>L===a||L.startsWith(`${a}=`));if(d===-1)return;let x=i[d];if(x.includes("="))return x.split("=").slice(1).join("=");let $=i[d+1];return!$||$.startsWith("-")?!0:$},g=a=>{let d=i.findIndex(x=>x===a||x.startsWith(`${a}=`));d!==-1&&(i[d].includes("=")?i.splice(d,1):i.splice(d,2))},h={"-d":"outDir","--out-dir":"outDir","--format":"format","--minify":"minify","--minify-whitespace":"minifyWhitespace","--minify-identifiers":"minifyIdentifiers","--minify-syntax":"minifySyntax","--keep-names":"keepNames","--target":"target","--legacy-output":"legacyOutput","--sourcemap":"sourcemap","--watch":"watch","--onSuccess":"onSuccess","--inject":"inject","--external":"external","--global-name":"globalName","--jsxFactory":"jsxFactory","--jsxFragment":"jsxFragment","--replaceNodeEnv":"replaceNodeEnv","--no-splitting":"splitting","--clean":"clean","--silent":"silent","--pure":"pure","--metafile":"metafile","--platform":"platform","--loader":"loader","--tsconfig":"tsconfig","--config":"config","--shims":"shims","--inject-style":"injectStyle","--treeshake":"treeshake","--publicDir":"publicDir","--killSignal":"killSignal","--cjsInterop":"cjsInterop"};for(let a of n)if(!(a in h)&&a!=="--no-config"&&!a.startsWith("--define."))return r.error(void 0,`Unknown CLI option: ${a}`),o&&process.exit(1),[];i.includes("--no-config")&&(t.config=!1,i.splice(i.indexOf("--no-config"),1));for(let[a,d]of Object.entries(h)){let x=a.startsWith("--")?a.replace(/^--/,"--no-"):null;if(x&&i.includes(x)){t[d]=!1,i.splice(i.indexOf(x),1);continue}let $=p(a);if($!==void 0){if(typeof $=="string"){let L=f($),ue=L.length>1?L.map(l):l(L[0]);t[d]=ue}else t[d]=$;g(a)}else a in te}let m=p("--dts"),c=i.includes("--dts-only"),b=i.includes("--dts-resolve");(m||c||b)&&(t.dts={},typeof m=="string"&&(t.dts.entry=m),c&&(t.dts.only=!0),b&&(t.dts.resolve=!0));let k=i.filter(a=>a.startsWith("--define."));if(k.length>0){t.define={};for(let a of k){let[,d]=a.split("--define."),[x,$]=d.split("=");t.define[x]=$}}let u=i.filter(a=>!a.startsWith("-"));u.length>0&&(t.entry=u);let y=s?await ee.mergeBuildOptionsAsync(s,{execute:!0,overrideOptions:t},!1,o):t,v=a=>Array.isArray(a)?a.length>0:Object.keys(a||{}).length>0;return(Array.isArray(y)?!y.some(a=>v(a.entry)):!v(y.entry))?(r.custom("error",`${M.red("No input files, try")} '${M.magenta(e)} ${M.gray("[...files]")}' ${M.red("instead")}`),o&&process.exit(1),[]):y}var O=process.cwd(),U=new oe,ne=async e=>{try{return he(await W.promises.readFile(e,"utf8"))}catch(n){throw n instanceof Error?new Error(`Failed to parse ${C.relative(O,e)}: ${n.message}`):n}};function he(e){try{return new Function(`return ${me(e).trim()}`)()}catch{return{}}}var ye={test:/\.json$/,load(e){return ne(e)}};U.addLoader(ye);async function be(e){let n=new oe,s=await n.resolve({files:e?[e]:["tochibuild.config.ts","tochibuild.config.cts","tochibuild.config.mts","tochibuild.config.js","tochibuild.config.cjs","tochibuild.config.mjs","tochibuild.config.json","package.json"],cwd:O,stopDir:C.parse(O).root,packageKey:"tochibuild"}),o=await n.resolve({files:e?[e]:["tsup.config.ts","tsup.config.cts","tsup.config.mts","tsup.config.js","tsup.config.cjs","tsup.config.mjs","tsup.config.json","package.json"],cwd:O,stopDir:C.parse(O).root,packageKey:"tsup"}),t=s||o;if(t){if(t.endsWith(".json")){let p=await ne(t);return t.endsWith("package.json")&&(p=p.tochibuild||p.tsup),p?{path:t,data:p}:{}}let i=await ge({filepath:t}),f=i.mod.tochibuild||i.mod.tsup||i.mod.default||i.mod,l=typeof f=="function"?await f():await f;return{path:t,data:l}}return{}}async function R(e=!1){return await B(["package.json"],e)}async function B(e,n=!1){n&&U.clearCache();let s=await U.load(e,O,C.dirname(O));return{...s,data:s.data||{}}}async function ke(e,n,s){let o=n?process.argv.slice(2):[],t=n?o.includes("--config"):!1,i=n?o.includes("--no-config"):!1,f=[...[".ts",".js",".cjs",".json"].map(d=>C.join(O,`tochibuild.config${d}`)),...[".ts",".js",".cjs",".json"].map(d=>C.join(O,`tsup.config${d}`))],l=s??await R(!0),p=l.data?.tochibuild,g=l.data?.tsup,h=p||g,m=!!Object.keys(h||{}).length,c=f.find(d=>W.existsSync(d)),b=m||!!c,k=c?C.relative(O,c).replace(/\\/g,"/"):void 0,u;if(!i&&c&&!t)u=c,r.log(`using existing configuration file: ${w.gray(k)}`);else if(!i&&!c&&t){if(u=o[o.indexOf("--config")+1],!W.existsSync(u)){r.error(void 0,`config file '${u}' does not exist`),r.info(`try running '${w.magenta(e)} ${w.blue("config")} ${w.gray("-h")}' to get help on how to generate a config file`);return}r.log(`using configuration file: ${w.gray(u)}`)}else if(!i&&!b&&!t){if(!n){r.error(void 0,"no configuration file found"),r.info(`try running '${w.magenta(e)} ${w.blue("config")} ${w.gray("-h")}' to get help on how to generate a config file`);return}if(o[0]==null||o[0]?.startsWith("-")){r.custom("error",`${w.red("No input files, try")} '${w.magenta(e)} ${w.gray("[...files]")}' ${w.red("instead")}`);return}}let v=await(async()=>{if(h)return h;if(!i&&(c||u))return(await be(c||u)).data})(),a=await ie(e,o,v,n).catch(d=>r.error(void 0,d?.message));if(a)return Array.isArray(a)?a:[a]}var re=ke,ae=async(e,n)=>{let s=n||(await R(!0)).data;if(!e)return s;if(typeof e=="string")return(await B([e],!0)).data;if(typeof e=="function")return e(s);if(typeof e=="object"){let o=e,t=s;return o.path&&(t=(await B([o.path],!0)).data),typeof o.data=="function"?o.data(t):typeof o.data=="object"&&o.data!==null?{...t,...o.data}:{...t,...e}}return s};function G(e,n){n.command("pack").description("Create a tarball (.tgz file) of the package").option("--dir <string>","path to the original package directory (relative/absolute) (defaults to the current working directory)").option("-p, --pkg <string>","the custom path to the package.json file (relative/absolute)","package.json").option("-o, --out <string>","the output tarball path (relative/absolute)","tochibuild.package.tgz").action(async s=>{let o={...s,dir:s.dir||we.relative(process.cwd(),".")||"."};r.info(`creating tarball with options:
|
|
3
|
+
${Object.entries(o).map(([l,p])=>`- ${l}: ${E.gray(p)}`).join(`
|
|
4
|
+
`)}`);let t;o.pkg&&o.pkg!=="package.json"&&(r.info(`loading custom package.json from ${E.gray(o.pkg)}`),t=await B([o.pkg],!0).then(l=>l.data));let i=await T({packageDir:process.cwd(),packageJsonData:t}),f=i.fileList.map(l=>`- ${E.gray(l)}`).join(`
|
|
5
|
+
`);r.success(`successfully created tarball from ${i.fileList.length} files:
|
|
6
|
+
${f}`),r.success(`tarball created at ${E.gray(i.tarballPath)}`)})}function _(e,n){n.command("merge").description("Merge the contents of all files into a single file").argument("<outFile>","the output file path (relative/absolute)").argument("<files...>","the files to merge into a single file (glob supported)").action(async(s,o)=>{try{await Z(o,s)}catch(t){r.error(void 0,t?.message)}})}var xe=[H,G,_],se=xe;import q from"chalk";import $e from"cross-spawn";import z from"chalk";function ce(e,n=[],s){return new Promise((o,t)=>{let i=$e(e,n,{stdio:"inherit",shell:!0,cwd:process.cwd(),env:process.env,...s});i.on("exit",f=>{f===0?o():t(new Error(`${e} exited with code ${f}`))}),i.on("error",t),process.on("SIGINT",()=>{t(),i.kill("SIGINT")}),process.on("SIGTERM",()=>{t(),i.kill("SIGTERM")})})}async function Oe(e,n,s,o,t){let i=t!=null?` #${t}`:"";if("cli"in e){let f=e.cli.name??n.packageManager,l=e.cli.args;return r.info(`running hook${i}: ${z.magenta(`${f}`)}${l.length?" ":""}${z.gray(l.join(" "))}`),await ce(f,l)}else if("action"in e){let f=e.name||"unnamed";return r.info(`running hook${i}: ${z.magenta(`${f}`)}`),await e.action(D,s,o)}}var j={cli:ce,hook:Oe};import le from"chalk";async function K(e){let n=e.packageManager||"npm",s=e.command||"deprecate",o=e.args||[];return r.info(`running hook: ${le.magenta(`${n} ${s}`)}${o.length?" ":""}${le.gray(o.join(" "))}`),j.cli(n,[s].concat(o))}import je from"node:fs";import Pe from"node:path";import F from"chalk";async function X(e,n){let s=e.packageManager||"npm",o=e.command||"publish",t=e.args||[];r.info(`running hook: ${F.magenta(`${s} ${o}`)}${t.length?" ":""}${F.gray(t.join(" "))}`);let i="",f="";if(t.length&&typeof t[0]=="string"&&!t[0].startsWith("-")&&t[0].endsWith(".tgz")&&(i=t[0].replace(/\\/g,"/"),f=Pe.relative(process.cwd(),i).replace(/\\/g,"/")),i)r.info(`using custom tarball ${f}`);else{r.info("creating tarball...");let l=await T({packageDir:process.cwd(),packageJsonData:n});i=l.tarballPath.replace(/\\/g,"/"),f=l.tarballRelativePath.replace(/\\/g,"/");let p=l.fileList.map(g=>`- ${F.gray(g)}`).join(`
|
|
7
|
+
`);r.success(`successfully created tarball from ${l.fileList.length} files:
|
|
8
|
+
${p}`),r.info(`tarball created at ${F.gray(l.tarballRelativePath)}`)}if(!je.existsSync(i))throw new Error(`tarball not found at ${f}`);return r.info("publishing package from tarball..."),j.cli(s,[o].concat(i).concat(t))}async function P(e,n,s,o){return Array.isArray(e)?await Promise.all(e.map((t,i)=>j.hook(t,n,s,o,i+1))):await j.hook(e,n,s,o,1)}async function Q(e,n){let s=e?.tochibuildConfig,o=s?.lifecycle,t=o?.access||"restricted",i=o?.packageManager||"npm",f=o?.registry||"https://registry.npmjs.org/",l=await ae(o?.packageJson,n),p=o?.hooks,g={publish:p?.publish?{access:t,packageManager:i,command:"publish",...p?.publish,args:p?.publish?.args||[]}:void 0,deprecate:p?.deprecate?{access:t,packageManager:i,command:"deprecate",...p?.deprecate,args:p?.deprecate?.args||[]}:void 0,custom:Array.isArray(p?.custom)?p?.custom:[]},h={access:t,packageManager:i,registry:f,packageJson:l,hooks:g},m={beforeBuild:g.custom.filter(c=>c.position==="before.build"),beforePublish:g.custom.filter(c=>c.position==="before.publish"),beforeDeprecate:g.custom.filter(c=>c.position==="before.deprecate"),afterBuild:g.custom.filter(c=>c.position==="after.build"),afterPublish:g.custom.filter(c=>c.position==="after.publish"),afterDeprecate:g.custom.filter(c=>c.position==="after.deprecate")};return{access:t,packageManager:i,registry:f,packageJson:l,hooks:{...g,custom:m},runner:j,runHooks:async c=>new Promise(async(b,k)=>{try{let u=s,y;switch(c){case"publish":if(!g.publish)break;y=X(g.publish,l);break;case"deprecate":if(!g.deprecate)break;y=K(g.deprecate);break;case"custom.before.build":if(!m.beforeBuild.length)break;y=P(m.beforeBuild,h,u);break;case"custom.before.publish":if(!m.beforePublish.length)break;y=P(m.beforePublish,h,u);break;case"custom.before.deprecate":if(!m.beforeDeprecate.length)break;y=P(m.beforeDeprecate,h,u);break;case"custom.after.build":if(!m.afterBuild.length)break;y=P(m.afterBuild,h,u);break;case"custom.after.publish":if(!m.afterPublish.length)break;y=P(m.afterPublish,h,u);break;case"custom.after.deprecate":if(!m.afterDeprecate.length)break;y=P(m.afterDeprecate,h,u);break;default:throw new Error(`Unknown lifecycle hook: ${q.magenta(c)}`)}let v=await y?.then(()=>r.success(`successfully ran lifecycle hook(s): ${q.magenta(c)}`));b(v)}catch(u){throw r.error(void 0,`failed to run lifecycle hook(s) ${q.magenta(c)}:`),u}})}}var S=process.cwd(),fe=S.replace(/\\/g,"/").includes("packages/build");r.initialize(S,J.version);async function pe(e){try{let n=new Le("tochibuild").name("tochibuild").description(J.description).version(J.version).allowUnknownOption(!0);A(e,n).action(async()=>s()),se.forEach(o=>o(e,n)),n.parseAsync(process.argv);async function s(){return new Promise(async(o,t)=>{let i;try{let l=process.argv.slice(2).includes("--no-config"),p=await R(!0),g=await re(e,!0).catch(h=>{r.error(void 0,h?.message),t()});if(!g)return;r.log(`running build${fe||p.data?.name?` for ${I.magenta(fe?e:p.data.name)}`:""}...`);for(let h=0;h<g.length;h++){if(i=V(`tochibuild.config.tmp-${Date.now()}.json`),!i)throw new Error("Temp config path is undefined.");let m=ve.relative(S,i).replace(/\\/g,"/"),c=g[h];typeof c.config=="string"&&(Ce.existsSync(c.config)||(r.error(void 0,`config file '${c.config}' does not exist`),r.info(`try running '${I.magenta(e)} ${I.blue("config")} ${I.gray("-h")}' to get help on how to generate a config file`),process.exit(1)));let b=await Q(c,p.data);await b.runHooks("custom.before.build");let k={...c};if(k.config!=null&&delete k.config,k.tochibuildConfig!=null&&delete k.tochibuildConfig,i=Y(i,JSON.stringify(k,null,4),{overwrite:!0,fsOptions:{encoding:"utf-8"}}),!i)throw new Error("Failed to create temp config file.");r.debug("options:",`
|
|
9
|
+
${Object.entries(k).map(([u,y])=>`- ${u}: ${I.gray(JSON.stringify(y,null,4))}`).join(`
|
|
10
|
+
`)}`),await Be({config:l?void 0:m,skipNodeModulesBundle:c.skipNodeModulesBundle??!0,clean:h>0?!1:c.clean}).catch(u=>{r.error(void 0,u?.message),t()}),await b.runHooks("custom.after.build"),await b.runHooks("custom.before.publish"),await b.runHooks("publish"),await b.runHooks("custom.after.publish"),await b.runHooks("custom.before.deprecate"),await b.runHooks("deprecate"),await b.runHooks("custom.after.deprecate"),N(S)}o()}catch(f){r.error(f),N(S),t()}})}}catch(n){r.error(n),process.exit(1)}}pe("@tochii/build");
|