@tochii/build 2.6.3 → 3.0.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-IRC4GCCU.mjs +16 -0
- package/dist/cli.mjs +9 -9
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/package.json +5 -2
- package/dist/chunk-S6QAP2TG.mjs +0 -16
|
@@ -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} file(s) 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,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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.3",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","publish","lifecycle","hooks","cli","node","tochi","tochiResources"],bin:"./dist/cli.mjs",scripts:{dev:"tsx cli.ts"},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",tsx:"^4.19.4",typescript:"^5.8.3"},files:["dist"],engines:{node:">=18.17.0"}};function A(e,n){return n.argument("[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(([
|
|
4
|
-
`)}`);let
|
|
5
|
-
`);
|
|
6
|
-
${
|
|
7
|
-
`);
|
|
8
|
-
${
|
|
9
|
-
${Object.entries(
|
|
10
|
-
`)}`),await
|
|
2
|
+
import{a,b as _,c as I,d as Q,e as B,f as Y,g as Z,h as T}from"./chunk-IRC4GCCU.mjs";import Oe from"node:fs";import je from"node:path";import j from"chalk";import ve from"cac";import{build as Le}from"tsup";var E={name:"tochibuild",version:"3.0.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","publish","lifecycle","hooks","cli","node","tochi","tochiResources"],bin:"./dist/cli.mjs",scripts:{dev:"tsx cli.ts"},dependencies:{"@npmcli/arborist":"^9.1.1","bundle-require":"5.1.0",cac:"^6.7.14",chalk:"^5.4.1","cross-spawn":"^7.0.6",deepmerge:"^4.3.1","fast-glob":"^3.3.3",flat:"^6.0.1",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",tsx:"^4.19.4",typescript:"^5.8.3"},files:["dist"],engines:{node:">=18.17.0"}};function H(e,r){return r.command("[...files]","Bundle files",{ignoreOptionDefaultValue:!0}).option("--entry.* <file>","Use a key-value pair as entry files").option("-d, --out-dir <dir>","Output directory",{default:"dist"}).option("--format <format>",'Bundle format, "cjs", "iife", "esm"',{default:"cjs"}).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"',{default:"es2017"}).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",{default:"React.createElement"}).option("--jsxFragment <jsxFragment>","Name of JSX fragment function",{default:"React.Fragment"}).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",{default:"node"}).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 A(e,r){r.command("config","Generate config files").option("--ext <string>","The file extension to use (excluding the dot, defaults to '.ts')",{default:".ts"}).option("-f, --filename <string>","The file name to use (defaults to tochibuild.config)",{default:"tochibuild.config"}).option("-o, --overwrite","Overwrite existing config file",{default:!1}).option("--outDir <string>","Output directory paths to create the config in",{default:["."],type:[]}).action(t=>T.generateConfig(e,t,!1,!0))}import ke from"node:path";import D from"chalk";import F from"node:fs";import C from"node:path";import P from"chalk";import ee from"joycon";import{bundleRequire as de}from"bundle-require";import ge from"strip-json-comments";import R from"chalk";import{flatten as pe}from"flat";function M(e){return Array.isArray(e)?e:e.split(",")}function ue(e){return e.startsWith("\\\\?\\")?e:e.replace(/\\/g,"/")}async function V(e,r,t,o,n){let i={},l=t.config===!1;if(Object.assign(i,{...t}),!i.entry&&r.length>0&&(i.entry=r.map(ue)),t.format){let c=M(t.format);i.format=c}if(t.external){let c=M(t.external);i.external=c}if(t.target&&(i.target=t.target.includes(",")?t.target.split(","):t.target),(t.dts||t.dtsResolve||t.dtsOnly)&&(i.dts={},typeof t.dts=="string"&&(i.dts.entry=t.dts),t.dtsResolve&&(i.dts.resolve=t.dtsResolve),t.dtsOnly&&(i.dts.only=!0)),t.inject){let c=M(t.inject);i.inject=c}if(t.define){let c=pe(t.define);i.define=c}if(t.loader){let c=M(t.loader);i.loader=c.reduce((y,u)=>{let p=u.split("=");return{...y,[p[0]]:p[1]}},{})}let s=!l&&o?await Z.mergeBuildOptionsAsync(o,{execute:!0,overrideOptions:i},!1,n):i,f=c=>Array.isArray(c)?c.length>0:Object.keys(c||{}).length>0;return(Array.isArray(s)?!s.some(c=>f(c.entry)):!f(s.entry))?(a.custom("error",`${R.red("No input files, try")} '${R.magenta(e)} ${R.gray("[...files]")}' ${R.red("instead")}`),n&&process.exit(1),[]):s}var k=process.cwd(),N=new ee,te=async e=>{try{return me(await F.promises.readFile(e,"utf8"))}catch(r){throw r instanceof Error?new Error(`Failed to parse ${C.relative(k,e)}: ${r.message}`):r}};function me(e){try{return new Function(`return ${ge(e).trim()}`)()}catch{return{}}}var ye={test:/\.json$/,load(e){return te(e)}};N.addLoader(ye);async function he(e){let r=new ee,t=await r.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:k,stopDir:C.parse(k).root,packageKey:"tochibuild"}),o=await r.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:k,stopDir:C.parse(k).root,packageKey:"tsup"}),n=t||o;if(n){if(n.endsWith(".json")){let f=await te(n);return n.endsWith("package.json")&&(f=f.tochibuild||f.tsup),f?{path:n,data:f}:{}}let i=await de({filepath:n}),l=i.mod.tochibuild||i.mod.tsup||i.mod.default||i.mod,s=typeof l=="function"?await l():await l;return{path:n,data:s}}return{}}async function J(e=!1){return await O(["package.json"],e)}async function O(e,r=!1){r&&N.clearCache();let t=await N.load(e,k,C.dirname(k));return{...t,data:t.data||{}}}async function be(e,r,t,o,n){let i=o?process.argv.slice(2):[],l=o?i.includes("--config"):!1,s=o?t.config===!1:!1,f=[...[".ts",".js",".cjs",".json"].map(x=>C.join(k,`tochibuild.config${x}`)),...[".ts",".js",".cjs",".json"].map(x=>C.join(k,`tsup.config${x}`))],c=n??await J(!0),y=c.data?.tochibuild,u=c.data?.tsup,p=y||u,h=!!Object.keys(p||{}).length,g=f.find(x=>F.existsSync(x)),d=h||!!g,m=g?C.relative(k,g).replace(/\\/g,"/"):void 0,b;if(!s&&g&&!l)b=g,a.log(`using existing configuration file: ${P.gray(m)}`);else if(!s&&!g&&l){if(b=i[i.indexOf("--config")+1],!F.existsSync(b)){a.error(void 0,`config file '${b}' does not exist`),a.info(`try running '${P.magenta(e)} ${P.blue("config")} ${P.gray("-h")}' to get help on how to generate a config file`);return}a.log(`using configuration file: ${P.gray(b)}`)}else if(!s&&!d&&!l){a.error(void 0,"no configuration file found"),a.info(`try running '${P.magenta(e)} ${P.blue("config")} ${P.gray("-h")}' to get help on how to generate a config file`);return}let le=await(async()=>{if(p)return p;if(!s&&(g||b))return(await he(g||b)).data})(),L=await V(e,r,t,le,o).catch(x=>a.error(void 0,x?.message));if(L)return Array.isArray(L)?L:[L]}var oe=be,ie=async(e,r)=>{let t=r||(await J(!0)).data;if(!e)return t;if(typeof e=="string")return(await O([e],!0)).data;if(typeof e=="function")return e(t);if(typeof e=="object"){let o=e,n=t;return o.path&&(n=(await O([o.path],!0)).data),typeof o.data=="function"?o.data(n):typeof o.data=="object"&&o.data!==null?{...n,...o.data}:{...n,...e}}return t};function G(e,r){r.command("pack","Create a tarball (.tgz file) of the package").option("--dir <string>","Path to the original package directory (relative/absolute)",{default:"."}).option("-p, --pkg <string>","Custom path to package.json (relative/absolute)",{default:"package.json"}).option("-o, --out <string>","Output tarball path (relative/absolute)",{default:"tochibuild.package.tgz"}).action(async t=>{let o={...t,dir:t.dir||ke.relative(process.cwd(),".")||"."};o["--"]&&delete o["--"],a.info(`creating tarball with options:
|
|
3
|
+
${Object.entries(o).map(([s,f])=>`- ${s}: ${D.gray(f)}`).join(`
|
|
4
|
+
`)}`);let n;o.pkg&&o.pkg!=="package.json"&&(a.info(`loading custom package.json from ${D.gray(o.pkg)}`),n=await O([o.pkg],!0).then(s=>s.data));let i=await B({packageDir:process.cwd(),packageJsonData:n}),l=i.fileList.map(s=>`- ${D.gray(s)}`).join(`
|
|
5
|
+
`);a.success(`successfully created tarball from ${i.fileList.length} files:
|
|
6
|
+
${l}`),a.success(`tarball created at ${D.gray(i.tarballPath)}`)})}function W(e,r){r.command("merge <outFile> <...files>","Merge the contents of all files into a single file").action(async(t,o)=>{try{await Y(o,t)}catch(n){a.error(void 0,n?.message)}})}var we=[A,G,W],ne=we;import X from"chalk";import xe from"cross-spawn";import U from"chalk";function re(e,r=[],t){return new Promise((o,n)=>{let i=xe(e,r,{stdio:"inherit",shell:!0,cwd:process.cwd(),env:process.env,...t});i.on("exit",l=>{l===0?o():n(new Error(`${e} exited with code ${l}`))}),i.on("error",n),process.on("SIGINT",()=>{n(),i.kill("SIGINT")}),process.on("SIGTERM",()=>{n(),i.kill("SIGTERM")})})}async function Pe(e,r,t,o,n){let i=n!=null?` #${n}`:"";if("cli"in e){let l=e.cli.name??r.packageManager,s=e.cli.args;return a.info(`running hook${i}: ${U.magenta(`${l}`)}${s.length?" ":""}${U.gray(s.join(" "))}`),await re(l,s)}else if("action"in e){let l=e.name||"unnamed";return a.info(`running hook${i}: ${U.magenta(`${l}`)}`),await e.action(T,t,o)}}var w={cli:re,hook:Pe};import ae from"chalk";async function z(e){let r=e.packageManager||"npm",t=e.command||"deprecate",o=e.args||[];return a.info(`running hook: ${ae.magenta(`${r} ${t}`)}${o.length?" ":""}${ae.gray(o.join(" "))}`),w.cli(r,[t].concat(o))}import $e from"node:fs";import Ce from"node:path";import S from"chalk";async function K(e,r){let t=e.packageManager||"npm",o=e.command||"publish",n=e.args||[];a.info(`running hook: ${S.magenta(`${t} ${o}`)}${n.length?" ":""}${S.gray(n.join(" "))}`);let i="",l="";if(n.length&&typeof n[0]=="string"&&!n[0].startsWith("-")&&n[0].endsWith(".tgz")&&(i=n[0].replace(/\\/g,"/"),l=Ce.relative(process.cwd(),i).replace(/\\/g,"/")),i)a.info(`using custom tarball ${l}`);else{a.info("creating tarball...");let s=await B({packageDir:process.cwd(),packageJsonData:r});i=s.tarballPath.replace(/\\/g,"/"),l=s.tarballRelativePath.replace(/\\/g,"/");let f=s.fileList.map(c=>`- ${S.gray(c)}`).join(`
|
|
7
|
+
`);a.success(`successfully created tarball from ${s.fileList.length} files:
|
|
8
|
+
${f}`),a.info(`tarball created at ${S.gray(s.tarballRelativePath)}`)}if(!$e.existsSync(i))throw new Error(`tarball not found at ${l}`);return a.info("publishing package from tarball..."),w.cli(t,[o].concat(i).concat(n))}async function $(e,r,t,o){return Array.isArray(e)?await Promise.all(e.map((n,i)=>w.hook(n,r,t,o,i+1))):await w.hook(e,r,t,o,1)}async function q(e,r){let t=e?.tochibuildConfig,o=t?.lifecycle,n=o?.access||"restricted",i=o?.packageManager||"npm",l=o?.registry||"https://registry.npmjs.org/",s=await ie(o?.packageJson,r),f=o?.hooks,c={publish:f?.publish?{access:n,packageManager:i,command:"publish",...f?.publish,args:f?.publish?.args||[]}:void 0,deprecate:f?.deprecate?{access:n,packageManager:i,command:"deprecate",...f?.deprecate,args:f?.deprecate?.args||[]}:void 0,custom:Array.isArray(f?.custom)?f?.custom:[]},y={access:n,packageManager:i,registry:l,packageJson:s,hooks:c},u={beforeBuild:c.custom.filter(p=>p.position==="before.build"),beforePublish:c.custom.filter(p=>p.position==="before.publish"),beforeDeprecate:c.custom.filter(p=>p.position==="before.deprecate"),afterBuild:c.custom.filter(p=>p.position==="after.build"),afterPublish:c.custom.filter(p=>p.position==="after.publish"),afterDeprecate:c.custom.filter(p=>p.position==="after.deprecate")};return{access:n,packageManager:i,registry:l,packageJson:s,hooks:{...c,custom:u},runner:w,runHooks:async p=>new Promise(async(h,g)=>{try{let d=t,m;switch(p){case"publish":if(!c.publish)break;m=K(c.publish,s);break;case"deprecate":if(!c.deprecate)break;m=z(c.deprecate);break;case"custom.before.build":if(!u.beforeBuild.length)break;m=$(u.beforeBuild,y,d);break;case"custom.before.publish":if(!u.beforePublish.length)break;m=$(u.beforePublish,y,d);break;case"custom.before.deprecate":if(!u.beforeDeprecate.length)break;m=$(u.beforeDeprecate,y,d);break;case"custom.after.build":if(!u.afterBuild.length)break;m=$(u.afterBuild,y,d);break;case"custom.after.publish":if(!u.afterPublish.length)break;m=$(u.afterPublish,y,d);break;case"custom.after.deprecate":if(!u.afterDeprecate.length)break;m=$(u.afterDeprecate,y,d);break;default:throw new Error(`Unknown lifecycle hook: ${X.magenta(p)}`)}let b=await m?.then(()=>a.success(`successfully ran lifecycle hook(s): ${X.magenta(p)}`));h(b)}catch(d){throw a.error(void 0,`failed to run lifecycle hook(s) ${X.magenta(p)}:`),d}})}}var v=process.cwd(),se=v.replace(/\\/g,"/").includes("packages/build");a.initialize(v,E.version);async function ce(e){try{let r=ve("tochibuild");for(let o of ne)await o(e,r);H(e,r).action(async(o,n)=>t(o,n)),r.help(),r.version(E.version),r.parse(process.argv,{run:!1}),await r.runMatchedCommand();async function t(o,n){return new Promise(async(i,l)=>{let s;try{let f=n.config===!1,c=await J(!0),y=await oe(e,o,n,!0).catch(u=>{a.error(void 0,u?.message),l()});if(!y)return;a.log(`running build${se||c.data?.name?` for ${j.magenta(se?e:c.data.name)}`:""}...`);for(let u=0;u<y.length;u++){if(s=_(`config.tmp-${Date.now()}.json`),!s)throw new Error("Temp config path is undefined.");let p=je.relative(v,s).replace(/\\/g,"/"),h=y[u];typeof h.config=="string"&&(Oe.existsSync(h.config)||(a.error(void 0,`config file '${h.config}' does not exist`),a.info(`try running '${j.magenta(e)} ${j.blue("config")} ${j.gray("-h")}' to get help on how to generate a config file`),process.exit(1)));let g=await q(h,c.data);await g.runHooks("custom.before.build");let d={...h};if(d["--"]!=null&&delete d["--"],!f&&(d.config!=null&&delete d.config,d.tochibuildConfig!=null&&delete d.tochibuildConfig,s=Q(s,JSON.stringify(d,null,4),{overwrite:!0,fsOptions:{encoding:"utf-8"}}),!s))throw new Error("Failed to create temp config file.");a.debug("options:",`
|
|
9
|
+
${Object.entries(d).map(([m,b])=>`- ${m}: ${j.gray(JSON.stringify(b,null,4))}`).join(`
|
|
10
|
+
`)}`),await Le({config:f?!1:p,...f?d:{},skipNodeModulesBundle:h.skipNodeModulesBundle??!0,clean:u>0?!1:h.clean}).catch(m=>{a.error(void 0,m?.message),l()}),await g.runHooks("custom.after.build"),await g.runHooks("custom.before.publish"),await g.runHooks("publish"),await g.runHooks("custom.after.publish"),await g.runHooks("custom.before.deprecate"),await g.runHooks("deprecate"),await g.runHooks("custom.after.deprecate"),I(v)}i()}catch(f){a.error(f),I(v),l()}})}}catch(r){a.error(r),process.exit(1)}}ce("@tochii/build");
|
package/dist/index.d.mts
CHANGED
|
@@ -240,10 +240,10 @@ export { BuildUtils, type DefineConfigOptions, type DefineConfigOptionsCommonEnt
|
|
|
240
240
|
// ---- cli.d.ts ----
|
|
241
241
|
/// <reference types="commander" />
|
|
242
242
|
|
|
243
|
-
type
|
|
243
|
+
type CLIcac = import('cac').CAC;
|
|
244
244
|
type CLIModule = '@tochii/build' | 'tochibuild';
|
|
245
245
|
|
|
246
|
-
type CommandHandler = (cliModule: CLIModule,
|
|
246
|
+
type CommandHandler = (cliModule: CLIModule, cli: CLIcac) => MaybePromise<void>;
|
|
247
247
|
|
|
248
248
|
type BuildOptionsCliFlag = keyof BuildOptionsCliFlagMap | '--no-config' | (string & {});
|
|
249
249
|
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as r,i as t,j as o,k as e,l as f,m}from"./chunk-
|
|
1
|
+
import{h as r,i as t,j as o,k as e,l as f,m}from"./chunk-IRC4GCCU.mjs";var d=o;export{r as BuildUtils,t as build,d as default,e as defineConfig,m as defineConfigWithCommonEntries,f as defineConfigWithIndexEntries};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tochii/build",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "An extremely fast JavaScript/Typescript and CSS bundler with minimal configuration.",
|
|
5
5
|
"repository": "https://github.com/tochiResources/project/tree/main/packages/build.git",
|
|
6
6
|
"license": "MIT",
|
|
@@ -23,15 +23,18 @@
|
|
|
23
23
|
"bin": "./dist/cli.mjs",
|
|
24
24
|
"scripts": {
|
|
25
25
|
"install:tochibuild": "cd ./tochibuild && bun install",
|
|
26
|
+
"add:tochibuild": "cd ./tochibuild && bun add",
|
|
27
|
+
"remove:tochibuild": "cd ./tochibuild && bun remove",
|
|
26
28
|
"dev": "tsx cli.ts"
|
|
27
29
|
},
|
|
28
30
|
"dependencies": {
|
|
29
31
|
"@npmcli/arborist": "^9.1.1",
|
|
30
32
|
"bundle-require": "5.1.0",
|
|
33
|
+
"cac": "^6.7.14",
|
|
31
34
|
"chalk": "^5.4.1",
|
|
32
|
-
"commander": "^13.1.0",
|
|
33
35
|
"deepmerge": "^4.3.1",
|
|
34
36
|
"fast-glob": "^3.3.3",
|
|
37
|
+
"flat": "^6.0.1",
|
|
35
38
|
"joycon": "3.1.1",
|
|
36
39
|
"npm-packlist": "^10.0.0",
|
|
37
40
|
"strip-json-comments": "5.0.1",
|
package/dist/chunk-S6QAP2TG.mjs
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
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};
|