@decaf-ts/utils 1.6.0 → 1.6.23
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/README.md +1 -1
- package/dist/utils.cjs +1 -1
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.js +1 -1
- package/dist/utils.js.map +1 -1
- package/lib/cjs/assets/slogans.cjs +1 -1
- package/lib/cjs/assets/slogans.cjs.map +1 -1
- package/lib/cjs/bin/build-scripts.cjs +1 -1
- package/lib/cjs/bin/build-scripts.cjs.map +1 -1
- package/lib/cjs/bin/modules.cjs +1 -1
- package/lib/cjs/bin/modules.cjs.map +1 -1
- package/lib/cjs/bin/npm-link.cjs +1 -1
- package/lib/cjs/bin/npm-link.cjs.map +1 -1
- package/lib/cjs/bin/npm-token.cjs +1 -1
- package/lib/cjs/bin/npm-token.cjs.map +1 -1
- package/lib/cjs/bin/release-chain-dispatch.cjs +1 -1
- package/lib/cjs/bin/release-chain-dispatch.cjs.map +1 -1
- package/lib/cjs/bin/release-chain.cjs +1 -1
- package/lib/cjs/bin/release-chain.cjs.map +1 -1
- package/lib/cjs/bin/run-all.cjs +1 -1
- package/lib/cjs/bin/run-all.cjs.map +1 -1
- package/lib/cjs/bin/tag-release.cjs +1 -1
- package/lib/cjs/bin/tag-release.cjs.map +1 -1
- package/lib/cjs/cli/command.cjs +1 -1
- package/lib/cjs/cli/command.cjs.map +1 -1
- package/lib/cjs/cli/commands/build-scripts.cjs +19 -4
- package/lib/cjs/cli/commands/build-scripts.cjs.map +1 -1
- package/lib/cjs/cli/commands/help.cjs +1 -1
- package/lib/cjs/cli/commands/help.cjs.map +1 -1
- package/lib/cjs/cli/commands/index.cjs +1 -1
- package/lib/cjs/cli/commands/index.cjs.map +1 -1
- package/lib/cjs/cli/commands/modules.cjs +1 -1
- package/lib/cjs/cli/commands/modules.cjs.map +1 -1
- package/lib/cjs/cli/commands/npm-link.cjs +1 -1
- package/lib/cjs/cli/commands/npm-link.cjs.map +1 -1
- package/lib/cjs/cli/commands/npm-token.cjs +1 -1
- package/lib/cjs/cli/commands/npm-token.cjs.map +1 -1
- package/lib/cjs/cli/commands/release-chain.cjs +1 -1
- package/lib/cjs/cli/commands/release-chain.cjs.map +1 -1
- package/lib/cjs/cli/commands/run-all.cjs +1 -1
- package/lib/cjs/cli/commands/run-all.cjs.map +1 -1
- package/lib/cjs/cli/commands/tag-release-shell.cjs +1 -1
- package/lib/cjs/cli/commands/tag-release-shell.cjs.map +1 -1
- package/lib/cjs/cli/commands/tag-release.cjs +1 -1
- package/lib/cjs/cli/commands/tag-release.cjs.map +1 -1
- package/lib/cjs/cli/constants.cjs +1 -1
- package/lib/cjs/cli/constants.cjs.map +1 -1
- package/lib/cjs/cli/index.cjs +1 -1
- package/lib/cjs/cli/index.cjs.map +1 -1
- package/lib/cjs/cli/types.cjs +1 -1
- package/lib/cjs/cli/types.cjs.map +1 -1
- package/lib/cjs/index.cjs +4 -4
- package/lib/cjs/index.cjs.map +1 -1
- package/lib/cjs/input/index.cjs +1 -1
- package/lib/cjs/input/index.cjs.map +1 -1
- package/lib/cjs/input/input.cjs +1 -1
- package/lib/cjs/input/input.cjs.map +1 -1
- package/lib/cjs/input/types.cjs +1 -1
- package/lib/cjs/input/types.cjs.map +1 -1
- package/lib/cjs/output/common.cjs +1 -1
- package/lib/cjs/output/common.cjs.map +1 -1
- package/lib/cjs/output/index.cjs +1 -1
- package/lib/cjs/output/index.cjs.map +1 -1
- package/lib/cjs/release-chain/index.cjs +1 -1
- package/lib/cjs/release-chain/index.cjs.map +1 -1
- package/lib/cjs/tests/Consumer.cjs +1 -1
- package/lib/cjs/tests/Consumer.cjs.map +1 -1
- package/lib/cjs/tests/ProducerChildProcess.cjs +1 -1
- package/lib/cjs/tests/ProducerChildProcess.cjs.map +1 -1
- package/lib/cjs/tests/TestReporter.cjs +1 -1
- package/lib/cjs/tests/TestReporter.cjs.map +1 -1
- package/lib/cjs/tests/index.cjs +1 -1
- package/lib/cjs/tests/index.cjs.map +1 -1
- package/lib/cjs/tests/jestPerformanceRunner.cjs +1 -1
- package/lib/cjs/tests/jestPerformanceRunner.cjs.map +1 -1
- package/lib/cjs/tests/utils.cjs +1 -1
- package/lib/cjs/tests/utils.cjs.map +1 -1
- package/lib/cjs/utils/constants.cjs +1 -1
- package/lib/cjs/utils/constants.cjs.map +1 -1
- package/lib/cjs/utils/fs.cjs +1 -1
- package/lib/cjs/utils/fs.cjs.map +1 -1
- package/lib/cjs/utils/http.cjs +1 -1
- package/lib/cjs/utils/http.cjs.map +1 -1
- package/lib/cjs/utils/index.cjs +1 -1
- package/lib/cjs/utils/index.cjs.map +1 -1
- package/lib/cjs/utils/md.cjs +1 -1
- package/lib/cjs/utils/md.cjs.map +1 -1
- package/lib/cjs/utils/performanceRunner.cjs +1 -1
- package/lib/cjs/utils/performanceRunner.cjs.map +1 -1
- package/lib/cjs/utils/timeout.cjs +1 -1
- package/lib/cjs/utils/timeout.cjs.map +1 -1
- package/lib/cjs/utils/types.cjs +1 -1
- package/lib/cjs/utils/types.cjs.map +1 -1
- package/lib/cjs/utils/utils.cjs +1 -1
- package/lib/cjs/utils/utils.cjs.map +1 -1
- package/lib/cjs/writers/OutputWriter.cjs +1 -1
- package/lib/cjs/writers/OutputWriter.cjs.map +1 -1
- package/lib/cjs/writers/RegexpOutputWriter.cjs +1 -1
- package/lib/cjs/writers/RegexpOutputWriter.cjs.map +1 -1
- package/lib/cjs/writers/StandardOutputWriter.cjs +1 -1
- package/lib/cjs/writers/StandardOutputWriter.cjs.map +1 -1
- package/lib/cjs/writers/index.cjs +1 -1
- package/lib/cjs/writers/index.cjs.map +1 -1
- package/lib/cjs/writers/types.cjs +1 -1
- package/lib/cjs/writers/types.cjs.map +1 -1
- package/lib/esm/cli/commands/build-scripts.js +19 -4
- package/lib/esm/cli/commands/build-scripts.js.map +1 -1
- package/lib/esm/index.js +3 -3
- package/lib/types/index.d.cts +3 -3
- package/lib/types/index.d.mts +3 -3
- package/package.json +7 -4
package/dist/utils.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"prompts";import{parseArgs as t}from"util";import{Logging as o,escapeRegExp as s,LoggedClass as a,LoggedEnvironment as r,StopWatch as n,LogLevel as i}from"@decaf-ts/logging";import c from"fs";import l from"path";import{createRequire as d,builtinModules as g}from"module";import{spawn as h,execSync as u}from"child_process";import{style as f}from"styled-string-builder";import{parse as p}from"shell-quote";import m from"zlib";import y from"https";import{writeFile as S,mkdir as b}from"fs/promises";import w from"@rollup/plugin-typescript";import v from"@rollup/plugin-commonjs";import{nodeResolve as T}from"@rollup/plugin-node-resolve";import k from"@rollup/plugin-json";import*as C from"typescript";import{ModuleKind as D,ModuleResolutionKind as $}from"typescript";import{execSync as E}from"node:child_process";import x from"node:fs";import N from"node:path";class F{static{this.logger=o.for(F)}constructor(e){this.type="text",this.name=e}setType(e){return F.logger.verbose("Setting type to: "+e),this.type=e,this}setMessage(e){return F.logger.verbose("Setting message to: "+e),this.message=e,this}setInitial(e){return F.logger.verbose("Setting initial value to: "+e),this.initial=e,this}setStyle(e){return F.logger.verbose("Setting style to: "+e),this.style=e,this}setFormat(e){return F.logger.verbose("Setting format function"),this.format=e,this}setValidate(e){return F.logger.verbose("Setting validate function"),this.validate=e,this}setOnState(e){return F.logger.verbose("Setting onState callback"),this.onState=e,this}setMin(e){return F.logger.verbose("Setting min value to: "+e),this.min=e,this}setMax(e){return F.logger.verbose("Setting max value to: "+e),this.max=e,this}setFloat(e){return F.logger.verbose("Setting float to: "+e),this.float=e,this}setRound(e){return F.logger.verbose("Setting round to: "+e),this.round=e,this}setInstructions(e){return F.logger.verbose("Setting instructions to: "+e),this.instructions=e,this}setIncrement(e){return F.logger.verbose("Setting increment to: "+e),this.increment=e,this}setSeparator(e){return F.logger.verbose("Setting separator to: "+e),this.separator=e,this}setActive(e){return F.logger.verbose("Setting active style to: "+e),this.active=e,this}setInactive(e){return F.logger.verbose("Setting inactive style to: "+e),this.inactive=e,this}setChoices(e){return F.logger.verbose("Setting choices: "+JSON.stringify(e)),this.choices=e,this}setHint(e){return F.logger.verbose("Setting hint to: "+e),this.hint=e,this}setWarn(e){return F.logger.verbose("Setting warn to: "+e),this.warn=e,this}setSuggest(e){return F.logger.verbose("Setting suggest function"),this.suggest=e,this}setLimit(e){return F.logger.verbose("Setting limit to: "+e),this.limit=e,this}setMask(e){return F.logger.verbose("Setting mask to: "+e),this.mask=e,this}setStdout(e){return F.logger.verbose("Setting stdout stream"),this.stdout=e,this}setStdin(e){return this.stdin=e,this}async ask(){return(await F.ask(this))[this.name]}static async ask(t){const o=F.logger.for(this.ask);let s;Array.isArray(t)||(t=[t]);try{o.verbose("Asking questions: "+t.map(e=>e.name).join(", ")),s=await e(t),o.verbose("Received answers: "+JSON.stringify(s,null,2))}catch(e){throw Error("Error while getting input: "+e)}return s}static async askNumber(e,t,o,s,a){F.logger.for(this.askNumber).verbose(`Asking number input: undefined, question: ${t}, min: ${o}, max: ${s}, initial: ${a}`);const r=new F(e).setMessage(t).setType("number");return"number"==typeof o&&r.setMin(o),"number"==typeof s&&r.setMax(s),"number"==typeof a&&r.setInitial(a),(await this.ask(r))[e]}static async askText(e,t,o=void 0,s){F.logger.for(this.askText).verbose(`Asking text input: undefined, question: ${t}, mask: ${o}, initial: ${s}`);const a=new F(e).setMessage(t);return o&&a.setMask(o),"string"==typeof s&&a.setInitial(s),(await this.ask(a))[e]}static async askConfirmation(e,t,o){F.logger.for(this.askConfirmation).verbose(`Asking confirmation input: undefined, question: ${t}, initial: ${o}`);const s=new F(e).setMessage(t).setType("confirm");return void 0!==o&&s.setInitial(o),(await this.ask(s))[e]}static async insist(e,t,o,s=1){const a=F.logger.for(this.insist);let r;a.verbose(`Insisting on input: ${e.name}, test: ${t.toString()}, defaultConfirmation: ${o}, limit: ${s}`);let n,i=0;try{do{r=(await F.ask(e))[e.name],t(r)?(n=await F.askConfirmation(e.name+"-confirm",`Is the ${e.type} correct?`,o),n||(r=void 0)):r=void 0}while(void 0===r&&s>1&&i++<s)}catch(e){throw a.error("Error while insisting: "+e),e}return void 0===r&&a.info("no selection..."),r}static async insistForText(e,t,o,s=void 0,a,r=!1,n=-1){F.logger.for(this.insistForText).verbose(`Insisting for text input: undefined, question: ${t}, test: ${o.toString()}, mask: ${s}, initial: ${a}, defaultConfirmation: ${r}, limit: ${n}`);const i=new F(e).setMessage(t);return s&&i.setMask(s),"string"==typeof a&&i.setInitial(a),await this.insist(i,o,r,n)}static async insistForNumber(e,t,o,s,a,r,n=!1,i=-1){F.logger.for(this.insistForNumber).verbose(`Insisting for number input: undefined, question: ${t}, test: ${o.toString()}, min: ${s}, max: ${a}, initial: ${r}, defaultConfirmation: ${n}, limit: ${i}`);const c=new F(e).setMessage(t).setType("number");return"number"==typeof s&&c.setMin(s),"number"==typeof a&&c.setMax(a),"number"==typeof r&&c.setInitial(r),await this.insist(c,o,n,i)}static parseArgs(e){const o=F.logger.for(this.parseArgs),s={args:process.argv.slice(2),options:e};o.debug("Parsing arguments: "+JSON.stringify(s,null,2));try{return t(s)}catch(t){throw o.debug(`Error while parsing arguments:\n${JSON.stringify(s,null,2)}\n | options\n${JSON.stringify(e,null,2)}\n | ${t}`),Error("Error while parsing arguments: "+t)}}}const I={verbose:{type:"boolean",short:"V",default:void 0},version:{type:"boolean",short:"v",default:void 0},help:{type:"boolean",short:"h",default:!1},logLevel:{type:"string",default:"info"},logStyle:{type:"boolean",default:!0},timestamp:{type:"boolean",default:!0},banner:{type:"boolean",default:!0}},A=Object.keys(I).reduce((e,t)=>(e[t]=I[t].default,e),{}),R="utf-8",j=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z])))/g;var M;(e=>{e.PATCH="patch",e.MINOR="minor",e.MAJOR="major"})(M||(M={}));const B="-no-ci",O="postinstall";var P;(e=>{e.GIT=".token",e.NPM=".npmtoken",e.DOCKER=".dockertoken",e.CONFLUENCE=".confluence-token"})(P||(P={}));const U="Aborted";class L{constructor(e,t,...s){this.cmd=e,this.lock=t,this.logger=o.for(this.cmd)}log(e,t){t=Buffer.isBuffer(t)?t.toString(R):t;const o="stderr"===e?f(t).red.text:t;this.logger.info(o)}data(e){this.log("stdout",e+"")}error(e){this.log("stderr",e+"")}errors(e){this.log("stderr","Error executing command exited : "+e)}exit(e,t){this.log("stdout","command exited code : "+(0===e?f(e.toString()).green.text:f(null===e?"null":e.toString()).red.text)),0===e?this.resolve(t.map(e=>e.trim()).join("\n")):this.reject(Error(t.length?t.join("\n"):e.toString()))}parseCommand(e){if(Array.isArray(e))return this.cmd=e.join(" "),[e[0],e.slice(1)];const t=p(e).filter(e=>"string"==typeof e).map(String);return this.cmd=t.join(" "),[t[0],t.slice(1)]}resolve(e){this.log("stdout",`${this.cmd} executed successfully: ${f(e?"ran to completion":e).green}`),this.lock.resolve(e)}reject(e){e instanceof Error||(e=Error("number"==typeof e?"Exit code "+e:e)),this.log("stderr",`${this.cmd} failed to execute: ${f(e.message).red}`),this.lock.reject(e)}}function _(e){let t=Promise.resolve();return(...o)=>{const s=t.then(()=>e(...o));return t=s.catch(()=>{}),s}}function V(e,...t){let o,s;if(e instanceof AbortSignal?(s=new AbortController,o=[e,...t]):(s=e,o=t),s.signal.aborted)return s;const a=()=>s.abort();for(const e of o){if(e.aborted){s.abort();break}e.addEventListener("abort",a,{once:!0,signal:s.signal})}return s}function H(e,t,o,s,a){function r(t,s){const[r,n]=e.parseCommand(t);a.info("Running command: "+r),a.debug("with args: "+n.join(" "));const i=h(r,n,{...o,cwd:o.cwd||process.cwd(),env:Object.assign({},process.env,o.env,{PATH:process.env.PATH}),shell:o.shell||!1,signal:s.signal});return a.verbose("pid : "+i.pid),i}const n=t.match(/[<>$#]/g);if(n)throw Error(`Invalid command: ${t}. contains invalid characters: ${n}`);if(t.includes(" | ")){const e=t.split(" | "),o=[],a=Array(e.length);a[0]=s;for(let t=0;t<e.length;t++)0!==t&&(a[t]=V(a[t-1].signal)),o.push(r(e[t],a[t])),0!==t&&o[t-1].stdout.pipe(o[t].stdin);return o[e.length-1]}return r(t,s)}function J(e,t={},s=L,...a){const r=o.for(J),n=new AbortController,i={abort:n,command:e,logs:[],errs:[]},c=new Promise((o,c)=>{let l;try{l=new s(e,{resolve:o,reject:c},...a),i.cmd=H(l,e,t,n,r)}catch(t){return c(Error(`Error running command ${e}: ${t}`))}i.cmd.stdout.setEncoding("utf8"),i.cmd.stdout.on("data",e=>{e=e.toString(),i.logs.push(e),l.data(e)}),i.cmd.stderr.on("data",e=>{e=e.toString(),i.errs.push(e),l.error(e)}),i.cmd.once("error",e=>{l.exit(e.message,i.errs)}),i.cmd.once("exit",(e=0)=>{n.signal.aborted&&null===e&&(e=U),l.exit(e,0===e?i.logs:i.errs)})});return Object.assign(i,{promise:c,pipe:async t=>{const o=r.for("pipe");try{o.verbose(`Executing pipe function ${e}...`);const s=await c;return o.verbose(`Piping output to ${t.name}: ${s}`),t(s)}catch(e){throw o.error("Error piping command output: "+e),e}}}),i}const W=o.for("fs"),G=d(process.cwd()+"/package.json");function K(e,t,o){const a=W.for(K);if(!c.existsSync(e))throw Error(`File not found at path "${e}".`);let r=q(e);a.verbose(`Patching file "${e}"...`),a.debug("with value: "+JSON.stringify(t));try{r=((e,t,o="g",a)=>(Object.entries(t).forEach(([t,r])=>{const n=RegExp(s(t),o);e=e.replace(n,e=>(!a||a(e),r))}),e))(r,t,"g",o)}catch(e){throw Error("Error patching file: "+e)}z(e,r)}function q(e){const t=W.for(q);try{return t.verbose(`Reading file "${e}"...`),c.readFileSync(e,"utf8")}catch(o){throw t.verbose(`Error reading file "${e}": ${o}`),Error(`Error reading file "${e}": ${o}`)}}function z(e,t){const o=W.for(z);try{o.verbose(`Writing file "${e} with ${t.length} bytes...`),c.writeFileSync(e,t,"utf8")}catch(t){throw o.verbose(`Error writing file "${e}": ${t}`),Error(`Error writing file "${e}": ${t}`)}}function X(e,t){const o=W.for(X),s=[];try{return o.verbose(`Retrieving all files from "${e}"...`),c.readdirSync(e).forEach(t=>{const o=l.join(e,t),a=c.statSync(o);a.isFile()?s.push(o):a.isDirectory()&&s.push(...X(o))}),t?s.filter(t):s}catch(t){throw o.verbose(`Error retrieving files from "${e}": ${t}`),Error(`Error retrieving files from "${e}": ${t}`)}}async function Y(e,t){const o=W.for(Y);let s,a;try{s=c.statSync(e)}catch(t){throw o.verbose(`Source path "${e}" does not exist: ${t}`),Error(`Source path "${e}" does not exist: ${t}`)}try{a=c.statSync(t)}catch(e){}if(a)throw o.verbose(`Destination path "${t}" already exists`),Error(`Destination path "${t}" already exists`);try{o.verbose(`Renaming ${s.isFile()?"file":"directory"} "${e}" to "${t}...`),c.renameSync(e,t),o.verbose(`Successfully renamed to "${t}"`)}catch(a){throw o.verbose(`Error renaming ${s.isFile()?"file":"directory"} "${e}" to "${t}": ${a}`),Error(`Error renaming ${s.isFile()?"file":"directory"} "${e}" to "${t}": ${a}`)}}function Z(e,t){const o=W.for(Z);let s,a;try{s=c.statSync(e)}catch(t){throw o.verbose(`Source path "${e}" does not exist: ${t}`),Error(`Source path "${e}" does not exist: ${t}`)}try{a=c.statSync(t)}catch(e){s.isDirectory()&&(o.verbose(`Dest path "${t}" does not exist. creating`),c.mkdirSync(t,{recursive:!0}))}try{o.verbose(`Copying ${s.isFile()?"file":"directory"} "${e}" to "${t}...`),c.cpSync(e,t,{recursive:!0})}catch(a){throw o.verbose(`Error copying ${s.isFile()?"file":"directory"} "${e}" to "${t}: ${a}`),Error(`Error copying ${s.isFile()?"file":"directory"} "${e}" to "${t}: ${a}`)}}function Q(e){const t=W.for(Q);try{const o=c.statSync(e);o.isFile()?(t.verbose(`Deleting file "${e}...`),c.rmSync(e,{recursive:!0,force:!0})):o.isDirectory()&&c.rmSync(e,{recursive:!0,force:!0})}catch(o){throw t.verbose(`Error Deleting "${e}": ${o}`),Error(`Error Deleting "${e}": ${o}`)}}function ee(e=process.cwd(),t){let o;try{o=JSON.parse(q(l.join(e,"package.json")))}catch(e){throw Error('Failed to retrieve package information" '+e)}if(t){if(!(t in o))throw Error(`Property "${t}" not found in package.json`);return o[t]}return o}function te(e,t,o=process.cwd()){const s=ee(o);s[e]=t,z(l.join(o,"package.json"),JSON.stringify(s,null,2))}function oe(e=process.cwd()){return ee(e,"version")}async function se(e=process.cwd()){const t=l.join(e,"package.json"),o=l.join(e,"package-lock.json");let s,a;try{s=JSON.parse(q(t))}catch(e){throw Error(`Could not read package.json at ${t}: ${e}`)}if(c.existsSync(o))try{a=JSON.parse(q(o))}catch(e){W.warn(`Unable to parse package-lock.json at ${o}: ${e}`)}const r=(e={})=>Object.entries(e).map(([e,t])=>({name:e,version:ae(a,e,t)}));return{prod:r(s.dependencies),dev:r(s.devDependencies),peer:r(s.peerDependencies)}}function ae(e,t,o){if(e){const s=e.packages||{},a="node_modules/"+t;if(s[a]&&s[a].version)return s[a].version;if(e.dependencies&&e.dependencies[t])return e.dependencies[t].version||o}return o}async function re(){const e=W.for(re);e.info("checking for updates..."),await J("npx npm-check-updates -u").promise,e.info("updating..."),await J("npx npm run do-install").promise}async function ne(e,t){e="string"==typeof e?[e]:e;const o={prod:t?.prod?[...t.prod]:[],dev:t?.dev?[...t.dev]:[],peer:t?.peer?[...t.peer]:[]},s=new Set([...o.prod??[],...o.dev??[],...o.peer??[]]),a=[];for(const t of e)if(!s.has(t))try{G.resolve(t),s.add(t)}catch{a.push(t)}if(a.length){"test"===process.env.NODE_ENV||void 0!==process.env.JEST_WORKER_ID?W.verbose("Skipping dependency install in test environment for: "+a.join(", ")):await ce({dev:a});const e=new Set(o.dev??[]);a.forEach(t=>e.add(t)),o.dev=Array.from(e)}return o}async function ie(){const e=W.for(ie),t=await J("git config user.name").promise,o=await J("git config user.email").promise;e.verbose(`cached git id: ${t}/${o}. changing to automation`),await J('git config user.email "automation@decaf.ts"').promise,await J('git config user.name "decaf"').promise,e.info("Pushing changes to git..."),await J("git add .").promise,await J('git commit -m "refs #1 - after repo setup"').promise,await J("git push").promise,await J(`git config user.email "${o}"`).promise,await J(`git config user.name "${t}"`).promise,e.verbose(`reverted to git id: ${t}/${o}`)}async function ce(e){const t=W.for(ce),o=e.prod||[],s=e.dev||[],a=e.peer||[];o.length&&(t.info(`Installing dependencies ${o.join(", ")}...`),await J("npm install "+o.join(" "),{cwd:process.cwd()}).promise),s.length&&(t.info(`Installing devDependencies ${s.join(", ")}...`),await J("npm install --save-dev "+s.join(" "),{cwd:process.cwd()}).promise),a.length&&(t.info(`Installing peerDependencies ${a.join(", ")}...`),await J("npm install --save-peer "+a.join(" "),{cwd:process.cwd()}).promise)}async function le(e){return e.then(e=>e.default||e)}async function de(e){const t=W.for(de);try{const o=c.readdirSync(e).map(t=>l.join(e,t)).filter(e=>{try{return c.statSync(e).isFile()&&(e.endsWith(".js")||e.endsWith(".cjs")||e.endsWith(".mjs"))}catch{return!1}});if(0===o.length)throw Error("No JS files found in directory "+e);let s=o[0],a=c.statSync(s).size;for(const e of o.slice(1)){const t=c.statSync(e).size;a>t&&(s=e,a=t)}t.verbose(`Selected smallest bundle: ${s} (${a} bytes)`);const r=c.readFileSync(s),n=m.gzipSync(r),i=Number((n.length/1024).toFixed(1));return t.verbose(`Gzipped size: ${n.length} bytes (${i} KB)`),i}catch(o){throw t.verbose(`Failed to compute gzipped size for ${e}: ${o}`),o}}function ge(e=process.cwd(),t){const o=W.for(ge);try{return c.existsSync(e)?c.readdirSync(e,{withFileTypes:!0}).filter(e=>!t||t(e.name,e)).map(e=>e.name):[]}catch(t){return o.verbose(`Failed to list folder ${e}: ${t}`),[]}}function he(e=l.join(process.cwd(),"node_modules")){const t=W.for(he);try{if(!c.existsSync(e))return[];const o=c.readdirSync(e,{withFileTypes:!0}),s=[];for(const a of o)try{if(!a.isDirectory())continue;if(a.name.startsWith("."))continue;if(a.name.startsWith("@")){const o=l.join(e,a.name);try{const e=c.readdirSync(o,{withFileTypes:!0});for(const t of e)t.isDirectory()&&!t.name.startsWith(".")&&s.push(`${a.name}/${t.name}`)}catch(e){t.verbose(`Failed to read scope ${o}: ${e}`)}}else s.push(a.name)}catch(e){t.verbose(`Skipping entry ${a.name} due to error: ${e}`)}return s}catch(o){return t.verbose(`Failed to list node_modules packages at ${e}: ${o}`),[]}}const ue=[{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That's Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"Decaf-TS: Where smart contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No CRUD, no problem \u2014 Decaf your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS: Your frontend already understands your smart contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye CRUD, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From smart contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No CRUD. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"},{Slogan:"Decaf-TS-TS: Where blockchain contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No boilerplate, no problem \u2014 Decaf-TS your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS-TS: Your frontend already understands your blockchain contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye boilerplate, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From blockchain contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No boilerplate. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf-TS.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"},{Slogan:"Decaf-TS-TS: Where blockchain contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No boilerplate, no problem \u2014 Decaf-TS your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS-TS: Your frontend already understands your blockchain contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye boilerplate, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From blockchain contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No boilerplate. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf-TS.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"},{Slogan:"Decaf-TS-TS: Where blockchain contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No boilerplate, no problem \u2014 Decaf-TS your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS-TS: Your frontend already understands your blockchain contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye boilerplate, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From blockchain contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No boilerplate. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf-TS.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"},{Slogan:"Decaf-TS-TS: Where blockchain contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No boilerplate, no problem \u2014 Decaf-TS your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS-TS: Your frontend already understands your blockchain contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye boilerplate, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From blockchain contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No boilerplate. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf-TS.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"}],fe=["\x1b[38;5;215m","\x1b[38;5;209m","\x1b[38;5;205m","\x1b[38;5;210m","\x1b[38;5;217m","\x1b[38;5;216m","\x1b[38;5;224m","\x1b[38;5;230m","\x1b[38;5;230m"];function pe(e){const t=me(),o="# \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \n# ( ( \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \n# ) ) \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \n# [=======] \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \n# `-----\xb4 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \n# \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \n# \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \n#".split("\n"),s=o.reduce((e,t)=>Math.max(e,t.length),0);o.push("# "+t.padStart(s-3)),o.forEach((t,o)=>{(e?e.info.bind(e):(()=>{}).bind())(f(t||"").raw(fe[o]).text)})}function me(e){try{return e=void 0===e?Math.floor(Math.random()*ue.length):e,ue[e].Slogan}catch(e){throw Error("Failed to retrieve slogans: "+e)}}class ye extends a{constructor(e,t={},s=[]){super(),this.name=e,this.inputs=t,this.requirements=s,ye.log||Object.defineProperty(ye,"log",{writable:!1,value:o.for(ye.name)}),this.inputs=Object.assign({},I,t)}async checkRequirements(){const{prod:e,dev:t,peer:o}=await se(),s=[],a=Array.from(new Set([...e,...t,...o]).values()).map(e=>e.name);for(const e of this.requirements)a.includes(e)||s.push(e);s.length}help(e){return this.log.info("This is help. I'm no use because I should have been overridden.")}async execute(){const e=F.parseArgs(this.inputs),t=r.accumulate(A).accumulate(e.values),{version:o,help:s,banner:a}=t;if(o)return oe();if(s)return this.help(e);let n;a&&pe(this.log.for(pe,{timestamp:!1,style:!1,context:!1,logLevel:!1}));try{n=await this.run(t)}catch(e){throw e}return n}}class Se{static{this.log=o.for(Se)}static async downloadFile(e){return new Promise((t,o)=>{!function e(s){s=encodeURI(s),y.get(s,a=>{if(301===a.statusCode||307===a.statusCode)return e(a.headers.location);if(200!==a.statusCode)return Se.log.error(`Failed to fetch ${s} (status: ${a.statusCode})`),o(Error("Failed to fetch "+s));let r="";a.on("data",e=>{r+=e}),a.on("error",e=>{o(e)}),a.on("end",()=>{t(r)})})}(e)})}}const be={width:1200,height:260,padding:32,backgroundColor:"#0f172a",headerFont:"bold 18px 'Segoe UI', sans-serif",rowFont:"14px 'Segoe UI', sans-serif",headerColor:"#f8fafc",rowColor:"#cbd5f5"},we=e=>new Promise(t=>setTimeout(t,e)),ve=(process.env.PERF_VERBOSE,(...e)=>{});class Te{constructor(e){this.scenario=e}async run(){this.scenario.initialize&&await this.scenario.initialize();let e=0;const t=this.scenario.phases.map(t=>({phase:t,phaseNumber:++e})),o=[];for(;t.length;){const s=t.shift(),a=s.phase,r=this.mergeContext(a),n=await this.runPhase(a,r);if(o.push(n),a.generator){const r=[...o],i={phaseNumber:s.phaseNumber,phaseName:a.name,iterationCount:a.config.iterations,burstSegments:n.segmentCount,segmentCount:n.segmentCount,mode:a.config.mode,history:r},c=await a.generator({result:n,history:r,metadata:i});if(c){const o="config"in c?{name:c.name??a.name+" \u2192 gen",config:c.config,generator:a.generator}:{name:a.name+" \u2192 gen",config:c,generator:a.generator};t.push({phase:o,phaseNumber:++e})}}}if(await this.logSummary(o),!1!==this.scenario.failOnError){const e=o.reduce((e,t)=>e+t.aggregated.failureCount,0);if(e>0)throw Error(`Scenario "${this.scenario.name}" recorded ${e} failures across ${o.length} phases`)}return o}async runPhase(e,t){await this.runWarmup(e,t);const o=this.buildSegmentIndices(e.config.iterations,e.config.burst),s=[],a=Date.now();for(let a=0;a<o.length;a+=1){const r=o[a];if(!r.length)continue;ve((e.name,o.length,r[0],r[r.length-1]));const n=await this.executeSegment(this.scenario.handler,e.config,t,r);s.push(...n);const i=e.config.burst?.intervalMs;i&&a<o.length-1&&await we(i)}const r=Date.now()-a,n=[...s].sort((e,t)=>e.iteration-t.iteration),i=this.aggregateMetrics(n);return e.config.pauseAfterMs&&await we(e.config.pauseAfterMs),{phase:e,config:e.config,iterationMetrics:n,aggregated:i,context:t,segmentCount:o.length,wallClockMs:r}}async runWarmup(e,t){const o=e.config.warmup;if(!o?.iterations)return;const s=o.handler??this.scenario.handler;for(let a=0;a<o.iterations;a+=1)await s({iteration:a,config:e.config,loadFactor:this.computeLoadFactor(e.config,a),context:t}),o.delayBetweenIterationsMs&&a<o.iterations-1&&await we(o.delayBetweenIterationsMs)}computeLoadFactor(e,t){return((e.loadStart??1)+(e.loadStep??0)*t)*(e.loadMultiplier??1)}buildSegmentIndices(e,t){const o=Math.max(0,e);if(0===o)return[];const s=t?.size&&t.size>0?Math.min(t.size,o):o,a=[];for(let e=0;o>e;e+=s){const t=Math.min(o,e+s);a.push(Array.from({length:t-e},(t,o)=>e+o))}return a}mergeContext(e){const t=this.scenario.baseContext??{},o=e.config.context??{};return this.mergeContexts(t,o)}mergeContexts(e,t){return Object.assign({},e,t)}async executeSegment(e,t,o,s){return s.length?"concurrent"===t.mode?this.collectConcurrent(e,t,o,s):this.collectSequential(e,t,o,s):[]}async collectSequential(e,t,o,s){const a=[],r=t.delayBetweenIterationsMs;for(let n=0;n<s.length;n+=1)a.push(await this.runIteration(e,t,o,s[n])),r&&n<s.length-1&&await we(r);return a}async collectConcurrent(e,t,o,s){const a=Math.max(1,Math.min(t.concurrency??s.length,s.length)),r=[];let n=0;const i=async()=>{for(;n<s.length;){const a=s[n];n+=1,r.push(await this.runIteration(e,t,o,a))}};return await Promise.all(Array.from({length:a},()=>i())),r}async runIteration(e,t,o,s){const a=this.computeLoadFactor(t,s),r=new n(!0);let i,c=!0;t.metadata,a.toFixed(2);try{const r=await e({iteration:s,config:t,loadFactor:a,context:o});"boolean"==typeof r?.success&&(c=r.success),i=r?.meta}catch(e){c=!1,i={error:e instanceof Error?e.message:e+""}}const l=r.stop();return l.toFixed(2),{iteration:s,durationMs:l,success:c,meta:i,loadFactor:a}}aggregateMetrics(e){if(0===e.length)return{totalDurationMs:0,minMs:0,maxMs:0,averageMs:0,successCount:0,failureCount:0,loadStart:0,loadEnd:0};const t=e.reduce((e,t)=>e+t.durationMs,0),o=Math.min(...e.map(e=>e.durationMs)),s=Math.max(...e.map(e=>e.durationMs)),a=t/e.length,r=e.filter(e=>e.success).length,n=e.length-r,i=e[0]?.loadFactor??0;return{totalDurationMs:t,minMs:o,maxMs:s,averageMs:a,successCount:r,failureCount:n,loadStart:i,loadEnd:e[e.length-1]?.loadFactor??i}}logPhaseTable(e){e.config.iterations,e.wallClockMs,e.phase.name,e.config.mode,e.config.iterations.toString(),e.wallClockMs.toFixed(0),e.aggregated.averageMs.toFixed(2),e.aggregated.minMs.toFixed(2),e.aggregated.maxMs.toFixed(2),e.aggregated.successCount.toString(),e.aggregated.failureCount.toString(),e.aggregated.loadStart.toFixed(2),e.aggregated.loadEnd.toFixed(2)}async logSummary(e){if(!e.length)return;const t=["Phase","Mode","Iterations","Wall ms","RPS","Avg ms","Min ms","Max ms","Success","Failures","Load range"],o=e.map(e=>{const t=(e.config.iterations/(e.wallClockMs/1e3)).toFixed(1);return[e.phase.name,e.config.mode,e.config.iterations.toString(),e.wallClockMs.toFixed(0),t,e.aggregated.averageMs.toFixed(2),e.aggregated.minMs.toFixed(2),e.aggregated.maxMs.toFixed(2),e.aggregated.successCount.toString(),e.aggregated.failureCount.toString(),`${e.aggregated.loadStart.toFixed(2)} \u2192 ${e.aggregated.loadEnd.toFixed(2)}`]});if(this.shouldRenderCanvas()){const e=this.scenario.canvasOutputPath??l.join(process.cwd(),"workdocs","reports","performance-runner.png");await(async(e,t,o,s)=>{const a={...be,...o};let r;try{r=(await import("canvas")).createCanvas}catch(e){return}const n=r(a.width,a.height),i=n.getContext("2d");i.fillStyle=a.backgroundColor,i.fillRect(0,0,a.width,a.height),i.font=a.headerFont,i.fillStyle=a.headerColor;const c=(a.width-2*a.padding)/e.length,d=a.padding+24;e.forEach((e,t)=>{i.fillText(e,a.padding+c*t,d)}),i.font=a.rowFont,i.fillStyle=a.rowColor,t.forEach((e,t)=>{const o=d+12+24*(t+1);e.forEach((e,t)=>{i.fillText(e,a.padding+c*t,o)})}),await(async e=>{await b(l.dirname(e),{recursive:!0})})(s),await S(s,n.toBuffer("image/png"))})(t,o,this.scenario.canvasOptions??be,e)}}shouldRenderCanvas(){return this.scenario.enableCanvas??!!this.scenario.canvasOptions}}function ke(e){return e?Array.isArray(e)?e.map(e=>(""+e).trim()).filter(Boolean):(""+e).split(",").map(e=>e.trim()).filter(Boolean):[]}function Ce(e){return e.replace(/^@/,"").split(/[/\-_.]+/).filter(Boolean).map((e,t)=>0===t?e.replace(/[^a-zA-Z0-9]/g,""):`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join("")}function De(){let e;try{e=ee(process.cwd())}catch{e=void 0}try{if(!e||!(Object.keys(e.dependencies||{}).length>0||Object.keys(e.devDependencies||{}).length>0||Object.keys(e.peerDependencies||{}).length>0)){const t=l.resolve(__dirname,"../../..");try{e=ee(t)}catch{}}}catch{}const t=Object.keys(e&&e.dependencies||{}),o=Object.keys(e&&e.peerDependencies||{}),s=Object.keys(e&&e.devDependencies||{});return Array.from(new Set([...t,...o,...s]))}const $e="##VERSION##",Ee="##COMMIT##",xe="##FULL_VERSION##",Ne="##PACKAGE##",Fe="##PACKAGE_SIZE##";var Ie,Ae,Re;(e=>{e.CJS="commonjs",e.ESM="es2022"})(Ie||(Ie={})),(e=>{e.BUILD="build",e.BUNDLE="bundle",e.ALL="all"})(Ae||(Ae={})),(e=>{e.ESM="esm",e.CJS_CHECK="cjs-check",e.TYPES="types",e.NODE_NEXT_VALIDATE="nodenext-validate",e.BUNDLE="bundle"})(Re||(Re={}));const je={prod:{type:"boolean",default:!1},dev:{type:"boolean",default:!1},buildMode:{type:"string",default:Ae.ALL},includes:{type:"string",default:""},externals:{type:"string",default:""},docs:{type:"boolean",default:!1},commands:{type:"boolean",default:!1},entry:{type:"string",default:"./src/index.ts"},banner:{type:"boolean",default:!1},validateNodeNext:{type:"boolean",default:!1}},Me=(e=".cjs")=>{const t=Be.log.for(Me),o=new Map;return s=>a=>{const r=l.dirname(a.fileName);function n(s){const a=JSON.stringify([r,s]),n=o.get(a);if(null!=n)return n;let i,d=s;try{d=l.resolve(r,d+".ts")}catch(e){throw Error(`Failed to resolve path ${s}: ${e}`)}try{i=c.statSync(d)}catch(e){try{t.verbose(`Testing existence of path ${d} as a folder defaulting to index file`),i=c.statSync(d.replace(/\.ts$/gm,""))}catch(t){throw Error(`Failed to resolve path ${s}: ${e}, ${t}`)}}if(i.isDirectory()&&(d=d.replace(/\.ts$/gm,"/index.ts")),l.isAbsolute(d)){const t=(/\.tsx?$/.exec(l.basename(d))||[])[0]||void 0;d="./"+l.relative(r,l.resolve(l.dirname(d),l.basename(d,t)+e))}return o.set(a,d),d}function i(e){return!(!e.startsWith("./")&&!e.startsWith("../"))&&""===l.extname(e)}return C.visitNode(a,function e(t){if((e=>!(!C.isImportDeclaration(e)&&!C.isExportDeclaration(e))&&void 0!==e.moduleSpecifier&&!!C.isStringLiteral(e.moduleSpecifier)&&i(e.moduleSpecifier.text))(t)){if(C.isImportDeclaration(t)){const e=n(t.moduleSpecifier.text),o=s.factory.createStringLiteral(e);return s.factory.updateImportDeclaration(t,t.modifiers,t.importClause,o,void 0)}if(C.isExportDeclaration(t)){const e=n(t.moduleSpecifier.text),o=s.factory.createStringLiteral(e);return s.factory.updateExportDeclaration(t,t.modifiers,t.isTypeOnly,t.exportClause,o,void 0)}}else if(C.isCallExpression(t)){const e=(e=>(e=>e.expression.kind===C.SyntaxKind.ImportKeyword)(e)&&e.arguments.length>0&&C.isStringLiteral(e.arguments[0])||C.isIdentifier(e.expression)&&"require"===e.expression.text&&e.arguments.length>0&&C.isStringLiteral(e.arguments[0])?e.arguments[0]:void 0)(t);if(e&&i(e.text)){const o=n(e.text),a=s.factory.createStringLiteral(o),r=t.arguments.map((e,t)=>0===t?a:e);return s.factory.updateCallExpression(t,t.expression,t.typeArguments,s.factory.createNodeArray(r))}}return C.visitEachChild(t,e,s)})}};class Be extends ye{constructor(){super("BuildScripts",Object.assign({},I,je)),this.replacements={};const e=ee(),{name:t,version:o}=e;this.pkgName=t.includes("@")?t.split("/")[1]:t,this.pkgVersion=o;try{this.commitHash=u("git rev-parse --short HEAD",{encoding:"utf8"}).trim()}catch{this.commitHash="unknown"}this.fullVersion=`${this.pkgVersion}-${this.commitHash}`,this.replacements[$e]=this.pkgVersion,this.replacements[Ee]=this.commitHash,this.replacements[xe]=this.fullVersion,this.replacements[Ne]=t}patchFiles(e){const t=this.log.for(this.patchFiles),{name:o,version:s}=ee();t.info(`Patching ${o} ${s} module in ${e}...`);const a=c.statSync(e),r=e=>{let t=e;return t=t.replace(/((?:^|[\s;,(])(?:const|let|var)\s+VERSION\s*=\s*["'])##VERSION##(["'])/gm,`$1${s}$2`),t=t.replace(/((?:^|[\s;,(])(?:const|let|var)\s+COMMIT\s*=\s*["'])##COMMIT##(["'])/gm,`$1${this.commitHash}$2`),t=t.replace(/((?:^|[\s;,(])(?:const|let|var)\s+FULL_VERSION\s*=\s*["'])##FULL_VERSION##(["'])/gm,`$1${this.fullVersion}$2`),t=t.replace(/((?:^|[\s;,(])(?:exports|module\.exports)\.VERSION\s*=\s*["'])##VERSION##(["'])/gm,`$1${s}$2`),t=t.replace(/((?:^|[\s;,(])(?:exports|module\.exports)\.COMMIT\s*=\s*["'])##COMMIT##(["'])/gm,`$1${this.commitHash}$2`),t=t.replace(/((?:^|[\s;,(])(?:exports|module\.exports)\.FULL_VERSION\s*=\s*["'])##FULL_VERSION##(["'])/gm,`$1${this.fullVersion}$2`),t=t.replace(/((?:^|[\s;,(])\w+\.VERSION\s*=\s*["'])##VERSION##(["'])/gm,`$1${s}$2`),t=t.replace(/((?:^|[\s;,(])\w+\.COMMIT\s*=\s*["'])##COMMIT##(["'])/gm,`$1${this.commitHash}$2`),t=t.replace(/((?:^|[\s;,(])\w+\.FULL_VERSION\s*=\s*["'])##FULL_VERSION##(["'])/gm,`$1${this.fullVersion}$2`),t=t.replace(/((?:^|[\s;,(])(?:const|let|var)\s+PACKAGE_NAME\s*=\s*["'])##PACKAGE##(["'])/gm,`$1${o}$2`),t=t.replace(/((?:^|[\s;,(])(?:exports|module\.exports)\.PACKAGE_NAME\s*=\s*["'])##PACKAGE##(["'])/gm,`$1${o}$2`),t=t.replace(/((?:^|[\s;,(])\w+\.PACKAGE_NAME\s*=\s*["'])##PACKAGE##(["'])/gm,`$1${o}$2`),t};a.isDirectory()&&c.readdirSync(e,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()).forEach(e=>{const t=l.join(e.parentPath,e.name),o=c.readFileSync(t,"utf8"),s=r(o);s!==o&&c.writeFileSync(t,s,"utf8"),K(t,Object.entries(this.replacements).reduce((e,[t,o])=>([$e,Ee,xe,Ne].includes(t)||(e[t]=o),e),{}))}),t.verbose(`Module ${o} ${s} patched in ${e}...`)}reportDiagnostics(e,t){const o=this.formatDiagnostics(e);try{this.log[t](o)}catch(e){throw e}return o}formatDiagnostics(e){return e.map(e=>{let t="";if(e.file&&e.start){const{line:o,character:s}=e.file.getLineAndCharacterOfPosition(e.start);t+=`${e.file.fileName} (${o+1},${s+1})`}return t+=": "+C.flattenDiagnosticMessageText(e.messageText,"\n"),t}).join("\n")}readConfigFile(e){const t=c.readFileSync(e).toString(),o=C.parseConfigFileTextToJson(e,t),s=o.config;s||this.reportDiagnostics([o.error],i.error);const a=C.parseJsonConfigFileContent(s,C.sys,l.dirname(e));return a.errors.length>0&&this.reportDiagnostics(a.errors,i.error),a}evalDiagnostics(e){if(e&&e.length>0){const t=e.filter(e=>e.category===C.DiagnosticCategory.Error),o=e.filter(e=>e.category===C.DiagnosticCategory.Warning),s=e.filter(e=>e.category===C.DiagnosticCategory.Suggestion),a=e.filter(e=>e.category===C.DiagnosticCategory.Message);if(o.length&&this.reportDiagnostics(o,i.warn),t.length)throw this.reportDiagnostics(e,i.error),Error(`TypeScript reported ${e.length} diagnostic(s) during check; aborting.`);s.length&&this.reportDiagnostics(s,i.info),a.length&&this.reportDiagnostics(a,i.info)}}preCheckDiagnostics(e){const t=C.getPreEmitDiagnostics(e);this.evalDiagnostics(t)}async checkTsDiagnostics(e,t,o=!1){const s=this.log.for(this.checkTsDiagnostics);let a;try{a=this.readConfigFile("./tsconfig.json")}catch(e){throw Error("Failed to parse tsconfig.json: "+e)}this.applyTsConfigProfile(a.options,o?Re.BUNDLE:t===Ie.ESM?Re.ESM:Re.CJS_CHECK,e);const r=C.createProgram(a.fileNames,a.options);this.preCheckDiagnostics(r),s.verbose(`TypeScript checks passed (${o?"bundle":"normal"} mode).`)}async buildTs(e,t,o=!1){let s;this.log.for(this.buildTs).info(`Building ${this.pkgName} ${this.pkgVersion} module (${t}) in ${e?"dev":"prod"} mode...`);try{s=this.readConfigFile("./tsconfig.json")}catch(e){throw Error("Failed to parse tsconfig.json: "+e)}this.applyTsConfigProfile(s.options,o?Re.BUNDLE:t===Ie.ESM?Re.ESM:Re.CJS_CHECK,e);const a=C.createProgram(s.fileNames,s.options),r={};t===Ie.ESM&&(r.before=[Me(".js")]);const n=a.emit(void 0,void 0,void 0,void 0,r),i=C.getPreEmitDiagnostics(a).concat(n.diagnostics);this.evalDiagnostics(i)}async build(e,t,o=!1){const s=this.log.for(this.build);await this.buildTs(e,t,o),s.verbose(`Module ${this.pkgName} ${this.pkgVersion} (${t}) built in ${e?"dev":"prod"} mode...`),t!==Ie.CJS||o||await this.buildCjsFromEsm(e)}rewriteRelativeJsSpecifiersToCjs(e){return e.replace(/(["'])(\.{1,2}\/[^"']+?)(\1)/g,(e,t,o,s)=>`${t}${(e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")?e.endsWith(".cjs")?e:e.endsWith(".js")?e.replace(/\.js$/,".cjs"):e:e)(o)}${s}`)}async buildCjsFromEsm(e){this.log.for(this.buildCjsFromEsm).info(`Building ${this.pkgName} ${this.pkgVersion} module (${Ie.CJS}) from ESM output in ${e?"dev":"prod"} mode...`);const t=l.resolve("lib/esm"),o=l.resolve("lib/cjs");c.mkdirSync(o,{recursive:!0});const s=X(t,e=>e.endsWith(".js")&&!e.endsWith(".d.js"));for(const a of s){const s=l.relative(t,a),r=l.join(o,s).replace(/\.js$/gm,".cjs");c.mkdirSync(l.dirname(r),{recursive:!0});const n=c.readFileSync(a,"utf8"),i=C.transpileModule(n,{compilerOptions:{module:D.CommonJS,target:C.ScriptTarget.ES2022,sourceMap:!e,inlineSourceMap:e,inlineSources:e,esModuleInterop:!0},fileName:l.basename(a),reportDiagnostics:!0});i.diagnostics?.length&&this.evalDiagnostics(i.diagnostics);const d=this.rewriteRelativeJsSpecifiersToCjs(i.outputText);c.writeFileSync(r,d,"utf8"),i.sourceMapText&&c.writeFileSync(r+".map",i.sourceMapText,"utf8")}}applyTsConfigProfile(e,t,o){switch(e.declaration=!1,e.emitDeclarationOnly=!1,e.noEmit=!1,e.outFile=void 0,e.moduleResolution=$.Bundler,t){case Re.ESM:e.module=D.ESNext,e.outDir="lib/esm";break;case Re.CJS_CHECK:e.module=D.Preserve??D.ESNext,e.moduleResolution=$.Bundler,e.noEmit=!0,e.outDir=void 0;break;case Re.TYPES:e.module=D.ESNext,e.outDir="lib/types",e.declaration=!0,e.emitDeclarationOnly=!0;break;case Re.NODE_NEXT_VALIDATE:e.module=D.NodeNext,e.moduleResolution=$.NodeNext,e.noEmit=!0;break;case Re.BUNDLE:e.module=D.ESNext,e.moduleResolution=$.Bundler,e.outDir="dist",e.isolatedModules=!1,e.outFile=void 0}if(t===Re.NODE_NEXT_VALIDATE)return e.inlineSourceMap=!1,e.inlineSources=!1,void(e.sourceMap=!1);o?(e.inlineSourceMap=!0,e.inlineSources=!0,e.sourceMap=!1):(e.inlineSourceMap=!1,e.inlineSources=!1,e.sourceMap=!0)}async checkNodeNextCompatibility(){const e=this.log.for(this.checkNodeNextCompatibility);let t;try{t=this.readConfigFile("./tsconfig.json")}catch(e){throw Error("Failed to parse tsconfig.json: "+e)}this.applyTsConfigProfile(t.options,Re.NODE_NEXT_VALIDATE,!1);const o=C.createProgram(t.fileNames,t.options);this.preCheckDiagnostics(o),e.verbose("TypeScript NodeNext compatibility check passed.")}async buildTypes(e){let t;this.log.for(this.buildTypes).info(`Building ${this.pkgName} ${this.pkgVersion} declaration files...`);try{t=this.readConfigFile("./tsconfig.json")}catch(e){throw Error("Failed to parse tsconfig.json: "+e)}this.applyTsConfigProfile(t.options,Re.TYPES,e);const o=C.createProgram(t.fileNames,t.options),s=o.emit(),a=C.getPreEmitDiagnostics(o).concat(s.diagnostics);this.evalDiagnostics(a),this.emitDualDeclarationFiles(),this.removeLegacyDeclarationFiles(),this.updatePackageJsonDualTypeExports()}rewriteRelativeDeclarationSpecifiers(e,t,o){const s=l.dirname(o),a=e=>{if(!e.startsWith("./")&&!e.startsWith("../")&&!e.startsWith("/"))return e;if(/\.(d\.(mts|cts)|mts|cts|ts|json)$/i.test(e))return e;const o=l.resolve(s,e);try{if(c.existsSync(o)&&c.statSync(o).isDirectory())return`${e}/index${t}`}catch{}return`${e}${t}`};let r=e.replace(/(\b(?:import|export)\b[\s\S]*?\bfrom\s*["'])([^"']+)(["'])/gm,(e,t,o,s)=>`${t}${a(o)}${s}`);return r=r.replace(/(\bimport\s*\(\s*["'])([^"']+)(["']\s*\))/gm,(e,t,o,s)=>`${t}${a(o)}${s}`),r=r.replace(/(\brequire\s*\(\s*["'])([^"']+)(["']\s*\))/gm,(e,t,o,s)=>`${t}${a(o)}${s}`),r}emitDualDeclarationFiles(){const e=this.log.for(this.emitDualDeclarationFiles),t=l.resolve("lib/types");if(!c.existsSync(t))return;const o=X(t,e=>e.endsWith(".d.ts"));for(const e of o){const t=c.readFileSync(e,"utf8"),o=e.replace(/\.d\.ts$/i,".d.mts"),s=e.replace(/\.d\.ts$/i,".d.cts");c.writeFileSync(o,this.rewriteRelativeDeclarationSpecifiers(t,".d.mts",e),"utf8"),c.writeFileSync(s,this.rewriteRelativeDeclarationSpecifiers(t,".d.cts",e),"utf8")}e.verbose(`Generated ${2*o.length} dual declaration files.`)}removeLegacyDeclarationFiles(){const e=this.log.for(this.removeLegacyDeclarationFiles),t=l.resolve("lib/types");if(!c.existsSync(t))return;const o=X(t,e=>e.endsWith(".d.ts")||e.endsWith(".d.ts.map"));for(const e of o)try{c.unlinkSync(e)}catch{}e.verbose(`Removed ${o.length} legacy declaration files.`)}updatePackageJsonDualTypeExports(){const e=this.log.for(this.updatePackageJsonDualTypeExports),t=l.resolve("package.json");if(!c.existsSync(t))return;const o=JSON.parse(c.readFileSync(t,"utf8")),s=o?.exports;if(!s||"object"!=typeof s)return;const a=(e,t)=>e.replace(/\.d\.(ts|mts|cts)$/i,t),r=e=>{if(e)return e.includes("/lib/esm/")?e.replace("/lib/esm/","/lib/cjs/").replace(/\.js$/i,".cjs"):e},n=(e,t=".d.mts")=>{if(e)return e.includes("/lib/esm/")?e.replace("/lib/esm/","/lib/types/").replace(/\.js$/i,t):void 0},i=e=>"string"==typeof e?e:e&&"object"==typeof e&&"string"==typeof e.default?e.default:void 0,d=e=>{if(e&&"object"==typeof e&&"string"==typeof e.types)return e.types},g={};for(const[e,t]of Object.entries(s)){if(!t||"object"!=typeof t||Array.isArray(t)){g[e]=t;continue}const o=t,s=i(o.import),c=i(o.require),l=c&&c.includes("/lib/esm/")?r(c):c||r(s),h=i(o.default),u=("string"==typeof o.types?o.types:void 0)||d(o.import),f=u&&/\.d\.(ts|mts|cts)$/i.test(u)?a(u,".d.mts"):d(o.import)||n(s,".d.mts"),p=u&&/\.d\.(ts|mts|cts)$/i.test(u)?a(u,".d.cts"):d(o.require)||n(s,".d.cts");g[e]={...s?{import:{...f?{types:f}:{},default:s}}:{},...l?{require:{...p?{types:p}:{},default:l}}:{},...h||s?{default:h||s}:{}}}o.exports=g,"string"==typeof o.types&&/\.d\.(ts|mts|cts)$/i.test(o.types)&&(o.types=o.types.replace(/\.d\.(ts|mts|cts)$/i,".d.mts")),c.writeFileSync(t,JSON.stringify(o,null,2)+"\n","utf8"),e.verbose("Updated package.json exports with import/require type conditions.")}copyAssets(e){const t=this.log.for(this.copyAssets);let o=!1;try{o=c.statSync("./src/assets").isDirectory()}catch(e){return t.verbose("No assets found in ./src/assets to copy")}o&&Z("./src/assets",`./${e===Ie.CJS?"lib":"dist"}/assets`)}async bundle(e,t,o,s="./src/index.ts",a=this.pkgName,r,n=["prompts","styled-string-builder","typed-object-accumulator","@decaf-ts/logging"]){await this.checkTsDiagnostics(t,e,!0);const i=e===Ie.ESM,c=this.pkgName,d=this.log,h=Array.from(new Set([...ke(n)]));let u=ke(r);if(0===u.length){try{u=he(l.join(process.cwd(),"node_modules"))}catch{}u&&0!==u.length||(u=De())}const f=Array.from(new Set([...(()=>{try{return Array.isArray(g)?g:[]}catch{return["fs","path","process","child_process","util","https","http","os","stream","crypto","zlib","net","tls","url","querystring","assert","events","tty","dns","querystring"]}})(),...u])),p=!t||"inline",m=[w({compilerOptions:{module:"esnext",declaration:!1,outDir:o?"bin":"dist",sourceMap:!t,inlineSourceMap:!!t,inlineSources:!!t},include:["src/**/*.ts"],exclude:["node_modules","**/*.spec.ts"],tsconfig:"./tsconfig.json"}),k()];o&&m.push(v({include:[],exclude:u}),T({resolveOnly:h}));try{const C=await import("@rollup/plugin-terser"),D=C&&C.terser||C.default||C,$={parse:{ecma:2020},compress:!1,mangle:!1,format:{comments:!1,beautify:!0}},E={parse:{ecma:2020},compress:{ecma:2020,passes:5,drop_console:!0,drop_debugger:!0,toplevel:!0,module:i,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,collapse_vars:!0,reduce_funcs:!0,reduce_vars:!0},mangle:{toplevel:!0},format:{comments:!1,ascii_only:!0},toplevel:!0};m.push(D(t?$:E))}catch{}const y={input:s,plugins:m,external:f,onwarn:void 0,treeshake:!t},S={};f.forEach(e=>{S[e]=Ce(e)});const b=[{dir:o?"bin":"dist",entryFileNames:`${a||".bundle."+(t?"":"min")}${i?".js":".cjs"}`,format:o?"cjs":i?"esm":"umd",name:c,esModule:i,sourcemap:p,globals:S,exports:"auto"}];try{const{rollup:x}=await import("rollup"),N=await x(y);async function F(e){for(const t of b)await e.write(t)}d.verbose(N.watchFiles);try{await F(N)}finally{await N.close()}}catch(I){throw Error("Failed to bundle: "+I)}}async buildByEnv(e="./src/index.ts",t,o=Ae.ALL,s=!1,a,r){s&&await this.checkNodeNextCompatibility();try{Q("lib")}catch(e){}try{Q("dist")}catch(e){}[Ae.ALL,Ae.BUILD].includes(o)&&(c.mkdirSync("lib",{recursive:!0}),await this.build(t,Ie.ESM),await this.build(t,Ie.CJS),await this.buildTypes(t),this.patchFiles("lib")),[Ae.ALL,Ae.BUNDLE].includes(o)&&(c.mkdirSync("dist"),await this.bundle(Ie.ESM,t,!1,e||"./src/index.ts",this.pkgName,r,a),await this.bundle(Ie.CJS,t,!1,e||"./src/index.ts",this.pkgName,r,a),this.patchFiles("dist")),this.copyAssets(Ie.CJS),this.copyAssets(Ie.ESM)}async buildDev(e="./src/index.ts",t=Ae.ALL,o=!1,s,a){return this.buildByEnv(e,!0,t,o,s,a)}async buildProd(e="./src/index.ts",t=Ae.ALL,o=!1,s,a){return this.buildByEnv(e,!1,t,o,s,a)}async buildDocs(){await J("npm install better-docs taffydb").promise,await J("npx markdown-include ./workdocs/readme-md.json").promise,await J("npx jsdoc -c ./workdocs/jsdocs.json -t ./node_modules/better-docs").promise,await J("npm remove better-docs taffydb").promise,[{src:"workdocs/assets",dest:"./docs/workdocs/assets"},{src:"workdocs/reports/coverage",dest:"./docs/workdocs/reports/coverage"},{src:"workdocs/reports/html",dest:"./docs/workdocs/reports/html"},{src:"workdocs/resources",dest:"./docs/workdocs/resources"},{src:"LICENSE.md",dest:"./docs/LICENSE.md"}].forEach(e=>{const{src:t,dest:o}=e;Z(t,o)});try{const e=await de(l.resolve(l.join(process.cwd(),"dist")));this.replacements[Fe]=e+" KB"}catch{this.replacements[Fe]="unknown"}try{K("./README.md",this.replacements)}catch(e){this.log.for(this.buildDocs).verbose("Failed to patch README.md: "+e)}}async run(e){const{dev:t,prod:o,docs:s,buildMode:a,includes:r,externals:n,entry:i,validateNodeNext:c}=e;return t?await this.buildDev(i||"./src/index.ts",a,!!c,r,n):o?await this.buildProd(i||"./src/index.ts",a,!!c,r,n):s?await this.buildDocs():void 0}}function Oe(e,t,o,s,a,r=[],n=[]){e.info(""+t),e.info(o),e.info("Usage: "+s),e.info("Options:");for(const t of a){const o=t.defaultValue?` (default: ${t.defaultValue})`:"";e.info(` ${t.flag} ${t.description}${o}`)}if(r.length>0){e.info("Notes:");for(const t of r)e.info(" "+t)}if(n.length>0){e.info("Examples:");for(const t of n)e.info(" "+t)}}const Pe={ci:{type:"boolean",default:!0},message:{type:"string",short:"m"},tag:{type:"string",short:"t",default:void 0}};class Ue extends ye{constructor(){super("ReleaseScript",Pe)}async prepareVersion(e){const t=this.log.for(this.prepareVersion);return(e=this.testVersion(e||""))||(t.verbose("No release version provided. Prompting for one:"),t.info("Listing latest git tags:"),await J("git tag --sort=-taggerdate | head -n 5").promise,await F.insistForText("tag","Enter the new tag number (accepts v*.*.*[-...])",e=>!!e.toString().match(/^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9a-zA-Z-]+)?$/)))}testVersion(e){const t=this.log.for(this.testVersion);switch(e=e.trim().toLowerCase()){case M.PATCH:case M.MINOR:case M.MAJOR:return t.verbose("Using provided SemVer update: "+e,1),e;default:return t.verbose("Testing provided version for SemVer compatibility: "+e,1),RegExp(j).test(e)?(t.verbose("version approved: "+e,1),e):void t.debug("Invalid version number: "+e)}}async prepareMessage(e){const t=this.log.for(this.prepareMessage);return e||(t.verbose("No release message provided. Prompting for one"),await F.insistForText("message","What should be the release message/ticket?",e=>!!e&&e.toString().length>5))}help(){Oe(this.log,"tag-release","Prepare, tag, and publish a release from the current repository.","tag-release [options]",[{flag:"--tag <version>",description:"Release tag to use"},{flag:"--message <text>",description:"Release message or ticket reference"},{flag:"--ci <true|false>",description:"Whether to treat the run as CI",defaultValue:"true"},{flag:"--version",description:"Print the package version and exit"},{flag:"-h, --help",description:"Show this help text and exit"}],["If tag or message are omitted, the command prompts interactively.","A successful run updates the package version, creates a git tag, pushes tags, and optionally publishes to npm."],['tag-release --tag v1.2.3 --message "Release 1.2.3"','tag-release --tag patch --message "Fix release"'])}async run(e){let t;const{ci:o}=e;let{tag:s,message:a}=e;s=await this.prepareVersion(s),a=await this.prepareMessage(a),t=await J(`npm run prepare-release -- ${s} ${a}`,{cwd:process.cwd()}).promise,t=await J("git status --porcelain").promise,await t,t.logs.length&&await F.askConfirmation("git-changes","Do you want to push the changes to the remote repository?",!0)&&(await J("git add .").promise,await J(`git commit -m "${s} - ${a} - after release preparation${o?"":B}"`).promise),await J(`npm version "${s}" -m "${a}${o?"":B}"`).promise,await J("git push --follow-tags").promise,o||await J("NPM_TOKEN=$(cat .npmtoken) npm publish --access public").promise}}const Le=o.for("ReleaseChainRunner");class _e{constructor(e){this.options=e,this.workspace=e.workspace??process.cwd(),this.clonesRoot=l.join(this.workspace,".release-chain"),this.token=e.token||process.env.RELEASE_CHAIN_TOKEN||process.env.GITHUB_TOKEN||process.env.GH_TOKEN,this.metaRepoSlug=We(e.metaRepoUrl)||ze("Unable to normalize META repo URL"),this.currentRepo=We(e.currentRepo)||qe()}async run(){const e=await this.loadSubmodules();if(!e.length)return void Le.warn("No modules detected in provided .gitmodules file");const t=this.currentRepo?e.findIndex(e=>e.slug===this.currentRepo):-1,o=0>t?e:e.slice(t+1);Le.info(`Evaluating ${o.length} repositories for ${this.options.packageName}`);for(const e of o)await this.evaluateModule(e)}async evaluateModule(e){if(!e.slug)return void Le.verbose(`Skipping ${e.name}: unsupported repository URL`);Le.info("\n[release-chain] "+e.slug);const t=l.join(this.clonesRoot,e.slug.replace(/\//g,"__"));c.rmSync(t,{recursive:!0,force:!0}),c.mkdirSync(t,{recursive:!0}),this.cloneRepository(e.url,t),await this.checkoutTargetBranch(t);const o=l.join(t,"package.json");if(!c.existsSync(o))return void Le.debug("No package.json detected for "+e.slug);if(s=JSON.parse(c.readFileSync(o,"utf8")),a=this.options.packageName,!["dependencies","devDependencies","peerDependencies","optionalDependencies"].some(e=>!!s?.[e]?.[a]))return void Le.debug(`${e.slug} does not depend on ${this.options.packageName}`);var s,a;if((e=>{try{E("git config user.name",{cwd:e,stdio:"pipe"}),E("git config user.email",{cwd:e,stdio:"pipe"})}catch{E("git config user.name 'release-chain'",{cwd:e}),E("git config user.email 'release-chain@users.noreply.github.com'",{cwd:e})}})(t),this.runCommand("npm install --ignore-scripts",t),this.runCommand("npm update "+this.options.packageName,t),this.runCommand("npm run build --if-present",t),this.runCommand("npm run test --if-present",t),!E("git status --porcelain",{cwd:t,encoding:"utf8"}).trim())return void Le.info("No changes detected for "+e.slug);this.runCommand("git add -A",t),this.runCommand(`git commit -m "chore: release chain update for ${this.options.packageName}"`,t),this.runCommand(`git push origin ${this.options.branch} --force-with-lease`,t);const r=await this.findExistingPr(e.slug);if(r)return Le.info(`Existing PR #${r.number} detected for ${e.slug}, attempting merge`),void await this.acceptPullRequest(e.slug,r.number,r.head.sha);const n=this.options.targetBaseBranch||await this.getDefaultBranch(e.slug);await this.createPullRequest(e.slug,n)}cloneRepository(e,t){const o=((e,t)=>{const o=Ge(e);if(!t)return o;const s=new URL(o);return s.username="x-access-token",s.password=t,s.toString()})(e,this.token);this.runCommand(`git clone --no-tags --depth 1 ${o} ${t}`)}async checkoutTargetBranch(e){try{return this.runCommand(`git fetch origin ${this.options.branch}:${this.options.branch}`,e),this.runCommand("git checkout "+this.options.branch,e),void this.runCommand("git reset --hard origin/"+this.options.branch,e)}catch(e){Le.verbose(`Branch ${this.options.branch} not found remotely; creating from default`)}const t=(e=>{try{return E("git symbolic-ref --short refs/remotes/origin/HEAD",{cwd:e,encoding:"utf8"}).trim().split("/").pop()||"main"}catch{return"main"}})(e);this.runCommand(`git checkout -b ${this.options.branch} origin/${t}`,e)}async loadSubmodules(){if(this.options.submodulePath&&c.existsSync(this.options.submodulePath))return Je(c.readFileSync(this.options.submodulePath,"utf8"));const e=[this.options.submoduleFile,".gitsubmodule",".gitmodules"].filter(Boolean);for(const t of e)try{const e=await Ke(this.metaRepoSlug,this.options.branch,t,this.token);if(e)return Je(e)}catch(o){if(t===e[e.length-1])throw o}return[]}runCommand(e,t=this.workspace){Le.debug(`[${t}] ${e}`),E(e,{cwd:t,stdio:"inherit",env:Object.assign({},process.env,{RELEASE_CHAIN_TOKEN:this.token})})}async githubRequest(e,t){const o={"User-Agent":"decaf-release-chain",Accept:"application/vnd.github+json"};this.token&&(o.Authorization="Bearer "+this.token);const s=await fetch("https://api.github.com"+e,{method:t?.method||"GET",headers:Object.assign({},o,t?.headers),body:t?.body});if(!s.ok){const e=await s.text();throw Error(`GitHub API ${s.status}: ${e}`)}if(204!==s.status)return await s.json()}async findExistingPr(e){const[t]=e.split("/"),o=await this.githubRequest(`/repos/${e}/pulls?head=${t}%3A${encodeURIComponent(this.options.branch)}&state=open&per_page=1`);return o?.[0]}async acceptPullRequest(e,t,o){await this.githubRequest(`/repos/${e}/pulls/${t}/merge`,{method:"PUT",body:JSON.stringify({merge_method:"squash",commit_title:"chore: accept release chain for "+this.options.packageName,sha:o})})}async createPullRequest(e,t){await this.githubRequest(`/repos/${e}/pulls`,{method:"POST",body:JSON.stringify({title:this.options.branch+"-release-chain",head:this.options.branch,base:t,body:`Automated dependency update for ${this.options.packageName}.`})})}async getDefaultBranch(e){const t=await this.githubRequest("/repos/"+e);return t?.default_branch||"main"}}async function Ve(e){const t=new _e(e);await t.run()}async function He(e){const t=e.token||process.env.RELEASE_CHAIN_TRIGGER_TOKEN||process.env.RELEASE_CHAIN_TOKEN||process.env.GITHUB_TOKEN||process.env.GH_TOKEN,o=e.repoSlug||qe()||ze("Unable to determine repository slug for dispatch"),s=e.workflowFile||"release-chain.yaml",a=e.ref||e.branch,r=We(e.currentRepo)||o;Le.info(`Dispatching ${s} on ${o} for ${e.branch} (current repo ${r})`);const n={"User-Agent":"decaf-release-chain-dispatch",Accept:"application/vnd.github+json","Content-Type":"application/json"};t&&(n.Authorization="Bearer "+t);const i=await fetch(`https://api.github.com/repos/${o}/actions/workflows/${s}/dispatches`,{method:"POST",headers:n,body:JSON.stringify({ref:a,inputs:{meta_repo_url:e.metaRepoUrl,branch:e.branch,current_repo:r,target_branch:e.targetBaseBranch||""}})});if(!i.ok){const e=await i.text();throw Error(`Workflow dispatch failed: ${i.status} ${e}`)}}function Je(e){return e.split("[submodule").slice(1).map(e=>{const t=e.match(/"(.+?)"\]/),o=e.match(/path\s*=\s*(.+)/),s=e.match(/url\s*=\s*(.+)/),a=s?.[1]?.trim()||"";return{name:t?.[1]?.trim()||"",path:o?.[1]?.trim()||"",url:a,slug:We(a)}}).filter(e=>e.url)}function We(e){if(e){if(e.includes("github.com")){const t=Ge(e);return new URL(t).pathname.replace(/^\//,"").replace(/\.git$/,"")}return e.replace(/^\//,"")}}function Ge(e){return e.startsWith("git@github.com:")?"https://github.com/"+e.replace("git@github.com:",""):e.startsWith("ssh://git@github.com/")?"https://github.com/"+e.replace("ssh://git@github.com/",""):e.replace(/\.git$/,"")}async function Ke(e,t,o,s){const a=`https://raw.githubusercontent.com/${e}/${t}/${o}`,r={"User-Agent":"decaf-release-chain"};s&&(r.Authorization="Bearer "+s);const n=await fetch(a,{headers:r});if(404===n.status)return null;if(!n.ok){const e=await n.text();throw Error(`Failed to download ${o}: ${n.status} ${e}`)}return n.text()}function qe(){if(process.env.GITHUB_REPOSITORY)return process.env.GITHUB_REPOSITORY;try{return We(E("git config --get remote.origin.url",{encoding:"utf8"}).trim().replace(/\s+/g,""))}catch{return}}function ze(e){throw Error(e)}const Xe={meta:{type:"string",default:process.env.RELEASE_CHAIN_META_REPO_URL||""},branch:{type:"string",default:process.env.RELEASE_CHAIN_BRANCH||process.env.GITHUB_REF_NAME||"main"},current:{type:"string",default:process.env.RELEASE_CHAIN_CURRENT||process.env.GITHUB_REPOSITORY||""},package:{type:"string",default:""},token:{type:"string",default:process.env.RELEASE_CHAIN_TOKEN||""},submoduleFile:{type:"string",default:process.env.RELEASE_CHAIN_FILE||""},submodulePath:{type:"string",default:process.env.RELEASE_CHAIN_FILE_PATH||""},workflow:{type:"string",default:process.env.RELEASE_CHAIN_WORKFLOW||"release-chain.yaml"},repo:{type:"string",default:process.env.RELEASE_CHAIN_REPO||""},ref:{type:"string",default:process.env.RELEASE_CHAIN_REF||""},targetBase:{type:"string",default:process.env.RELEASE_CHAIN_TARGET||""}};class Ye extends ye{constructor(){super("ReleaseChain",Object.assign({},I,Xe))}help(){Oe(this.log,"release-chain","Run the release-chain workflow locally across repositories.","release-chain [options]",[{flag:"--meta <url>",description:"Meta repository URL"},{flag:"--branch <name>",description:"Branch to update downstream repositories",defaultValue:"main or detected branch"},{flag:"--current <owner/repo>",description:"Current repository slug to resume after in the chain"},{flag:"--package <name>",description:"Override detected package name"},{flag:"--token <token>",description:"GitHub token for cloning and pushing"},{flag:"--submodule-file <file>",description:"Override submodule file name"},{flag:"--submodule-path <path>",description:"Use a local submodule file instead of downloading"},{flag:"--target-base <branch>",description:"Base branch for downstream pull requests"},{flag:"-h, --help",description:"Show this help text and exit"}],["Missing meta or branch values are detected from git and environment variables when possible."])}async run(e){const t=e,o=t.package||ee(process.cwd())?.name;if(!o)throw Error("Unable to determine package name");const s=t.meta||Qe();if(!s)throw Error("A meta repository URL is required");const a=t.branch||et();await Ve({metaRepoUrl:s,branch:a,currentRepo:t.current,packageName:o,token:t.token,submoduleFile:t.submoduleFile||void 0,submodulePath:t.submodulePath||void 0,targetBaseBranch:t.targetBase||void 0})}}class Ze extends ye{constructor(){super("ReleaseChainDispatch",Object.assign({},I,Xe))}help(){Oe(this.log,"release-chain-dispatch","Dispatch the release-chain GitHub Actions workflow.","release-chain-dispatch [options]",[{flag:"--meta <url>",description:"Meta repository URL"},{flag:"--branch <name>",description:"Branch to evaluate in downstream repositories",defaultValue:"main or detected branch"},{flag:"--current <owner/repo>",description:"Repository slug that triggered the release chain"},{flag:"--workflow <file>",description:"Workflow file name",defaultValue:"release-chain.yaml"},{flag:"--repo <owner/repo>",description:"Target repository slug where the workflow lives"},{flag:"--token <token>",description:"GitHub token for dispatching workflows"},{flag:"--ref <ref>",description:"Git ref to dispatch the workflow on"},{flag:"--target-base <branch>",description:"Base branch for downstream pull requests"},{flag:"-h, --help",description:"Show this help text and exit"}],["Missing meta or branch values are detected from git and environment variables when possible."])}async run(e){const t=e,o=t.meta||Qe();if(!o)throw Error("A meta repository URL is required");const s=t.branch||et();await He({metaRepoUrl:o,branch:s,workflowFile:t.workflow||"release-chain.yaml",repoSlug:t.repo,currentRepo:t.current,token:t.token,ref:t.ref||s,targetBaseBranch:t.targetBase||void 0})}}function Qe(){try{return E("git config --get remote.origin.url",{encoding:"utf8"}).trim()}catch{return}}function et(){try{return E("git rev-parse --abbrev-ref HEAD",{encoding:"utf8"}).trim()}catch{return"main"}}function tt(e=process.cwd()){const t=N.join(e,".gitmodules");return x.readFileSync(t,"utf8").toString().match(/(?<=").*?(?="])/g)||[]}function ot(e=process.cwd(),t=2){const o=new Set,s=new Set,a=(e,t,r="")=>{const n=N.resolve(e);if(s.has(n))return;s.add(n);let i=[];try{i=tt(e)}catch{return}for(const s of i){const n=r?N.join(r,s):s;if(o.add(n),0>=t)continue;const i=N.join(e,s),c=N.join(i,".gitmodules");x.existsSync(c)&&a(i,t-1,n)}};return a(e,t),Array.from(o)}const st={basePath:{type:"string",default:process.cwd()}};class at extends ye{constructor(){super("ModulesCommand",st)}help(){Oe(this.log,"modules","List modules discovered from .gitmodules.","modules [options]",[{flag:"--base-path <path>",description:"Directory to read .gitmodules from",defaultValue:"current working directory"},{flag:"-h, --help",description:"Show this help text and exit"}],["Each discovered module path is printed on its own line."],["modules","modules --base-path ../repo"])}async run(e){tt(e.basePath).forEach(e=>this.log.info(e))}}const rt={maxTraversal:{type:"string",default:"2"},excludes:{type:"string",multiple:!0,default:["@decaf-ts/utils","@decaf-ts/logging"]},include:{type:"string",multiple:!0,default:[]},packages:{type:"string",multiple:!0,default:[]},mainPackagePath:{type:"string",default:""},operation:{type:"string",default:"link"}};function nt(e){return e.split("/")[1]||e}function it(e){return[...Object.keys(e.dependencies||{}),...Object.keys(e.devDependencies||{}),...Object.keys(e.peerDependencies||{})]}function ct(e){return Array.isArray(e)?e.map(e=>(""+e).trim()).filter(Boolean):"string"==typeof e&&e.length>0?e.split(",").map(e=>e.trim()).filter(Boolean):[]}function lt(e,t){if(t.includes("*")){const o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*");return RegExp(`^${o}$`).test(e)}return e===t||N.basename(e)===t||e.endsWith("/"+t)}class dt extends ye{constructor(){super("NpmLinkCommand",rt)}help(){Oe(this.log,"npm-link","Link or unlink decaf-ts package outputs across linked modules.","npm-link [options]",[{flag:"--max-traversal <depth>",description:"How many nested .gitmodules levels to traverse",defaultValue:"2"},{flag:"--excludes <items...>",description:"Dependency names or patterns to ignore",defaultValue:"@decaf-ts/utils,@decaf-ts/logging"},{flag:"--include <items...>",description:"Module names or paths to target explicitly"},{flag:"--packages <items...>",description:"Additional non-decaf packages to link or unlink"},{flag:"--main-package-path <path>",description:"Path to the package tree that provides the original decaf packages"},{flag:"--operation <name>",description:"Operation to run in each module",defaultValue:"link"},{flag:"-h, --help",description:"Show this help text and exit"}],["link creates symlinks for decaf-ts dependencies","link can also include extra non-decaf packages passed via --packages","when --packages is set, --main-package-path is required and is used as the source root","unlink removes those links and reinstalls dependencies","any other operation is passed through to npm in each selected module"],["npm-link --operation link","npm-link --operation unlink","npm-link --operation install --include packages/app","npm-link --packages @scope/* --main-package-path ../packages --include packages/app"])}async run(e){const t=Number.parseInt(""+(e.maxTraversal||"2"),10),o=ct(e.include),s=ct(e.excludes),a=ct(e.packages),r=(""+(e.mainPackagePath||"")).trim(),n=["@decaf-ts/utils","@decaf-ts/logging"],i=(""+(e.operation||"link")).trim()||"link",c=r?N.resolve(r):process.cwd();if(a.length>0&&!r)return void process.exit(1);const l=JSON.parse(x.readFileSync(N.join(c,"package.json"),"utf8")).name.split("/")[0]||"",d=ot(process.cwd(),Number.isFinite(t)?t:2).filter(e=>0>=o.length||o.some(t=>lt(e,t))),g=e=>(s.length>0?s:n).some(t=>lt(e,t));for(const e of d){const t=N.join(process.cwd(),e);let o;try{o=JSON.parse(x.readFileSync(N.join(t,"package.json"),"utf8"))}catch{continue}const s=it(o).filter(e=>{return(t=e).startsWith(l)||a.some(e=>lt(t,e));var t});if("link"!==i)if("unlink"!==i)try{E("npm "+i,{cwd:t,env:process.env,stdio:"inherit"})}catch{process.exit(1)}else{for(const e of s)if(!g(e))try{x.rmSync(N.join(t,"node_modules",e),{force:!0,recursive:!0})}catch{process.exit(1)}try{E("npm run do-install",{cwd:t,env:process.env,stdio:"inherit"})}catch{process.exit(1)}}else for(const e of s){if(g(e))continue;const o=e.endsWith("styles")?"dist":"lib",s=nt(e);try{const a=N.join(t,"node_modules",e),r=N.join(t,"node_modules",e),n=N.join(c,s,o),i=N.join(a,o);if(!x.existsSync(n))continue;x.rmSync(r,{force:!0,recursive:!0}),x.mkdirSync(a,{recursive:!0}),x.rmSync(i,{force:!0,recursive:!0}),x.symlinkSync(N.relative(a,n),i,"dir")}catch(e){process.exit(1)}}}}}const gt={maxTraversal:{type:"string",default:"2"},tokenFiles:{type:"string",multiple:!0,default:[".token",".npmtoken"]}};class ht extends ye{constructor(){super("NpmTokenCommand",gt)}help(){Oe(this.log,"npm-token","Link token files into every module discovered in .gitmodules.","npm-token [options]",[{flag:"--max-traversal <depth>",description:"How many nested .gitmodules levels to traverse",defaultValue:"2"},{flag:"--token-files <files...>",description:"Token files to link into each selected module",defaultValue:".token,.npmtoken"},{flag:"-h, --help",description:"Show this help text and exit"}],["The command creates symlinks from each selected module back to the token files in the repository root."],["npm-token","npm-token --token-files .token .npmtoken secrets/npm.token"])}async run(e){const t=Number.parseInt(""+(e.maxTraversal||"2"),10),o=(s=e.tokenFiles,Array.isArray(s)?s.map(e=>(""+e).trim()).filter(Boolean):"string"==typeof s&&s.length>0?s.split(",").map(e=>e.trim()).filter(Boolean):[]);var s;const a=o.length>0?o:[".token",".npmtoken"],r=ot(process.cwd(),Number.isFinite(t)?t:2);for(const e of r){const t=N.join(process.cwd(),e);try{for(const e of a)x.rmSync(N.join(t,e),{force:!0,recursive:!0}),x.symlinkSync(N.join("..",e),N.join(t,e))}catch{process.exit(1)}}}}const ut={basePath:{type:"string",default:process.cwd()},command:{type:"string",default:void 0}};class ft extends ye{constructor(){super("RunAllCommand",ut)}help(){Oe(this.log,"run-all","Run a shell command in every module listed in .gitmodules.","run-all [options] --command <cmd>",[{flag:"--base-path <path>",description:"Directory to read .gitmodules from",defaultValue:"current working directory"},{flag:"--command <cmd>",description:"Shell command to execute in each module"},{flag:"-h, --help",description:"Show this help text and exit"}],["The command fails fast if any module invocation fails."],["run-all --command npm test","run-all --base-path ../repo --command npm run lint"])}async run(e){const t="string"==typeof e.basePath&&e.basePath.trim().length>0?e.basePath.trim():process.cwd(),o="string"==typeof e.command?e.command.trim():"";if(0===o.length)throw Error("run-all requires a command to execute");const s=tt(t);for(const e of s){const s=N.join(t,e);if(x.existsSync(s))try{E(o,{cwd:s,env:process.env,stdio:"inherit"})}catch{process.exit(1)}}}}const pt={public:{type:"boolean",default:!1},private:{type:"boolean",default:!1},gitToken:{type:"string",default:".token"},npmToken:{type:"string",default:".npmtoken"},gitUser:{type:"string",default:void 0},allowFromBranch:{type:"boolean",default:!1},tag:{type:"string",default:void 0},message:{type:"string",default:void 0}};class mt extends ye{constructor(){super("TagReleaseCommand",pt)}async ensureReleaseBranch(e=!1){if(e)return;const t=E("git rev-parse --abbrev-ref HEAD",{cwd:process.cwd(),encoding:"utf8"}).trim();if("master"!==t&&"main"!==t)throw Error("release must be run from 'master' or 'main' branch. Current branch: "+t)}async prepareTag(e){return(e=(""+(e||"")).trim()).length>0?e:(E("git tag --sort=-taggerdate | head -n 5",{cwd:process.cwd(),stdio:"inherit"}),F.insistForText("tag","What should be the new tag? (accepts v*.*.*[-...])",e=>!!e.toString().match(/^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9a-zA-Z-]+)?$/)))}async prepareMessage(e){return(e=(""+(e||"")).trim()).length>0?e:F.insistForText("message","Tag Message",e=>!!e&&e.toString().length>0)}hasToken(e){try{return x.statSync(N.join(process.cwd(),e)).size>0}catch{return!1}}readToken(e){return x.readFileSync(N.join(process.cwd(),e),"utf8").trim()}help(){Oe(this.log,"tag-release","Prepare a release, create a git tag, push, and optionally publish to npm.","tag-release [options] [tag] [message]",[{flag:"--public",description:"Publish to the public npm registry",defaultValue:"false"},{flag:"--private",description:"Publish to the restricted npm registry",defaultValue:"false"},{flag:"--git-token <file>",description:"File containing the token used for authenticated git pushes",defaultValue:".token"},{flag:"--npm-token <file>",description:"File containing the token used for npm publish",defaultValue:".npmtoken"},{flag:"--git-user <name>",description:"Git user name embedded in authenticated pushes"},{flag:"--allow-from-branch",description:"Skip the master/main branch guard",defaultValue:"false"},{flag:"--tag <version>",description:"Release tag to create"},{flag:"--message <text>",description:"Release message to use"},{flag:"-h, --help",description:"Show this help text and exit"}],["If tag or message are omitted, the command prompts interactively.","The command uses .token for git pushes and .npmtoken for npm publish unless overridden."],['tag-release --public --tag v1.2.3 --message "Release 1.2.3"',"tag-release --private --allow-from-branch --tag v1.2.3"])}async run(e){await this.ensureReleaseBranch(!0===e.allowFromBranch);const t=!0===e.private?"private":"public",o=await this.prepareTag(e.tag),s=await this.prepareMessage(e.message),a=""+(e.gitToken||".token"),r=""+(e.npmToken||".npmtoken"),n="string"==typeof e.gitUser&&e.gitUser.trim().length>0?e.gitUser.trim():E("git config user.name",{cwd:process.cwd(),encoding:"utf8"}).trim();E("npm run prepare-release",{cwd:process.cwd(),stdio:"inherit"}),E("git status --porcelain",{cwd:process.cwd(),encoding:"utf8"}).trim().length>0&&(E("git add .",{cwd:process.cwd(),stdio:"inherit"}),E(`git commit -m "${o} - ${s} - after release preparation"`,{cwd:process.cwd(),stdio:"inherit"})),E(`npm version "${o}" -m "${s}"`,{cwd:process.cwd(),stdio:"inherit"});const i=E("git remote get-url origin",{cwd:process.cwd(),encoding:"utf8"}).trim();if(this.hasToken(a)){const e=E("git rev-parse --abbrev-ref HEAD",{cwd:process.cwd(),encoding:"utf8"});let t="";try{t=E("git rev-parse --abbrev-ref --symbolic-full-name '@{u}'",{cwd:process.cwd(),encoding:"utf8"})}catch{t=""}const o=this.readToken(a);if(E(`git push "https://${n}:${o}@${i.replace(/^https:\/\//,"")}" --follow-tags`,{cwd:process.cwd(),stdio:"inherit"}),t.trim().length>0)try{E(`git branch --set-upstream-to="${t.trim()}" "${e.trim()}"`,{cwd:process.cwd(),stdio:"inherit"})}catch{}}else E("git push --follow-tags",{cwd:process.cwd(),stdio:"inherit"});const c="public"===t?"public":"restricted";if(s.endsWith(B)&&this.hasToken(r)){const e=this.readToken(r);E(`NPM_TOKEN="${e}" npm publish --access "${c}"`,{cwd:process.cwd(),stdio:"inherit"})}}}class yt extends L{constructor(e,t,o,s="g"){super(e,t);try{this.regexp="string"==typeof o?RegExp(o,s):o}catch(e){throw Error("Invalid regular expression: "+e)}}test(e){let t;this.regexp.lastIndex=0;try{t=this.regexp.exec(e)}catch(e){return}return t}testAndResolve(e){const t=this.test(e);t&&this.resolve(t[0])}testAndReject(e){const t=this.test(e);t&&this.reject(t[0])}data(e){super.data(e),this.testAndResolve(e+"")}error(e){super.error(e),this.testAndReject(e+"")}}const St="##VERSION##",bt="##COMMIT##",wt="##FULL_VERSION##",vt="##PACKAGE##";export{U as AbortCode,Be as BuildScripts,bt as COMMIT,ye as Command,I as DefaultCommandOptions,A as DefaultCommandValues,R as Encoding,wt as FULL_VERSION,Se as HttpClient,at as ModulesCommand,B as NoCIFLag,dt as NpmLinkCommand,ht as NpmTokenCommand,vt as PACKAGE_NAME,Te as PerformanceRunner,yt as RegexpOutputWriter,Ye as ReleaseChainCommand,Ze as ReleaseChainDispatchCommand,_e as ReleaseChainRunner,Ue as ReleaseScript,ft as RunAllCommand,M as SemVersion,j as SemVersionRegex,O as SetupScriptKey,L as StandardOutputWriter,mt as TagReleaseCommand,P as Tokens,F as UserInput,St as VERSION,V as chainAbortController,Z as copyFile,be as defaultCanvasOptions,Q as deletePath,He as dispatchReleaseChainWorkflow,X as getAllFiles,se as getDependencies,de as getFileSizeZipped,ee as getPackage,De as getPackageDependencies,oe as getPackageVersion,me as getSlogan,ce as installDependencies,ne as installIfNotAvailable,ge as listFolder,he as listNodeModulesPackages,_ as lockify,le as normalizeImport,Ce as packageToGlobal,ke as parseList,K as patchFile,pe as printBanner,ie as pushToGit,q as readFile,tt as readGitModules,ot as readGitModulesDeep,Y as renameFile,J as runCommand,Ve as runReleaseChain,te as setPackageAttribute,H as spawnCommand,re as updateDependencies,z as writeFile};
|
|
1
|
+
import e from"prompts";import{parseArgs as t}from"util";import{Logging as o,escapeRegExp as s,LoggedClass as a,LoggedEnvironment as r,StopWatch as n,LogLevel as i}from"@decaf-ts/logging";import c from"fs";import l from"path";import{createRequire as d,builtinModules as g}from"module";import{spawn as h,execSync as u}from"child_process";import{style as f}from"styled-string-builder";import{parse as p}from"shell-quote";import m from"zlib";import y from"https";import{writeFile as S,mkdir as b}from"fs/promises";import w from"@rollup/plugin-typescript";import v from"@rollup/plugin-commonjs";import{nodeResolve as T}from"@rollup/plugin-node-resolve";import k from"@rollup/plugin-json";import*as C from"typescript";import{ModuleKind as D,ModuleResolutionKind as $}from"typescript";import{execSync as E}from"node:child_process";import x from"node:fs";import N from"node:path";class F{static{this.logger=o.for(F)}constructor(e){this.type="text",this.name=e}setType(e){return F.logger.verbose("Setting type to: "+e),this.type=e,this}setMessage(e){return F.logger.verbose("Setting message to: "+e),this.message=e,this}setInitial(e){return F.logger.verbose("Setting initial value to: "+e),this.initial=e,this}setStyle(e){return F.logger.verbose("Setting style to: "+e),this.style=e,this}setFormat(e){return F.logger.verbose("Setting format function"),this.format=e,this}setValidate(e){return F.logger.verbose("Setting validate function"),this.validate=e,this}setOnState(e){return F.logger.verbose("Setting onState callback"),this.onState=e,this}setMin(e){return F.logger.verbose("Setting min value to: "+e),this.min=e,this}setMax(e){return F.logger.verbose("Setting max value to: "+e),this.max=e,this}setFloat(e){return F.logger.verbose("Setting float to: "+e),this.float=e,this}setRound(e){return F.logger.verbose("Setting round to: "+e),this.round=e,this}setInstructions(e){return F.logger.verbose("Setting instructions to: "+e),this.instructions=e,this}setIncrement(e){return F.logger.verbose("Setting increment to: "+e),this.increment=e,this}setSeparator(e){return F.logger.verbose("Setting separator to: "+e),this.separator=e,this}setActive(e){return F.logger.verbose("Setting active style to: "+e),this.active=e,this}setInactive(e){return F.logger.verbose("Setting inactive style to: "+e),this.inactive=e,this}setChoices(e){return F.logger.verbose("Setting choices: "+JSON.stringify(e)),this.choices=e,this}setHint(e){return F.logger.verbose("Setting hint to: "+e),this.hint=e,this}setWarn(e){return F.logger.verbose("Setting warn to: "+e),this.warn=e,this}setSuggest(e){return F.logger.verbose("Setting suggest function"),this.suggest=e,this}setLimit(e){return F.logger.verbose("Setting limit to: "+e),this.limit=e,this}setMask(e){return F.logger.verbose("Setting mask to: "+e),this.mask=e,this}setStdout(e){return F.logger.verbose("Setting stdout stream"),this.stdout=e,this}setStdin(e){return this.stdin=e,this}async ask(){return(await F.ask(this))[this.name]}static async ask(t){const o=F.logger.for(this.ask);let s;Array.isArray(t)||(t=[t]);try{o.verbose("Asking questions: "+t.map(e=>e.name).join(", ")),s=await e(t),o.verbose("Received answers: "+JSON.stringify(s,null,2))}catch(e){throw Error("Error while getting input: "+e)}return s}static async askNumber(e,t,o,s,a){F.logger.for(this.askNumber).verbose(`Asking number input: undefined, question: ${t}, min: ${o}, max: ${s}, initial: ${a}`);const r=new F(e).setMessage(t).setType("number");return"number"==typeof o&&r.setMin(o),"number"==typeof s&&r.setMax(s),"number"==typeof a&&r.setInitial(a),(await this.ask(r))[e]}static async askText(e,t,o=void 0,s){F.logger.for(this.askText).verbose(`Asking text input: undefined, question: ${t}, mask: ${o}, initial: ${s}`);const a=new F(e).setMessage(t);return o&&a.setMask(o),"string"==typeof s&&a.setInitial(s),(await this.ask(a))[e]}static async askConfirmation(e,t,o){F.logger.for(this.askConfirmation).verbose(`Asking confirmation input: undefined, question: ${t}, initial: ${o}`);const s=new F(e).setMessage(t).setType("confirm");return void 0!==o&&s.setInitial(o),(await this.ask(s))[e]}static async insist(e,t,o,s=1){const a=F.logger.for(this.insist);let r;a.verbose(`Insisting on input: ${e.name}, test: ${t.toString()}, defaultConfirmation: ${o}, limit: ${s}`);let n,i=0;try{do{r=(await F.ask(e))[e.name],t(r)?(n=await F.askConfirmation(e.name+"-confirm",`Is the ${e.type} correct?`,o),n||(r=void 0)):r=void 0}while(void 0===r&&s>1&&i++<s)}catch(e){throw a.error("Error while insisting: "+e),e}return void 0===r&&a.info("no selection..."),r}static async insistForText(e,t,o,s=void 0,a,r=!1,n=-1){F.logger.for(this.insistForText).verbose(`Insisting for text input: undefined, question: ${t}, test: ${o.toString()}, mask: ${s}, initial: ${a}, defaultConfirmation: ${r}, limit: ${n}`);const i=new F(e).setMessage(t);return s&&i.setMask(s),"string"==typeof a&&i.setInitial(a),await this.insist(i,o,r,n)}static async insistForNumber(e,t,o,s,a,r,n=!1,i=-1){F.logger.for(this.insistForNumber).verbose(`Insisting for number input: undefined, question: ${t}, test: ${o.toString()}, min: ${s}, max: ${a}, initial: ${r}, defaultConfirmation: ${n}, limit: ${i}`);const c=new F(e).setMessage(t).setType("number");return"number"==typeof s&&c.setMin(s),"number"==typeof a&&c.setMax(a),"number"==typeof r&&c.setInitial(r),await this.insist(c,o,n,i)}static parseArgs(e){const o=F.logger.for(this.parseArgs),s={args:process.argv.slice(2),options:e};o.debug("Parsing arguments: "+JSON.stringify(s,null,2));try{return t(s)}catch(t){throw o.debug(`Error while parsing arguments:\n${JSON.stringify(s,null,2)}\n | options\n${JSON.stringify(e,null,2)}\n | ${t}`),Error("Error while parsing arguments: "+t)}}}const I={verbose:{type:"boolean",short:"V",default:void 0},version:{type:"boolean",short:"v",default:void 0},help:{type:"boolean",short:"h",default:!1},logLevel:{type:"string",default:"info"},logStyle:{type:"boolean",default:!0},timestamp:{type:"boolean",default:!0},banner:{type:"boolean",default:!0}},A=Object.keys(I).reduce((e,t)=>(e[t]=I[t].default,e),{}),R="utf-8",j=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z])))/g;var M;(e=>{e.PATCH="patch",e.MINOR="minor",e.MAJOR="major"})(M||(M={}));const O="-no-ci",B="postinstall";var P;(e=>{e.GIT=".token",e.NPM=".npmtoken",e.DOCKER=".dockertoken",e.CONFLUENCE=".confluence-token"})(P||(P={}));const U="Aborted";class L{constructor(e,t,...s){this.cmd=e,this.lock=t,this.logger=o.for(this.cmd)}log(e,t){t=Buffer.isBuffer(t)?t.toString(R):t;const o="stderr"===e?f(t).red.text:t;this.logger.info(o)}data(e){this.log("stdout",e+"")}error(e){this.log("stderr",e+"")}errors(e){this.log("stderr","Error executing command exited : "+e)}exit(e,t){this.log("stdout","command exited code : "+(0===e?f(e.toString()).green.text:f(null===e?"null":e.toString()).red.text)),0===e?this.resolve(t.map(e=>e.trim()).join("\n")):this.reject(Error(t.length?t.join("\n"):e.toString()))}parseCommand(e){if(Array.isArray(e))return this.cmd=e.join(" "),[e[0],e.slice(1)];const t=p(e).filter(e=>"string"==typeof e).map(String);return this.cmd=t.join(" "),[t[0],t.slice(1)]}resolve(e){this.log("stdout",`${this.cmd} executed successfully: ${f(e?"ran to completion":e).green}`),this.lock.resolve(e)}reject(e){e instanceof Error||(e=Error("number"==typeof e?"Exit code "+e:e)),this.log("stderr",`${this.cmd} failed to execute: ${f(e.message).red}`),this.lock.reject(e)}}function _(e){let t=Promise.resolve();return(...o)=>{const s=t.then(()=>e(...o));return t=s.catch(()=>{}),s}}function V(e,...t){let o,s;if(e instanceof AbortSignal?(s=new AbortController,o=[e,...t]):(s=e,o=t),s.signal.aborted)return s;const a=()=>s.abort();for(const e of o){if(e.aborted){s.abort();break}e.addEventListener("abort",a,{once:!0,signal:s.signal})}return s}function H(e,t,o,s,a){function r(t,s){const[r,n]=e.parseCommand(t);a.info("Running command: "+r),a.debug("with args: "+n.join(" "));const i=h(r,n,{...o,cwd:o.cwd||process.cwd(),env:Object.assign({},process.env,o.env,{PATH:process.env.PATH}),shell:o.shell||!1,signal:s.signal});return a.verbose("pid : "+i.pid),i}const n=t.match(/[<>$#]/g);if(n)throw Error(`Invalid command: ${t}. contains invalid characters: ${n}`);if(t.includes(" | ")){const e=t.split(" | "),o=[],a=Array(e.length);a[0]=s;for(let t=0;t<e.length;t++)0!==t&&(a[t]=V(a[t-1].signal)),o.push(r(e[t],a[t])),0!==t&&o[t-1].stdout.pipe(o[t].stdin);return o[e.length-1]}return r(t,s)}function J(e,t={},s=L,...a){const r=o.for(J),n=new AbortController,i={abort:n,command:e,logs:[],errs:[]},c=new Promise((o,c)=>{let l;try{l=new s(e,{resolve:o,reject:c},...a),i.cmd=H(l,e,t,n,r)}catch(t){return c(Error(`Error running command ${e}: ${t}`))}i.cmd.stdout.setEncoding("utf8"),i.cmd.stdout.on("data",e=>{e=e.toString(),i.logs.push(e),l.data(e)}),i.cmd.stderr.on("data",e=>{e=e.toString(),i.errs.push(e),l.error(e)}),i.cmd.once("error",e=>{l.exit(e.message,i.errs)}),i.cmd.once("exit",(e=0)=>{n.signal.aborted&&null===e&&(e=U),l.exit(e,0===e?i.logs:i.errs)})});return Object.assign(i,{promise:c,pipe:async t=>{const o=r.for("pipe");try{o.verbose(`Executing pipe function ${e}...`);const s=await c;return o.verbose(`Piping output to ${t.name}: ${s}`),t(s)}catch(e){throw o.error("Error piping command output: "+e),e}}}),i}const W=o.for("fs"),G=d(process.cwd()+"/package.json");function K(e,t,o){const a=W.for(K);if(!c.existsSync(e))throw Error(`File not found at path "${e}".`);let r=q(e);a.verbose(`Patching file "${e}"...`),a.debug("with value: "+JSON.stringify(t));try{r=((e,t,o="g",a)=>(Object.entries(t).forEach(([t,r])=>{const n=RegExp(s(t),o);e=e.replace(n,e=>(!a||a(e),r))}),e))(r,t,"g",o)}catch(e){throw Error("Error patching file: "+e)}z(e,r)}function q(e){const t=W.for(q);try{return t.verbose(`Reading file "${e}"...`),c.readFileSync(e,"utf8")}catch(o){throw t.verbose(`Error reading file "${e}": ${o}`),Error(`Error reading file "${e}": ${o}`)}}function z(e,t){const o=W.for(z);try{o.verbose(`Writing file "${e} with ${t.length} bytes...`),c.writeFileSync(e,t,"utf8")}catch(t){throw o.verbose(`Error writing file "${e}": ${t}`),Error(`Error writing file "${e}": ${t}`)}}function X(e,t){const o=W.for(X),s=[];try{return o.verbose(`Retrieving all files from "${e}"...`),c.readdirSync(e).forEach(t=>{const o=l.join(e,t),a=c.statSync(o);a.isFile()?s.push(o):a.isDirectory()&&s.push(...X(o))}),t?s.filter(t):s}catch(t){throw o.verbose(`Error retrieving files from "${e}": ${t}`),Error(`Error retrieving files from "${e}": ${t}`)}}async function Y(e,t){const o=W.for(Y);let s,a;try{s=c.statSync(e)}catch(t){throw o.verbose(`Source path "${e}" does not exist: ${t}`),Error(`Source path "${e}" does not exist: ${t}`)}try{a=c.statSync(t)}catch(e){}if(a)throw o.verbose(`Destination path "${t}" already exists`),Error(`Destination path "${t}" already exists`);try{o.verbose(`Renaming ${s.isFile()?"file":"directory"} "${e}" to "${t}...`),c.renameSync(e,t),o.verbose(`Successfully renamed to "${t}"`)}catch(a){throw o.verbose(`Error renaming ${s.isFile()?"file":"directory"} "${e}" to "${t}": ${a}`),Error(`Error renaming ${s.isFile()?"file":"directory"} "${e}" to "${t}": ${a}`)}}function Z(e,t){const o=W.for(Z);let s,a;try{s=c.statSync(e)}catch(t){throw o.verbose(`Source path "${e}" does not exist: ${t}`),Error(`Source path "${e}" does not exist: ${t}`)}try{a=c.statSync(t)}catch(e){s.isDirectory()&&(o.verbose(`Dest path "${t}" does not exist. creating`),c.mkdirSync(t,{recursive:!0}))}try{o.verbose(`Copying ${s.isFile()?"file":"directory"} "${e}" to "${t}...`),c.cpSync(e,t,{recursive:!0})}catch(a){throw o.verbose(`Error copying ${s.isFile()?"file":"directory"} "${e}" to "${t}: ${a}`),Error(`Error copying ${s.isFile()?"file":"directory"} "${e}" to "${t}: ${a}`)}}function Q(e){const t=W.for(Q);try{const o=c.statSync(e);o.isFile()?(t.verbose(`Deleting file "${e}...`),c.rmSync(e,{recursive:!0,force:!0})):o.isDirectory()&&c.rmSync(e,{recursive:!0,force:!0})}catch(o){throw t.verbose(`Error Deleting "${e}": ${o}`),Error(`Error Deleting "${e}": ${o}`)}}function ee(e=process.cwd(),t){let o;try{o=JSON.parse(q(l.join(e,"package.json")))}catch(e){throw Error('Failed to retrieve package information" '+e)}if(t){if(!(t in o))throw Error(`Property "${t}" not found in package.json`);return o[t]}return o}function te(e,t,o=process.cwd()){const s=ee(o);s[e]=t,z(l.join(o,"package.json"),JSON.stringify(s,null,2))}function oe(e=process.cwd()){return ee(e,"version")}async function se(e=process.cwd()){const t=l.join(e,"package.json"),o=l.join(e,"package-lock.json");let s,a;try{s=JSON.parse(q(t))}catch(e){throw Error(`Could not read package.json at ${t}: ${e}`)}if(c.existsSync(o))try{a=JSON.parse(q(o))}catch(e){W.warn(`Unable to parse package-lock.json at ${o}: ${e}`)}const r=(e={})=>Object.entries(e).map(([e,t])=>({name:e,version:ae(a,e,t)}));return{prod:r(s.dependencies),dev:r(s.devDependencies),peer:r(s.peerDependencies)}}function ae(e,t,o){if(e){const s=e.packages||{},a="node_modules/"+t;if(s[a]&&s[a].version)return s[a].version;if(e.dependencies&&e.dependencies[t])return e.dependencies[t].version||o}return o}async function re(){const e=W.for(re);e.info("checking for updates..."),await J("npx npm-check-updates -u").promise,e.info("updating..."),await J("npx npm run do-install").promise}async function ne(e,t){e="string"==typeof e?[e]:e;const o={prod:t?.prod?[...t.prod]:[],dev:t?.dev?[...t.dev]:[],peer:t?.peer?[...t.peer]:[]},s=new Set([...o.prod??[],...o.dev??[],...o.peer??[]]),a=[];for(const t of e)if(!s.has(t))try{G.resolve(t),s.add(t)}catch{a.push(t)}if(a.length){"test"===process.env.NODE_ENV||void 0!==process.env.JEST_WORKER_ID?W.verbose("Skipping dependency install in test environment for: "+a.join(", ")):await ce({dev:a});const e=new Set(o.dev??[]);a.forEach(t=>e.add(t)),o.dev=Array.from(e)}return o}async function ie(){const e=W.for(ie),t=await J("git config user.name").promise,o=await J("git config user.email").promise;e.verbose(`cached git id: ${t}/${o}. changing to automation`),await J('git config user.email "automation@decaf.ts"').promise,await J('git config user.name "decaf"').promise,e.info("Pushing changes to git..."),await J("git add .").promise,await J('git commit -m "refs #1 - after repo setup"').promise,await J("git push").promise,await J(`git config user.email "${o}"`).promise,await J(`git config user.name "${t}"`).promise,e.verbose(`reverted to git id: ${t}/${o}`)}async function ce(e){const t=W.for(ce),o=e.prod||[],s=e.dev||[],a=e.peer||[];o.length&&(t.info(`Installing dependencies ${o.join(", ")}...`),await J("npm install "+o.join(" "),{cwd:process.cwd()}).promise),s.length&&(t.info(`Installing devDependencies ${s.join(", ")}...`),await J("npm install --save-dev "+s.join(" "),{cwd:process.cwd()}).promise),a.length&&(t.info(`Installing peerDependencies ${a.join(", ")}...`),await J("npm install --save-peer "+a.join(" "),{cwd:process.cwd()}).promise)}async function le(e){return e.then(e=>e.default||e)}async function de(e){const t=W.for(de);try{const o=c.readdirSync(e).map(t=>l.join(e,t)).filter(e=>{try{return c.statSync(e).isFile()&&(e.endsWith(".js")||e.endsWith(".cjs")||e.endsWith(".mjs"))}catch{return!1}});if(0===o.length)throw Error("No JS files found in directory "+e);let s=o[0],a=c.statSync(s).size;for(const e of o.slice(1)){const t=c.statSync(e).size;a>t&&(s=e,a=t)}t.verbose(`Selected smallest bundle: ${s} (${a} bytes)`);const r=c.readFileSync(s),n=m.gzipSync(r),i=Number((n.length/1024).toFixed(1));return t.verbose(`Gzipped size: ${n.length} bytes (${i} KB)`),i}catch(o){throw t.verbose(`Failed to compute gzipped size for ${e}: ${o}`),o}}function ge(e=process.cwd(),t){const o=W.for(ge);try{return c.existsSync(e)?c.readdirSync(e,{withFileTypes:!0}).filter(e=>!t||t(e.name,e)).map(e=>e.name):[]}catch(t){return o.verbose(`Failed to list folder ${e}: ${t}`),[]}}function he(e=l.join(process.cwd(),"node_modules")){const t=W.for(he);try{if(!c.existsSync(e))return[];const o=c.readdirSync(e,{withFileTypes:!0}),s=[];for(const a of o)try{if(!a.isDirectory())continue;if(a.name.startsWith("."))continue;if(a.name.startsWith("@")){const o=l.join(e,a.name);try{const e=c.readdirSync(o,{withFileTypes:!0});for(const t of e)t.isDirectory()&&!t.name.startsWith(".")&&s.push(`${a.name}/${t.name}`)}catch(e){t.verbose(`Failed to read scope ${o}: ${e}`)}}else s.push(a.name)}catch(e){t.verbose(`Skipping entry ${a.name} due to error: ${e}`)}return s}catch(o){return t.verbose(`Failed to list node_modules packages at ${e}: ${o}`),[]}}const ue=[{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That's Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"No caffeine, no chaos. Just clean code.",Tags:"Coffee-themed, Calm, Tech"},{Slogan:"Full flavor, no jitters. That\u2019s Decaf-TS.",Tags:"Coffee-themed, Cheerful"},{Slogan:"Chill fullstack. Powered by Decaf.",Tags:"Coffee-themed, Fun, Tech"},{Slogan:"Decaf-TS: Brewed for calm code.",Tags:"Coffee-themed, Branding"},{Slogan:"Smooth as your morning Decaf.",Tags:"Coffee-themed, Chill"},{Slogan:"All the kick, none of the crash.",Tags:"Coffee-themed, Energetic"},{Slogan:"Sip back and ship faster.",Tags:"Coffee-themed, Fun"},{Slogan:"Keep calm and code Decaf.",Tags:"Coffee-themed, Playful"},{Slogan:"Code without the caffeine shakes.",Tags:"Coffee-themed, Humorous"},{Slogan:"Your fullstack, decaffeinated.",Tags:"Coffee-themed, Technical"},{Slogan:"Decaf-TS: Where smart contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No CRUD, no problem \u2014 Decaf your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS: Your frontend already understands your smart contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye CRUD, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From smart contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No CRUD. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"},{Slogan:"Decaf-TS-TS: Where blockchain contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No boilerplate, no problem \u2014 Decaf-TS your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS-TS: Your frontend already understands your blockchain contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye boilerplate, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From blockchain contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No boilerplate. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf-TS.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"},{Slogan:"Decaf-TS-TS: Where blockchain contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No boilerplate, no problem \u2014 Decaf-TS your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS-TS: Your frontend already understands your blockchain contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye boilerplate, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From blockchain contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No boilerplate. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf-TS.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"},{Slogan:"Decaf-TS-TS: Where blockchain contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No boilerplate, no problem \u2014 Decaf-TS your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS-TS: Your frontend already understands your blockchain contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye boilerplate, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From blockchain contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No boilerplate. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf-TS.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"},{Slogan:"Decaf-TS-TS: Where blockchain contracts meet smart interfaces.",Tags:"Blockchain, Smart Contracts, Tech"},{Slogan:"Ship dApps without the stress.",Tags:"Blockchain, Cheerful, Developer"},{Slogan:"No boilerplate, no problem \u2014 Decaf-TS your data.",Tags:"Data, No-CRUD, Chill"},{Slogan:"From DID to UI, without breaking a sweat.",Tags:"DID, SSI, UI, Calm"},{Slogan:"Decaf-TS-TS: Your frontend already understands your blockchain contract.",Tags:"Smart Contracts, DX, Magic"},{Slogan:"Self-sovereign by design. Productive by default.",Tags:"SSI, Developer, Calm"},{Slogan:"Build once. Deploy everywhere. Decentralized and delightful.",Tags:"Blockchain, Multi-platform, Happy"},{Slogan:"Data that defines its own destiny.",Tags:"SSI, Data-driven, Empowerment"},{Slogan:"Goodbye boilerplate, hello intent-based interfaces.",Tags:"No-CRUD, UI, Technical"},{Slogan:"The smoothest path from DID to done.",Tags:"DID, Workflow, Chill"},{Slogan:"Because your dApp deserves more than boilerplate.",Tags:"Blockchain, DevX, Efficiency"},{Slogan:"Own your data. Own your flow.",Tags:"SSI, Control, Ownership"},{Slogan:"Write logic like it belongs with the data \u2014 because it does.",Tags:"Data Logic, Developer, Smart"},{Slogan:"From blockchain contracts to smarter frontends.",Tags:"Smart Contracts, UI, DX"},{Slogan:"No caffeine. No boilerplate. Just the future.",Tags:"No-CRUD, Coffee-themed, Futuristic"},{Slogan:"The future of web3 UX is Decaf-TS.",Tags:"Blockchain, UX, Vision"},{Slogan:"Code with confidence. Govern with clarity.",Tags:"Blockchain, Governance, Calm"},{Slogan:"Interfaces that obey the data, not the other way around.",Tags:"UI, Data Logic, Self-aware"},{Slogan:"Brew business logic right into your bytes.",Tags:"Data Logic, Coffee-themed, Fun"},{Slogan:"DIDs done differently \u2014 and delightfully.",Tags:"DID, Self-Sovereign, Playful"}],fe=["\x1b[38;5;215m","\x1b[38;5;209m","\x1b[38;5;205m","\x1b[38;5;210m","\x1b[38;5;217m","\x1b[38;5;216m","\x1b[38;5;224m","\x1b[38;5;230m","\x1b[38;5;230m"];function pe(e){const t=me(),o="# \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \n# ( ( \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \n# ) ) \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \n# [=======] \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \n# `-----\xb4 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \n# \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \n# \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591\u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2593\u2592\u2591 \u2591\u2592\u2593\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2593\u2592\u2591 \n#".split("\n"),s=o.reduce((e,t)=>Math.max(e,t.length),0);o.push("# "+t.padStart(s-3)),o.forEach((t,o)=>{(e?e.info.bind(e):(()=>{}).bind())(f(t||"").raw(fe[o]).text)})}function me(e){try{return e=void 0===e?Math.floor(Math.random()*ue.length):e,ue[e].Slogan}catch(e){throw Error("Failed to retrieve slogans: "+e)}}class ye extends a{constructor(e,t={},s=[]){super(),this.name=e,this.inputs=t,this.requirements=s,ye.log||Object.defineProperty(ye,"log",{writable:!1,value:o.for(ye.name)}),this.inputs=Object.assign({},I,t)}async checkRequirements(){const{prod:e,dev:t,peer:o}=await se(),s=[],a=Array.from(new Set([...e,...t,...o]).values()).map(e=>e.name);for(const e of this.requirements)a.includes(e)||s.push(e);s.length}help(e){return this.log.info("This is help. I'm no use because I should have been overridden.")}async execute(){const e=F.parseArgs(this.inputs),t=r.accumulate(A).accumulate(e.values),{version:o,help:s,banner:a}=t;if(o)return oe();if(s)return this.help(e);let n;a&&pe(this.log.for(pe,{timestamp:!1,style:!1,context:!1,logLevel:!1}));try{n=await this.run(t)}catch(e){throw e}return n}}class Se{static{this.log=o.for(Se)}static async downloadFile(e){return new Promise((t,o)=>{!function e(s){s=encodeURI(s),y.get(s,a=>{if(301===a.statusCode||307===a.statusCode)return e(a.headers.location);if(200!==a.statusCode)return Se.log.error(`Failed to fetch ${s} (status: ${a.statusCode})`),o(Error("Failed to fetch "+s));let r="";a.on("data",e=>{r+=e}),a.on("error",e=>{o(e)}),a.on("end",()=>{t(r)})})}(e)})}}const be={width:1200,height:260,padding:32,backgroundColor:"#0f172a",headerFont:"bold 18px 'Segoe UI', sans-serif",rowFont:"14px 'Segoe UI', sans-serif",headerColor:"#f8fafc",rowColor:"#cbd5f5"},we=e=>new Promise(t=>setTimeout(t,e)),ve=(process.env.PERF_VERBOSE,(...e)=>{});class Te{constructor(e){this.scenario=e}async run(){this.scenario.initialize&&await this.scenario.initialize();let e=0;const t=this.scenario.phases.map(t=>({phase:t,phaseNumber:++e})),o=[];for(;t.length;){const s=t.shift(),a=s.phase,r=this.mergeContext(a),n=await this.runPhase(a,r);if(o.push(n),a.generator){const r=[...o],i={phaseNumber:s.phaseNumber,phaseName:a.name,iterationCount:a.config.iterations,burstSegments:n.segmentCount,segmentCount:n.segmentCount,mode:a.config.mode,history:r},c=await a.generator({result:n,history:r,metadata:i});if(c){const o="config"in c?{name:c.name??a.name+" \u2192 gen",config:c.config,generator:a.generator}:{name:a.name+" \u2192 gen",config:c,generator:a.generator};t.push({phase:o,phaseNumber:++e})}}}if(await this.logSummary(o),!1!==this.scenario.failOnError){const e=o.reduce((e,t)=>e+t.aggregated.failureCount,0);if(e>0)throw Error(`Scenario "${this.scenario.name}" recorded ${e} failures across ${o.length} phases`)}return o}async runPhase(e,t){await this.runWarmup(e,t);const o=this.buildSegmentIndices(e.config.iterations,e.config.burst),s=[],a=Date.now();for(let a=0;a<o.length;a+=1){const r=o[a];if(!r.length)continue;ve((e.name,o.length,r[0],r[r.length-1]));const n=await this.executeSegment(this.scenario.handler,e.config,t,r);s.push(...n);const i=e.config.burst?.intervalMs;i&&a<o.length-1&&await we(i)}const r=Date.now()-a,n=[...s].sort((e,t)=>e.iteration-t.iteration),i=this.aggregateMetrics(n);return e.config.pauseAfterMs&&await we(e.config.pauseAfterMs),{phase:e,config:e.config,iterationMetrics:n,aggregated:i,context:t,segmentCount:o.length,wallClockMs:r}}async runWarmup(e,t){const o=e.config.warmup;if(!o?.iterations)return;const s=o.handler??this.scenario.handler;for(let a=0;a<o.iterations;a+=1)await s({iteration:a,config:e.config,loadFactor:this.computeLoadFactor(e.config,a),context:t}),o.delayBetweenIterationsMs&&a<o.iterations-1&&await we(o.delayBetweenIterationsMs)}computeLoadFactor(e,t){return((e.loadStart??1)+(e.loadStep??0)*t)*(e.loadMultiplier??1)}buildSegmentIndices(e,t){const o=Math.max(0,e);if(0===o)return[];const s=t?.size&&t.size>0?Math.min(t.size,o):o,a=[];for(let e=0;o>e;e+=s){const t=Math.min(o,e+s);a.push(Array.from({length:t-e},(t,o)=>e+o))}return a}mergeContext(e){const t=this.scenario.baseContext??{},o=e.config.context??{};return this.mergeContexts(t,o)}mergeContexts(e,t){return Object.assign({},e,t)}async executeSegment(e,t,o,s){return s.length?"concurrent"===t.mode?this.collectConcurrent(e,t,o,s):this.collectSequential(e,t,o,s):[]}async collectSequential(e,t,o,s){const a=[],r=t.delayBetweenIterationsMs;for(let n=0;n<s.length;n+=1)a.push(await this.runIteration(e,t,o,s[n])),r&&n<s.length-1&&await we(r);return a}async collectConcurrent(e,t,o,s){const a=Math.max(1,Math.min(t.concurrency??s.length,s.length)),r=[];let n=0;const i=async()=>{for(;n<s.length;){const a=s[n];n+=1,r.push(await this.runIteration(e,t,o,a))}};return await Promise.all(Array.from({length:a},()=>i())),r}async runIteration(e,t,o,s){const a=this.computeLoadFactor(t,s),r=new n(!0);let i,c=!0;t.metadata,a.toFixed(2);try{const r=await e({iteration:s,config:t,loadFactor:a,context:o});"boolean"==typeof r?.success&&(c=r.success),i=r?.meta}catch(e){c=!1,i={error:e instanceof Error?e.message:e+""}}const l=r.stop();return l.toFixed(2),{iteration:s,durationMs:l,success:c,meta:i,loadFactor:a}}aggregateMetrics(e){if(0===e.length)return{totalDurationMs:0,minMs:0,maxMs:0,averageMs:0,successCount:0,failureCount:0,loadStart:0,loadEnd:0};const t=e.reduce((e,t)=>e+t.durationMs,0),o=Math.min(...e.map(e=>e.durationMs)),s=Math.max(...e.map(e=>e.durationMs)),a=t/e.length,r=e.filter(e=>e.success).length,n=e.length-r,i=e[0]?.loadFactor??0;return{totalDurationMs:t,minMs:o,maxMs:s,averageMs:a,successCount:r,failureCount:n,loadStart:i,loadEnd:e[e.length-1]?.loadFactor??i}}logPhaseTable(e){e.config.iterations,e.wallClockMs,e.phase.name,e.config.mode,e.config.iterations.toString(),e.wallClockMs.toFixed(0),e.aggregated.averageMs.toFixed(2),e.aggregated.minMs.toFixed(2),e.aggregated.maxMs.toFixed(2),e.aggregated.successCount.toString(),e.aggregated.failureCount.toString(),e.aggregated.loadStart.toFixed(2),e.aggregated.loadEnd.toFixed(2)}async logSummary(e){if(!e.length)return;const t=["Phase","Mode","Iterations","Wall ms","RPS","Avg ms","Min ms","Max ms","Success","Failures","Load range"],o=e.map(e=>{const t=(e.config.iterations/(e.wallClockMs/1e3)).toFixed(1);return[e.phase.name,e.config.mode,e.config.iterations.toString(),e.wallClockMs.toFixed(0),t,e.aggregated.averageMs.toFixed(2),e.aggregated.minMs.toFixed(2),e.aggregated.maxMs.toFixed(2),e.aggregated.successCount.toString(),e.aggregated.failureCount.toString(),`${e.aggregated.loadStart.toFixed(2)} \u2192 ${e.aggregated.loadEnd.toFixed(2)}`]});if(this.shouldRenderCanvas()){const e=this.scenario.canvasOutputPath??l.join(process.cwd(),"workdocs","reports","performance-runner.png");await(async(e,t,o,s)=>{const a={...be,...o};let r;try{r=(await import("canvas")).createCanvas}catch(e){return}const n=r(a.width,a.height),i=n.getContext("2d");i.fillStyle=a.backgroundColor,i.fillRect(0,0,a.width,a.height),i.font=a.headerFont,i.fillStyle=a.headerColor;const c=(a.width-2*a.padding)/e.length,d=a.padding+24;e.forEach((e,t)=>{i.fillText(e,a.padding+c*t,d)}),i.font=a.rowFont,i.fillStyle=a.rowColor,t.forEach((e,t)=>{const o=d+12+24*(t+1);e.forEach((e,t)=>{i.fillText(e,a.padding+c*t,o)})}),await(async e=>{await b(l.dirname(e),{recursive:!0})})(s),await S(s,n.toBuffer("image/png"))})(t,o,this.scenario.canvasOptions??be,e)}}shouldRenderCanvas(){return this.scenario.enableCanvas??!!this.scenario.canvasOptions}}function ke(e){return e?Array.isArray(e)?e.map(e=>(""+e).trim()).filter(Boolean):(""+e).split(",").map(e=>e.trim()).filter(Boolean):[]}function Ce(e){return e.replace(/^@/,"").split(/[/\-_.]+/).filter(Boolean).map((e,t)=>0===t?e.replace(/[^a-zA-Z0-9]/g,""):`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join("")}function De(){let e;try{e=ee(process.cwd())}catch{e=void 0}try{if(!e||!(Object.keys(e.dependencies||{}).length>0||Object.keys(e.devDependencies||{}).length>0||Object.keys(e.peerDependencies||{}).length>0)){const t=l.resolve(__dirname,"../../..");try{e=ee(t)}catch{}}}catch{}const t=Object.keys(e&&e.dependencies||{}),o=Object.keys(e&&e.peerDependencies||{}),s=Object.keys(e&&e.devDependencies||{});return Array.from(new Set([...t,...o,...s]))}const $e="##VERSION##",Ee="##COMMIT##",xe="##FULL_VERSION##",Ne="##PACKAGE##",Fe="##PACKAGE_SIZE##";var Ie,Ae,Re;(e=>{e.CJS="commonjs",e.ESM="es2022"})(Ie||(Ie={})),(e=>{e.BUILD="build",e.BUNDLE="bundle",e.ALL="all"})(Ae||(Ae={})),(e=>{e.ESM="esm",e.CJS_CHECK="cjs-check",e.TYPES="types",e.NODE_NEXT_VALIDATE="nodenext-validate",e.BUNDLE="bundle"})(Re||(Re={}));const je={prod:{type:"boolean",default:!1},dev:{type:"boolean",default:!1},buildMode:{type:"string",default:Ae.ALL},includes:{type:"string",default:""},externals:{type:"string",default:""},docs:{type:"boolean",default:!1},commands:{type:"boolean",default:!1},entry:{type:"string",default:"./src/index.ts"},banner:{type:"boolean",default:!1},validateNodeNext:{type:"boolean",default:!1}},Me=(e=".cjs")=>{const t=Pe.log.for(Me),o=new Map;return s=>a=>{const r=l.dirname(a.fileName);function n(s){const a=JSON.stringify([r,s]),n=o.get(a);if(null!=n)return n;let i,d=s;try{d=l.resolve(r,d+".ts")}catch(e){throw Error(`Failed to resolve path ${s}: ${e}`)}try{i=c.statSync(d)}catch(e){try{t.verbose(`Testing existence of path ${d} as a folder defaulting to index file`),i=c.statSync(d.replace(/\.ts$/gm,""))}catch(t){throw Error(`Failed to resolve path ${s}: ${e}, ${t}`)}}if(i.isDirectory()&&(d=d.replace(/\.ts$/gm,"/index.ts")),l.isAbsolute(d)){const t=(/\.tsx?$/.exec(l.basename(d))||[])[0]||void 0;d="./"+l.relative(r,l.resolve(l.dirname(d),l.basename(d,t)+e))}return o.set(a,d),d}function i(e){return!(!e.startsWith("./")&&!e.startsWith("../"))&&""===l.extname(e)}return C.visitNode(a,function e(t){if((e=>!(!C.isImportDeclaration(e)&&!C.isExportDeclaration(e))&&void 0!==e.moduleSpecifier&&!!C.isStringLiteral(e.moduleSpecifier)&&i(e.moduleSpecifier.text))(t)){if(C.isImportDeclaration(t)){const e=n(t.moduleSpecifier.text),o=s.factory.createStringLiteral(e);return s.factory.updateImportDeclaration(t,t.modifiers,t.importClause,o,void 0)}if(C.isExportDeclaration(t)){const e=n(t.moduleSpecifier.text),o=s.factory.createStringLiteral(e);return s.factory.updateExportDeclaration(t,t.modifiers,t.isTypeOnly,t.exportClause,o,void 0)}}else if(C.isCallExpression(t)){const e=(e=>(e=>e.expression.kind===C.SyntaxKind.ImportKeyword)(e)&&e.arguments.length>0&&C.isStringLiteral(e.arguments[0])||C.isIdentifier(e.expression)&&"require"===e.expression.text&&e.arguments.length>0&&C.isStringLiteral(e.arguments[0])?e.arguments[0]:void 0)(t);if(e&&i(e.text)){const o=n(e.text),a=s.factory.createStringLiteral(o),r=t.arguments.map((e,t)=>0===t?a:e);return s.factory.updateCallExpression(t,t.expression,t.typeArguments,s.factory.createNodeArray(r))}}return C.visitEachChild(t,e,s)})}};function Oe(e){return e.split(l.sep).join("/")}function Be(e,t){const o=l.parse(e);return l.join(o.dir,`${o.name}${t}`)}class Pe extends ye{constructor(){super("BuildScripts",Object.assign({},I,je)),this.replacements={};const e=ee(),{name:t,version:o}=e;this.pkgName=t.includes("@")?t.split("/")[1]:t,this.pkgVersion=o;try{this.commitHash=u("git rev-parse --short HEAD",{encoding:"utf8"}).trim()}catch{this.commitHash="unknown"}this.fullVersion=`${this.pkgVersion}-${this.commitHash}`,this.replacements[$e]=this.pkgVersion,this.replacements[Ee]=this.commitHash,this.replacements[xe]=this.fullVersion,this.replacements[Ne]=t}patchFiles(e){const t=this.log.for(this.patchFiles),{name:o,version:s}=ee();t.info(`Patching ${o} ${s} module in ${e}...`);const a=c.statSync(e),r=e=>{let t=e;return t=t.replace(/((?:^|[\s;,(])(?:const|let|var)\s+VERSION\s*=\s*["'])##VERSION##(["'])/gm,`$1${s}$2`),t=t.replace(/((?:^|[\s;,(])(?:const|let|var)\s+COMMIT\s*=\s*["'])##COMMIT##(["'])/gm,`$1${this.commitHash}$2`),t=t.replace(/((?:^|[\s;,(])(?:const|let|var)\s+FULL_VERSION\s*=\s*["'])##FULL_VERSION##(["'])/gm,`$1${this.fullVersion}$2`),t=t.replace(/((?:^|[\s;,(])(?:exports|module\.exports)\.VERSION\s*=\s*["'])##VERSION##(["'])/gm,`$1${s}$2`),t=t.replace(/((?:^|[\s;,(])(?:exports|module\.exports)\.COMMIT\s*=\s*["'])##COMMIT##(["'])/gm,`$1${this.commitHash}$2`),t=t.replace(/((?:^|[\s;,(])(?:exports|module\.exports)\.FULL_VERSION\s*=\s*["'])##FULL_VERSION##(["'])/gm,`$1${this.fullVersion}$2`),t=t.replace(/((?:^|[\s;,(])\w+\.VERSION\s*=\s*["'])##VERSION##(["'])/gm,`$1${s}$2`),t=t.replace(/((?:^|[\s;,(])\w+\.COMMIT\s*=\s*["'])##COMMIT##(["'])/gm,`$1${this.commitHash}$2`),t=t.replace(/((?:^|[\s;,(])\w+\.FULL_VERSION\s*=\s*["'])##FULL_VERSION##(["'])/gm,`$1${this.fullVersion}$2`),t=t.replace(/((?:^|[\s;,(])(?:const|let|var)\s+PACKAGE_NAME\s*=\s*["'])##PACKAGE##(["'])/gm,`$1${o}$2`),t=t.replace(/((?:^|[\s;,(])(?:exports|module\.exports)\.PACKAGE_NAME\s*=\s*["'])##PACKAGE##(["'])/gm,`$1${o}$2`),t=t.replace(/((?:^|[\s;,(])\w+\.PACKAGE_NAME\s*=\s*["'])##PACKAGE##(["'])/gm,`$1${o}$2`),t};a.isDirectory()&&c.readdirSync(e,{withFileTypes:!0,recursive:!0}).filter(e=>e.isFile()).forEach(e=>{const t=l.join(e.parentPath,e.name),o=c.readFileSync(t,"utf8"),s=r(o);s!==o&&c.writeFileSync(t,s,"utf8"),K(t,Object.entries(this.replacements).reduce((e,[t,o])=>([$e,Ee,xe,Ne].includes(t)||(e[t]=o),e),{}))}),t.verbose(`Module ${o} ${s} patched in ${e}...`)}reportDiagnostics(e,t){const o=this.formatDiagnostics(e);try{this.log[t](o)}catch(e){throw e}return o}formatDiagnostics(e){return e.map(e=>{let t="";if(e.file&&e.start){const{line:o,character:s}=e.file.getLineAndCharacterOfPosition(e.start);t+=`${e.file.fileName} (${o+1},${s+1})`}return t+=": "+C.flattenDiagnosticMessageText(e.messageText,"\n"),t}).join("\n")}readConfigFile(e){const t=c.readFileSync(e).toString(),o=C.parseConfigFileTextToJson(e,t),s=o.config;s||this.reportDiagnostics([o.error],i.error);const a=C.parseJsonConfigFileContent(s,C.sys,l.dirname(e));return a.errors.length>0&&this.reportDiagnostics(a.errors,i.error),a}evalDiagnostics(e){if(e&&e.length>0){const t=e.filter(e=>e.category===C.DiagnosticCategory.Error),o=e.filter(e=>e.category===C.DiagnosticCategory.Warning),s=e.filter(e=>e.category===C.DiagnosticCategory.Suggestion),a=e.filter(e=>e.category===C.DiagnosticCategory.Message);if(o.length&&this.reportDiagnostics(o,i.warn),t.length)throw this.reportDiagnostics(e,i.error),Error(`TypeScript reported ${e.length} diagnostic(s) during check; aborting.`);s.length&&this.reportDiagnostics(s,i.info),a.length&&this.reportDiagnostics(a,i.info)}}preCheckDiagnostics(e){const t=C.getPreEmitDiagnostics(e);this.evalDiagnostics(t)}async checkTsDiagnostics(e,t,o=!1){const s=this.log.for(this.checkTsDiagnostics);let a;try{a=this.readConfigFile("./tsconfig.json")}catch(e){throw Error("Failed to parse tsconfig.json: "+e)}this.applyTsConfigProfile(a.options,o?Re.BUNDLE:t===Ie.ESM?Re.ESM:Re.CJS_CHECK,e);const r=C.createProgram(a.fileNames,a.options);this.preCheckDiagnostics(r),s.verbose(`TypeScript checks passed (${o?"bundle":"normal"} mode).`)}async buildTs(e,t,o=!1){let s;this.log.for(this.buildTs).info(`Building ${this.pkgName} ${this.pkgVersion} module (${t}) in ${e?"dev":"prod"} mode...`);try{s=this.readConfigFile("./tsconfig.json")}catch(e){throw Error("Failed to parse tsconfig.json: "+e)}this.applyTsConfigProfile(s.options,o?Re.BUNDLE:t===Ie.ESM?Re.ESM:Re.CJS_CHECK,e);const a=C.createProgram(s.fileNames,s.options),r={};t===Ie.ESM&&(r.before=[Me(".js")]);const n=a.emit(void 0,void 0,void 0,void 0,r),i=C.getPreEmitDiagnostics(a).concat(n.diagnostics);this.evalDiagnostics(i)}async build(e,t,o=!1){const s=this.log.for(this.build);await this.buildTs(e,t,o),s.verbose(`Module ${this.pkgName} ${this.pkgVersion} (${t}) built in ${e?"dev":"prod"} mode...`),t!==Ie.CJS||o||await this.buildCjsFromEsm(e)}rewriteRelativeJsSpecifiersToCjs(e){return e.replace(/(["'])(\.{1,2}\/[^"']+?)(\1)/g,(e,t,o,s)=>`${t}${(e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")?e.endsWith(".cjs")?e:e.endsWith(".js")?e.replace(/\.js$/,".cjs"):e:e)(o)}${s}`)}async buildCjsFromEsm(e){this.log.for(this.buildCjsFromEsm).info(`Building ${this.pkgName} ${this.pkgVersion} module (${Ie.CJS}) from ESM output in ${e?"dev":"prod"} mode...`);const t=l.resolve("lib/esm"),o=l.resolve("lib/cjs");c.mkdirSync(o,{recursive:!0});const s=X(t,e=>e.endsWith(".js")&&!e.endsWith(".d.js"));for(const a of s){const s=l.relative(t,a),r=Oe(s),n=Be(l.join(o,s),".cjs");c.mkdirSync(l.dirname(n),{recursive:!0});const i=c.readFileSync(a,"utf8"),d=C.transpileModule(i,{compilerOptions:{module:D.CommonJS,target:C.ScriptTarget.ES2022,sourceMap:!e,inlineSourceMap:e,inlineSources:e,esModuleInterop:!0},fileName:r,reportDiagnostics:!0});d.diagnostics?.length&&this.evalDiagnostics(d.diagnostics);const g=l.basename(n)+".map";let h=this.rewriteRelativeJsSpecifiersToCjs(d.outputText);if(d.sourceMapText&&(h=h.replace(/\/\/# sourceMappingURL=.*$/m,"//# sourceMappingURL="+g)),c.writeFileSync(n,h,"utf8"),d.sourceMapText){const e=JSON.parse(d.sourceMapText);e.file=Oe(Be(r,".cjs")),e.sources=[r],c.writeFileSync(n+".map",JSON.stringify(e)+"\n","utf8")}}}applyTsConfigProfile(e,t,o){switch(e.declaration=!1,e.emitDeclarationOnly=!1,e.noEmit=!1,e.outFile=void 0,e.moduleResolution=$.Bundler,t){case Re.ESM:e.module=D.ESNext,e.outDir="lib/esm";break;case Re.CJS_CHECK:e.module=D.Preserve??D.ESNext,e.moduleResolution=$.Bundler,e.noEmit=!0,e.outDir=void 0;break;case Re.TYPES:e.module=D.ESNext,e.outDir="lib/types",e.declaration=!0,e.emitDeclarationOnly=!0;break;case Re.NODE_NEXT_VALIDATE:e.module=D.NodeNext,e.moduleResolution=$.NodeNext,e.noEmit=!0;break;case Re.BUNDLE:e.module=D.ESNext,e.moduleResolution=$.Bundler,e.outDir="dist",e.isolatedModules=!1,e.outFile=void 0}if(t===Re.NODE_NEXT_VALIDATE)return e.inlineSourceMap=!1,e.inlineSources=!1,void(e.sourceMap=!1);o?(e.inlineSourceMap=!0,e.inlineSources=!0,e.sourceMap=!1):(e.inlineSourceMap=!1,e.inlineSources=!1,e.sourceMap=!0)}async checkNodeNextCompatibility(){const e=this.log.for(this.checkNodeNextCompatibility);let t;try{t=this.readConfigFile("./tsconfig.json")}catch(e){throw Error("Failed to parse tsconfig.json: "+e)}this.applyTsConfigProfile(t.options,Re.NODE_NEXT_VALIDATE,!1);const o=C.createProgram(t.fileNames,t.options);this.preCheckDiagnostics(o),e.verbose("TypeScript NodeNext compatibility check passed.")}async buildTypes(e){let t;this.log.for(this.buildTypes).info(`Building ${this.pkgName} ${this.pkgVersion} declaration files...`);try{t=this.readConfigFile("./tsconfig.json")}catch(e){throw Error("Failed to parse tsconfig.json: "+e)}this.applyTsConfigProfile(t.options,Re.TYPES,e);const o=C.createProgram(t.fileNames,t.options),s=o.emit(),a=C.getPreEmitDiagnostics(o).concat(s.diagnostics);this.evalDiagnostics(a),this.emitDualDeclarationFiles(),this.removeLegacyDeclarationFiles(),this.updatePackageJsonDualTypeExports()}rewriteRelativeDeclarationSpecifiers(e,t,o){const s=l.dirname(o),a=e=>{if(!e.startsWith("./")&&!e.startsWith("../")&&!e.startsWith("/"))return e;if(/\.(d\.(mts|cts)|mts|cts|ts|json)$/i.test(e))return e;const o=l.resolve(s,e);try{if(c.existsSync(o)&&c.statSync(o).isDirectory())return`${e}/index${t}`}catch{}return`${e}${t}`};let r=e.replace(/(\b(?:import|export)\b[\s\S]*?\bfrom\s*["'])([^"']+)(["'])/gm,(e,t,o,s)=>`${t}${a(o)}${s}`);return r=r.replace(/(\bimport\s*\(\s*["'])([^"']+)(["']\s*\))/gm,(e,t,o,s)=>`${t}${a(o)}${s}`),r=r.replace(/(\brequire\s*\(\s*["'])([^"']+)(["']\s*\))/gm,(e,t,o,s)=>`${t}${a(o)}${s}`),r}emitDualDeclarationFiles(){const e=this.log.for(this.emitDualDeclarationFiles),t=l.resolve("lib/types");if(!c.existsSync(t))return;const o=X(t,e=>e.endsWith(".d.ts"));for(const e of o){const t=c.readFileSync(e,"utf8"),o=e.replace(/\.d\.ts$/i,".d.mts"),s=e.replace(/\.d\.ts$/i,".d.cts");c.writeFileSync(o,this.rewriteRelativeDeclarationSpecifiers(t,".d.mts",e),"utf8"),c.writeFileSync(s,this.rewriteRelativeDeclarationSpecifiers(t,".d.cts",e),"utf8")}e.verbose(`Generated ${2*o.length} dual declaration files.`)}removeLegacyDeclarationFiles(){const e=this.log.for(this.removeLegacyDeclarationFiles),t=l.resolve("lib/types");if(!c.existsSync(t))return;const o=X(t,e=>e.endsWith(".d.ts")||e.endsWith(".d.ts.map"));for(const e of o)try{c.unlinkSync(e)}catch{}e.verbose(`Removed ${o.length} legacy declaration files.`)}updatePackageJsonDualTypeExports(){const e=this.log.for(this.updatePackageJsonDualTypeExports),t=l.resolve("package.json");if(!c.existsSync(t))return;const o=JSON.parse(c.readFileSync(t,"utf8")),s=o?.exports;if(!s||"object"!=typeof s)return;const a=(e,t)=>e.replace(/\.d\.(ts|mts|cts)$/i,t),r=e=>{if(e)return e.includes("/lib/esm/")?e.replace("/lib/esm/","/lib/cjs/").replace(/\.js$/i,".cjs"):e},n=(e,t=".d.mts")=>{if(e)return e.includes("/lib/esm/")?e.replace("/lib/esm/","/lib/types/").replace(/\.js$/i,t):void 0},i=e=>"string"==typeof e?e:e&&"object"==typeof e&&"string"==typeof e.default?e.default:void 0,d=e=>{if(e&&"object"==typeof e&&"string"==typeof e.types)return e.types},g={};for(const[e,t]of Object.entries(s)){if(!t||"object"!=typeof t||Array.isArray(t)){g[e]=t;continue}const o=t,s=i(o.import),c=i(o.require),l=c&&c.includes("/lib/esm/")?r(c):c||r(s),h=i(o.default),u=("string"==typeof o.types?o.types:void 0)||d(o.import),f=u&&/\.d\.(ts|mts|cts)$/i.test(u)?a(u,".d.mts"):d(o.import)||n(s,".d.mts"),p=u&&/\.d\.(ts|mts|cts)$/i.test(u)?a(u,".d.cts"):d(o.require)||n(s,".d.cts");g[e]={...s?{import:{...f?{types:f}:{},default:s}}:{},...l?{require:{...p?{types:p}:{},default:l}}:{},...h||s?{default:h||s}:{}}}o.exports=g,"string"==typeof o.types&&/\.d\.(ts|mts|cts)$/i.test(o.types)&&(o.types=o.types.replace(/\.d\.(ts|mts|cts)$/i,".d.mts")),c.writeFileSync(t,JSON.stringify(o,null,2)+"\n","utf8"),e.verbose("Updated package.json exports with import/require type conditions.")}copyAssets(e){const t=this.log.for(this.copyAssets);let o=!1;try{o=c.statSync("./src/assets").isDirectory()}catch(e){return t.verbose("No assets found in ./src/assets to copy")}o&&Z("./src/assets",`./${e===Ie.CJS?"lib":"dist"}/assets`)}async bundle(e,t,o,s="./src/index.ts",a=this.pkgName,r,n=["prompts","styled-string-builder","typed-object-accumulator","@decaf-ts/logging"]){await this.checkTsDiagnostics(t,e,!0);const i=e===Ie.ESM,c=this.pkgName,d=this.log,h=Array.from(new Set([...ke(n)]));let u=ke(r);if(0===u.length){try{u=he(l.join(process.cwd(),"node_modules"))}catch{}u&&0!==u.length||(u=De())}const f=Array.from(new Set([...(()=>{try{return Array.isArray(g)?g:[]}catch{return["fs","path","process","child_process","util","https","http","os","stream","crypto","zlib","net","tls","url","querystring","assert","events","tty","dns","querystring"]}})(),...u])),p=!t||"inline",m=[w({compilerOptions:{module:"esnext",declaration:!1,outDir:o?"bin":"dist",sourceMap:!t,inlineSourceMap:!!t,inlineSources:!!t},include:["src/**/*.ts"],exclude:["node_modules","**/*.spec.ts"],tsconfig:"./tsconfig.json"}),k()];o&&m.push(v({include:[],exclude:u}),T({resolveOnly:h}));try{const C=await import("@rollup/plugin-terser"),D=C&&C.terser||C.default||C,$={parse:{ecma:2020},compress:!1,mangle:!1,format:{comments:!1,beautify:!0}},E={parse:{ecma:2020},compress:{ecma:2020,passes:5,drop_console:!0,drop_debugger:!0,toplevel:!0,module:i,unsafe:!0,unsafe_arrows:!0,unsafe_comps:!0,collapse_vars:!0,reduce_funcs:!0,reduce_vars:!0},mangle:{toplevel:!0},format:{comments:!1,ascii_only:!0},toplevel:!0};m.push(D(t?$:E))}catch{}const y={input:s,plugins:m,external:f,onwarn:void 0,treeshake:!t},S={};f.forEach(e=>{S[e]=Ce(e)});const b=[{dir:o?"bin":"dist",entryFileNames:`${a||".bundle."+(t?"":"min")}${i?".js":".cjs"}`,format:o?"cjs":i?"esm":"umd",name:c,esModule:i,sourcemap:p,globals:S,exports:"auto"}];try{const{rollup:x}=await import("rollup"),N=await x(y);async function F(e){for(const t of b)await e.write(t)}d.verbose(N.watchFiles);try{await F(N)}finally{await N.close()}}catch(I){throw Error("Failed to bundle: "+I)}}async buildByEnv(e="./src/index.ts",t,o=Ae.ALL,s=!1,a,r){s&&await this.checkNodeNextCompatibility();try{Q("lib")}catch(e){}try{Q("dist")}catch(e){}[Ae.ALL,Ae.BUILD].includes(o)&&(c.mkdirSync("lib",{recursive:!0}),await this.build(t,Ie.ESM),await this.build(t,Ie.CJS),await this.buildTypes(t),this.patchFiles("lib")),[Ae.ALL,Ae.BUNDLE].includes(o)&&(c.mkdirSync("dist"),await this.bundle(Ie.ESM,t,!1,e||"./src/index.ts",this.pkgName,r,a),await this.bundle(Ie.CJS,t,!1,e||"./src/index.ts",this.pkgName,r,a),this.patchFiles("dist")),this.copyAssets(Ie.CJS),this.copyAssets(Ie.ESM)}async buildDev(e="./src/index.ts",t=Ae.ALL,o=!1,s,a){return this.buildByEnv(e,!0,t,o,s,a)}async buildProd(e="./src/index.ts",t=Ae.ALL,o=!1,s,a){return this.buildByEnv(e,!1,t,o,s,a)}async buildDocs(){await J("npm install better-docs taffydb").promise,await J("npx markdown-include ./workdocs/readme-md.json").promise,await J("npx jsdoc -c ./workdocs/jsdocs.json -t ./node_modules/better-docs").promise,await J("npm remove better-docs taffydb").promise,[{src:"workdocs/assets",dest:"./docs/workdocs/assets"},{src:"workdocs/reports/coverage",dest:"./docs/workdocs/reports/coverage"},{src:"workdocs/reports/html",dest:"./docs/workdocs/reports/html"},{src:"workdocs/resources",dest:"./docs/workdocs/resources"},{src:"LICENSE.md",dest:"./docs/LICENSE.md"}].forEach(e=>{const{src:t,dest:o}=e;Z(t,o)});try{const e=await de(l.resolve(l.join(process.cwd(),"dist")));this.replacements[Fe]=e+" KB"}catch{this.replacements[Fe]="unknown"}try{K("./README.md",this.replacements)}catch(e){this.log.for(this.buildDocs).verbose("Failed to patch README.md: "+e)}}async run(e){const{dev:t,prod:o,docs:s,buildMode:a,includes:r,externals:n,entry:i,validateNodeNext:c}=e;return t?await this.buildDev(i||"./src/index.ts",a,!!c,r,n):o?await this.buildProd(i||"./src/index.ts",a,!!c,r,n):s?await this.buildDocs():void 0}}function Ue(e,t,o,s,a,r=[],n=[]){e.info(""+t),e.info(o),e.info("Usage: "+s),e.info("Options:");for(const t of a){const o=t.defaultValue?` (default: ${t.defaultValue})`:"";e.info(` ${t.flag} ${t.description}${o}`)}if(r.length>0){e.info("Notes:");for(const t of r)e.info(" "+t)}if(n.length>0){e.info("Examples:");for(const t of n)e.info(" "+t)}}const Le={ci:{type:"boolean",default:!0},message:{type:"string",short:"m"},tag:{type:"string",short:"t",default:void 0}};class _e extends ye{constructor(){super("ReleaseScript",Le)}async prepareVersion(e){const t=this.log.for(this.prepareVersion);return(e=this.testVersion(e||""))||(t.verbose("No release version provided. Prompting for one:"),t.info("Listing latest git tags:"),await J("git tag --sort=-taggerdate | head -n 5").promise,await F.insistForText("tag","Enter the new tag number (accepts v*.*.*[-...])",e=>!!e.toString().match(/^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9a-zA-Z-]+)?$/)))}testVersion(e){const t=this.log.for(this.testVersion);switch(e=e.trim().toLowerCase()){case M.PATCH:case M.MINOR:case M.MAJOR:return t.verbose("Using provided SemVer update: "+e,1),e;default:return t.verbose("Testing provided version for SemVer compatibility: "+e,1),RegExp(j).test(e)?(t.verbose("version approved: "+e,1),e):void t.debug("Invalid version number: "+e)}}async prepareMessage(e){const t=this.log.for(this.prepareMessage);return e||(t.verbose("No release message provided. Prompting for one"),await F.insistForText("message","What should be the release message/ticket?",e=>!!e&&e.toString().length>5))}help(){Ue(this.log,"tag-release","Prepare, tag, and publish a release from the current repository.","tag-release [options]",[{flag:"--tag <version>",description:"Release tag to use"},{flag:"--message <text>",description:"Release message or ticket reference"},{flag:"--ci <true|false>",description:"Whether to treat the run as CI",defaultValue:"true"},{flag:"--version",description:"Print the package version and exit"},{flag:"-h, --help",description:"Show this help text and exit"}],["If tag or message are omitted, the command prompts interactively.","A successful run updates the package version, creates a git tag, pushes tags, and optionally publishes to npm."],['tag-release --tag v1.2.3 --message "Release 1.2.3"','tag-release --tag patch --message "Fix release"'])}async run(e){let t;const{ci:o}=e;let{tag:s,message:a}=e;s=await this.prepareVersion(s),a=await this.prepareMessage(a),t=await J(`npm run prepare-release -- ${s} ${a}`,{cwd:process.cwd()}).promise,t=await J("git status --porcelain").promise,await t,t.logs.length&&await F.askConfirmation("git-changes","Do you want to push the changes to the remote repository?",!0)&&(await J("git add .").promise,await J(`git commit -m "${s} - ${a} - after release preparation${o?"":O}"`).promise),await J(`npm version "${s}" -m "${a}${o?"":O}"`).promise,await J("git push --follow-tags").promise,o||await J("NPM_TOKEN=$(cat .npmtoken) npm publish --access public").promise}}const Ve=o.for("ReleaseChainRunner");class He{constructor(e){this.options=e,this.workspace=e.workspace??process.cwd(),this.clonesRoot=l.join(this.workspace,".release-chain"),this.token=e.token||process.env.RELEASE_CHAIN_TOKEN||process.env.GITHUB_TOKEN||process.env.GH_TOKEN,this.metaRepoSlug=Ke(e.metaRepoUrl)||Ye("Unable to normalize META repo URL"),this.currentRepo=Ke(e.currentRepo)||Xe()}async run(){const e=await this.loadSubmodules();if(!e.length)return void Ve.warn("No modules detected in provided .gitmodules file");const t=this.currentRepo?e.findIndex(e=>e.slug===this.currentRepo):-1,o=0>t?e:e.slice(t+1);Ve.info(`Evaluating ${o.length} repositories for ${this.options.packageName}`);for(const e of o)await this.evaluateModule(e)}async evaluateModule(e){if(!e.slug)return void Ve.verbose(`Skipping ${e.name}: unsupported repository URL`);Ve.info("\n[release-chain] "+e.slug);const t=l.join(this.clonesRoot,e.slug.replace(/\//g,"__"));c.rmSync(t,{recursive:!0,force:!0}),c.mkdirSync(t,{recursive:!0}),this.cloneRepository(e.url,t),await this.checkoutTargetBranch(t);const o=l.join(t,"package.json");if(!c.existsSync(o))return void Ve.debug("No package.json detected for "+e.slug);if(s=JSON.parse(c.readFileSync(o,"utf8")),a=this.options.packageName,!["dependencies","devDependencies","peerDependencies","optionalDependencies"].some(e=>!!s?.[e]?.[a]))return void Ve.debug(`${e.slug} does not depend on ${this.options.packageName}`);var s,a;if((e=>{try{E("git config user.name",{cwd:e,stdio:"pipe"}),E("git config user.email",{cwd:e,stdio:"pipe"})}catch{E("git config user.name 'release-chain'",{cwd:e}),E("git config user.email 'release-chain@users.noreply.github.com'",{cwd:e})}})(t),this.runCommand("npm install --ignore-scripts",t),this.runCommand("npm update "+this.options.packageName,t),this.runCommand("npm run build --if-present",t),this.runCommand("npm run test --if-present",t),!E("git status --porcelain",{cwd:t,encoding:"utf8"}).trim())return void Ve.info("No changes detected for "+e.slug);this.runCommand("git add -A",t),this.runCommand(`git commit -m "chore: release chain update for ${this.options.packageName}"`,t),this.runCommand(`git push origin ${this.options.branch} --force-with-lease`,t);const r=await this.findExistingPr(e.slug);if(r)return Ve.info(`Existing PR #${r.number} detected for ${e.slug}, attempting merge`),void await this.acceptPullRequest(e.slug,r.number,r.head.sha);const n=this.options.targetBaseBranch||await this.getDefaultBranch(e.slug);await this.createPullRequest(e.slug,n)}cloneRepository(e,t){const o=((e,t)=>{const o=qe(e);if(!t)return o;const s=new URL(o);return s.username="x-access-token",s.password=t,s.toString()})(e,this.token);this.runCommand(`git clone --no-tags --depth 1 ${o} ${t}`)}async checkoutTargetBranch(e){try{return this.runCommand(`git fetch origin ${this.options.branch}:${this.options.branch}`,e),this.runCommand("git checkout "+this.options.branch,e),void this.runCommand("git reset --hard origin/"+this.options.branch,e)}catch(e){Ve.verbose(`Branch ${this.options.branch} not found remotely; creating from default`)}const t=(e=>{try{return E("git symbolic-ref --short refs/remotes/origin/HEAD",{cwd:e,encoding:"utf8"}).trim().split("/").pop()||"main"}catch{return"main"}})(e);this.runCommand(`git checkout -b ${this.options.branch} origin/${t}`,e)}async loadSubmodules(){if(this.options.submodulePath&&c.existsSync(this.options.submodulePath))return Ge(c.readFileSync(this.options.submodulePath,"utf8"));const e=[this.options.submoduleFile,".gitsubmodule",".gitmodules"].filter(Boolean);for(const t of e)try{const e=await ze(this.metaRepoSlug,this.options.branch,t,this.token);if(e)return Ge(e)}catch(o){if(t===e[e.length-1])throw o}return[]}runCommand(e,t=this.workspace){Ve.debug(`[${t}] ${e}`),E(e,{cwd:t,stdio:"inherit",env:Object.assign({},process.env,{RELEASE_CHAIN_TOKEN:this.token})})}async githubRequest(e,t){const o={"User-Agent":"decaf-release-chain",Accept:"application/vnd.github+json"};this.token&&(o.Authorization="Bearer "+this.token);const s=await fetch("https://api.github.com"+e,{method:t?.method||"GET",headers:Object.assign({},o,t?.headers),body:t?.body});if(!s.ok){const e=await s.text();throw Error(`GitHub API ${s.status}: ${e}`)}if(204!==s.status)return await s.json()}async findExistingPr(e){const[t]=e.split("/"),o=await this.githubRequest(`/repos/${e}/pulls?head=${t}%3A${encodeURIComponent(this.options.branch)}&state=open&per_page=1`);return o?.[0]}async acceptPullRequest(e,t,o){await this.githubRequest(`/repos/${e}/pulls/${t}/merge`,{method:"PUT",body:JSON.stringify({merge_method:"squash",commit_title:"chore: accept release chain for "+this.options.packageName,sha:o})})}async createPullRequest(e,t){await this.githubRequest(`/repos/${e}/pulls`,{method:"POST",body:JSON.stringify({title:this.options.branch+"-release-chain",head:this.options.branch,base:t,body:`Automated dependency update for ${this.options.packageName}.`})})}async getDefaultBranch(e){const t=await this.githubRequest("/repos/"+e);return t?.default_branch||"main"}}async function Je(e){const t=new He(e);await t.run()}async function We(e){const t=e.token||process.env.RELEASE_CHAIN_TRIGGER_TOKEN||process.env.RELEASE_CHAIN_TOKEN||process.env.GITHUB_TOKEN||process.env.GH_TOKEN,o=e.repoSlug||Xe()||Ye("Unable to determine repository slug for dispatch"),s=e.workflowFile||"release-chain.yaml",a=e.ref||e.branch,r=Ke(e.currentRepo)||o;Ve.info(`Dispatching ${s} on ${o} for ${e.branch} (current repo ${r})`);const n={"User-Agent":"decaf-release-chain-dispatch",Accept:"application/vnd.github+json","Content-Type":"application/json"};t&&(n.Authorization="Bearer "+t);const i=await fetch(`https://api.github.com/repos/${o}/actions/workflows/${s}/dispatches`,{method:"POST",headers:n,body:JSON.stringify({ref:a,inputs:{meta_repo_url:e.metaRepoUrl,branch:e.branch,current_repo:r,target_branch:e.targetBaseBranch||""}})});if(!i.ok){const e=await i.text();throw Error(`Workflow dispatch failed: ${i.status} ${e}`)}}function Ge(e){return e.split("[submodule").slice(1).map(e=>{const t=e.match(/"(.+?)"\]/),o=e.match(/path\s*=\s*(.+)/),s=e.match(/url\s*=\s*(.+)/),a=s?.[1]?.trim()||"";return{name:t?.[1]?.trim()||"",path:o?.[1]?.trim()||"",url:a,slug:Ke(a)}}).filter(e=>e.url)}function Ke(e){if(e){if(e.includes("github.com")){const t=qe(e);return new URL(t).pathname.replace(/^\//,"").replace(/\.git$/,"")}return e.replace(/^\//,"")}}function qe(e){return e.startsWith("git@github.com:")?"https://github.com/"+e.replace("git@github.com:",""):e.startsWith("ssh://git@github.com/")?"https://github.com/"+e.replace("ssh://git@github.com/",""):e.replace(/\.git$/,"")}async function ze(e,t,o,s){const a=`https://raw.githubusercontent.com/${e}/${t}/${o}`,r={"User-Agent":"decaf-release-chain"};s&&(r.Authorization="Bearer "+s);const n=await fetch(a,{headers:r});if(404===n.status)return null;if(!n.ok){const e=await n.text();throw Error(`Failed to download ${o}: ${n.status} ${e}`)}return n.text()}function Xe(){if(process.env.GITHUB_REPOSITORY)return process.env.GITHUB_REPOSITORY;try{return Ke(E("git config --get remote.origin.url",{encoding:"utf8"}).trim().replace(/\s+/g,""))}catch{return}}function Ye(e){throw Error(e)}const Ze={meta:{type:"string",default:process.env.RELEASE_CHAIN_META_REPO_URL||""},branch:{type:"string",default:process.env.RELEASE_CHAIN_BRANCH||process.env.GITHUB_REF_NAME||"main"},current:{type:"string",default:process.env.RELEASE_CHAIN_CURRENT||process.env.GITHUB_REPOSITORY||""},package:{type:"string",default:""},token:{type:"string",default:process.env.RELEASE_CHAIN_TOKEN||""},submoduleFile:{type:"string",default:process.env.RELEASE_CHAIN_FILE||""},submodulePath:{type:"string",default:process.env.RELEASE_CHAIN_FILE_PATH||""},workflow:{type:"string",default:process.env.RELEASE_CHAIN_WORKFLOW||"release-chain.yaml"},repo:{type:"string",default:process.env.RELEASE_CHAIN_REPO||""},ref:{type:"string",default:process.env.RELEASE_CHAIN_REF||""},targetBase:{type:"string",default:process.env.RELEASE_CHAIN_TARGET||""}};class Qe extends ye{constructor(){super("ReleaseChain",Object.assign({},I,Ze))}help(){Ue(this.log,"release-chain","Run the release-chain workflow locally across repositories.","release-chain [options]",[{flag:"--meta <url>",description:"Meta repository URL"},{flag:"--branch <name>",description:"Branch to update downstream repositories",defaultValue:"main or detected branch"},{flag:"--current <owner/repo>",description:"Current repository slug to resume after in the chain"},{flag:"--package <name>",description:"Override detected package name"},{flag:"--token <token>",description:"GitHub token for cloning and pushing"},{flag:"--submodule-file <file>",description:"Override submodule file name"},{flag:"--submodule-path <path>",description:"Use a local submodule file instead of downloading"},{flag:"--target-base <branch>",description:"Base branch for downstream pull requests"},{flag:"-h, --help",description:"Show this help text and exit"}],["Missing meta or branch values are detected from git and environment variables when possible."])}async run(e){const t=e,o=t.package||ee(process.cwd())?.name;if(!o)throw Error("Unable to determine package name");const s=t.meta||tt();if(!s)throw Error("A meta repository URL is required");const a=t.branch||ot();await Je({metaRepoUrl:s,branch:a,currentRepo:t.current,packageName:o,token:t.token,submoduleFile:t.submoduleFile||void 0,submodulePath:t.submodulePath||void 0,targetBaseBranch:t.targetBase||void 0})}}class et extends ye{constructor(){super("ReleaseChainDispatch",Object.assign({},I,Ze))}help(){Ue(this.log,"release-chain-dispatch","Dispatch the release-chain GitHub Actions workflow.","release-chain-dispatch [options]",[{flag:"--meta <url>",description:"Meta repository URL"},{flag:"--branch <name>",description:"Branch to evaluate in downstream repositories",defaultValue:"main or detected branch"},{flag:"--current <owner/repo>",description:"Repository slug that triggered the release chain"},{flag:"--workflow <file>",description:"Workflow file name",defaultValue:"release-chain.yaml"},{flag:"--repo <owner/repo>",description:"Target repository slug where the workflow lives"},{flag:"--token <token>",description:"GitHub token for dispatching workflows"},{flag:"--ref <ref>",description:"Git ref to dispatch the workflow on"},{flag:"--target-base <branch>",description:"Base branch for downstream pull requests"},{flag:"-h, --help",description:"Show this help text and exit"}],["Missing meta or branch values are detected from git and environment variables when possible."])}async run(e){const t=e,o=t.meta||tt();if(!o)throw Error("A meta repository URL is required");const s=t.branch||ot();await We({metaRepoUrl:o,branch:s,workflowFile:t.workflow||"release-chain.yaml",repoSlug:t.repo,currentRepo:t.current,token:t.token,ref:t.ref||s,targetBaseBranch:t.targetBase||void 0})}}function tt(){try{return E("git config --get remote.origin.url",{encoding:"utf8"}).trim()}catch{return}}function ot(){try{return E("git rev-parse --abbrev-ref HEAD",{encoding:"utf8"}).trim()}catch{return"main"}}function st(e=process.cwd()){const t=N.join(e,".gitmodules");return x.readFileSync(t,"utf8").toString().match(/(?<=").*?(?="])/g)||[]}function at(e=process.cwd(),t=2){const o=new Set,s=new Set,a=(e,t,r="")=>{const n=N.resolve(e);if(s.has(n))return;s.add(n);let i=[];try{i=st(e)}catch{return}for(const s of i){const n=r?N.join(r,s):s;if(o.add(n),0>=t)continue;const i=N.join(e,s),c=N.join(i,".gitmodules");x.existsSync(c)&&a(i,t-1,n)}};return a(e,t),Array.from(o)}const rt={basePath:{type:"string",default:process.cwd()}};class nt extends ye{constructor(){super("ModulesCommand",rt)}help(){Ue(this.log,"modules","List modules discovered from .gitmodules.","modules [options]",[{flag:"--base-path <path>",description:"Directory to read .gitmodules from",defaultValue:"current working directory"},{flag:"-h, --help",description:"Show this help text and exit"}],["Each discovered module path is printed on its own line."],["modules","modules --base-path ../repo"])}async run(e){st(e.basePath).forEach(e=>this.log.info(e))}}const it={maxTraversal:{type:"string",default:"2"},excludes:{type:"string",multiple:!0,default:["@decaf-ts/utils","@decaf-ts/logging"]},include:{type:"string",multiple:!0,default:[]},packages:{type:"string",multiple:!0,default:[]},mainPackagePath:{type:"string",default:""},operation:{type:"string",default:"link"}};function ct(e){return e.split("/")[1]||e}function lt(e){return[...Object.keys(e.dependencies||{}),...Object.keys(e.devDependencies||{}),...Object.keys(e.peerDependencies||{})]}function dt(e){return Array.isArray(e)?e.map(e=>(""+e).trim()).filter(Boolean):"string"==typeof e&&e.length>0?e.split(",").map(e=>e.trim()).filter(Boolean):[]}function gt(e,t){if(t.includes("*")){const o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*");return RegExp(`^${o}$`).test(e)}return e===t||N.basename(e)===t||e.endsWith("/"+t)}class ht extends ye{constructor(){super("NpmLinkCommand",it)}help(){Ue(this.log,"npm-link","Link or unlink decaf-ts package outputs across linked modules.","npm-link [options]",[{flag:"--max-traversal <depth>",description:"How many nested .gitmodules levels to traverse",defaultValue:"2"},{flag:"--excludes <items...>",description:"Dependency names or patterns to ignore",defaultValue:"@decaf-ts/utils,@decaf-ts/logging"},{flag:"--include <items...>",description:"Module names or paths to target explicitly"},{flag:"--packages <items...>",description:"Additional non-decaf packages to link or unlink"},{flag:"--main-package-path <path>",description:"Path to the package tree that provides the original decaf packages"},{flag:"--operation <name>",description:"Operation to run in each module",defaultValue:"link"},{flag:"-h, --help",description:"Show this help text and exit"}],["link creates symlinks for decaf-ts dependencies","link can also include extra non-decaf packages passed via --packages","when --packages is set, --main-package-path is required and is used as the source root","unlink removes those links and reinstalls dependencies","any other operation is passed through to npm in each selected module"],["npm-link --operation link","npm-link --operation unlink","npm-link --operation install --include packages/app","npm-link --packages @scope/* --main-package-path ../packages --include packages/app"])}async run(e){const t=Number.parseInt(""+(e.maxTraversal||"2"),10),o=dt(e.include),s=dt(e.excludes),a=dt(e.packages),r=(""+(e.mainPackagePath||"")).trim(),n=["@decaf-ts/utils","@decaf-ts/logging"],i=(""+(e.operation||"link")).trim()||"link",c=r?N.resolve(r):process.cwd();if(a.length>0&&!r)return void process.exit(1);const l=JSON.parse(x.readFileSync(N.join(c,"package.json"),"utf8")).name.split("/")[0]||"",d=at(process.cwd(),Number.isFinite(t)?t:2).filter(e=>0>=o.length||o.some(t=>gt(e,t))),g=e=>(s.length>0?s:n).some(t=>gt(e,t));for(const e of d){const t=N.join(process.cwd(),e);let o;try{o=JSON.parse(x.readFileSync(N.join(t,"package.json"),"utf8"))}catch{continue}const s=lt(o).filter(e=>{return(t=e).startsWith(l)||a.some(e=>gt(t,e));var t});if("link"!==i)if("unlink"!==i)try{E("npm "+i,{cwd:t,env:process.env,stdio:"inherit"})}catch{process.exit(1)}else{for(const e of s)if(!g(e))try{x.rmSync(N.join(t,"node_modules",e),{force:!0,recursive:!0})}catch{process.exit(1)}try{E("npm run do-install",{cwd:t,env:process.env,stdio:"inherit"})}catch{process.exit(1)}}else for(const e of s){if(g(e))continue;const o=e.endsWith("styles")?"dist":"lib",s=ct(e);try{const a=N.join(t,"node_modules",e),r=N.join(t,"node_modules",e),n=N.join(c,s,o),i=N.join(a,o);if(!x.existsSync(n))continue;x.rmSync(r,{force:!0,recursive:!0}),x.mkdirSync(a,{recursive:!0}),x.rmSync(i,{force:!0,recursive:!0}),x.symlinkSync(N.relative(a,n),i,"dir")}catch(e){process.exit(1)}}}}}const ut={maxTraversal:{type:"string",default:"2"},tokenFiles:{type:"string",multiple:!0,default:[".token",".npmtoken"]}};class ft extends ye{constructor(){super("NpmTokenCommand",ut)}help(){Ue(this.log,"npm-token","Link token files into every module discovered in .gitmodules.","npm-token [options]",[{flag:"--max-traversal <depth>",description:"How many nested .gitmodules levels to traverse",defaultValue:"2"},{flag:"--token-files <files...>",description:"Token files to link into each selected module",defaultValue:".token,.npmtoken"},{flag:"-h, --help",description:"Show this help text and exit"}],["The command creates symlinks from each selected module back to the token files in the repository root."],["npm-token","npm-token --token-files .token .npmtoken secrets/npm.token"])}async run(e){const t=Number.parseInt(""+(e.maxTraversal||"2"),10),o=(s=e.tokenFiles,Array.isArray(s)?s.map(e=>(""+e).trim()).filter(Boolean):"string"==typeof s&&s.length>0?s.split(",").map(e=>e.trim()).filter(Boolean):[]);var s;const a=o.length>0?o:[".token",".npmtoken"],r=at(process.cwd(),Number.isFinite(t)?t:2);for(const e of r){const t=N.join(process.cwd(),e);try{for(const e of a)x.rmSync(N.join(t,e),{force:!0,recursive:!0}),x.symlinkSync(N.join("..",e),N.join(t,e))}catch{process.exit(1)}}}}const pt={basePath:{type:"string",default:process.cwd()},command:{type:"string",default:void 0}};class mt extends ye{constructor(){super("RunAllCommand",pt)}help(){Ue(this.log,"run-all","Run a shell command in every module listed in .gitmodules.","run-all [options] --command <cmd>",[{flag:"--base-path <path>",description:"Directory to read .gitmodules from",defaultValue:"current working directory"},{flag:"--command <cmd>",description:"Shell command to execute in each module"},{flag:"-h, --help",description:"Show this help text and exit"}],["The command fails fast if any module invocation fails."],["run-all --command npm test","run-all --base-path ../repo --command npm run lint"])}async run(e){const t="string"==typeof e.basePath&&e.basePath.trim().length>0?e.basePath.trim():process.cwd(),o="string"==typeof e.command?e.command.trim():"";if(0===o.length)throw Error("run-all requires a command to execute");const s=st(t);for(const e of s){const s=N.join(t,e);if(x.existsSync(s))try{E(o,{cwd:s,env:process.env,stdio:"inherit"})}catch{process.exit(1)}}}}const yt={public:{type:"boolean",default:!1},private:{type:"boolean",default:!1},gitToken:{type:"string",default:".token"},npmToken:{type:"string",default:".npmtoken"},gitUser:{type:"string",default:void 0},allowFromBranch:{type:"boolean",default:!1},tag:{type:"string",default:void 0},message:{type:"string",default:void 0}};class St extends ye{constructor(){super("TagReleaseCommand",yt)}async ensureReleaseBranch(e=!1){if(e)return;const t=E("git rev-parse --abbrev-ref HEAD",{cwd:process.cwd(),encoding:"utf8"}).trim();if("master"!==t&&"main"!==t)throw Error("release must be run from 'master' or 'main' branch. Current branch: "+t)}async prepareTag(e){return(e=(""+(e||"")).trim()).length>0?e:(E("git tag --sort=-taggerdate | head -n 5",{cwd:process.cwd(),stdio:"inherit"}),F.insistForText("tag","What should be the new tag? (accepts v*.*.*[-...])",e=>!!e.toString().match(/^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9a-zA-Z-]+)?$/)))}async prepareMessage(e){return(e=(""+(e||"")).trim()).length>0?e:F.insistForText("message","Tag Message",e=>!!e&&e.toString().length>0)}hasToken(e){try{return x.statSync(N.join(process.cwd(),e)).size>0}catch{return!1}}readToken(e){return x.readFileSync(N.join(process.cwd(),e),"utf8").trim()}help(){Ue(this.log,"tag-release","Prepare a release, create a git tag, push, and optionally publish to npm.","tag-release [options] [tag] [message]",[{flag:"--public",description:"Publish to the public npm registry",defaultValue:"false"},{flag:"--private",description:"Publish to the restricted npm registry",defaultValue:"false"},{flag:"--git-token <file>",description:"File containing the token used for authenticated git pushes",defaultValue:".token"},{flag:"--npm-token <file>",description:"File containing the token used for npm publish",defaultValue:".npmtoken"},{flag:"--git-user <name>",description:"Git user name embedded in authenticated pushes"},{flag:"--allow-from-branch",description:"Skip the master/main branch guard",defaultValue:"false"},{flag:"--tag <version>",description:"Release tag to create"},{flag:"--message <text>",description:"Release message to use"},{flag:"-h, --help",description:"Show this help text and exit"}],["If tag or message are omitted, the command prompts interactively.","The command uses .token for git pushes and .npmtoken for npm publish unless overridden."],['tag-release --public --tag v1.2.3 --message "Release 1.2.3"',"tag-release --private --allow-from-branch --tag v1.2.3"])}async run(e){await this.ensureReleaseBranch(!0===e.allowFromBranch);const t=!0===e.private?"private":"public",o=await this.prepareTag(e.tag),s=await this.prepareMessage(e.message),a=""+(e.gitToken||".token"),r=""+(e.npmToken||".npmtoken"),n="string"==typeof e.gitUser&&e.gitUser.trim().length>0?e.gitUser.trim():E("git config user.name",{cwd:process.cwd(),encoding:"utf8"}).trim();E("npm run prepare-release",{cwd:process.cwd(),stdio:"inherit"}),E("git status --porcelain",{cwd:process.cwd(),encoding:"utf8"}).trim().length>0&&(E("git add .",{cwd:process.cwd(),stdio:"inherit"}),E(`git commit -m "${o} - ${s} - after release preparation"`,{cwd:process.cwd(),stdio:"inherit"})),E(`npm version "${o}" -m "${s}"`,{cwd:process.cwd(),stdio:"inherit"});const i=E("git remote get-url origin",{cwd:process.cwd(),encoding:"utf8"}).trim();if(this.hasToken(a)){const e=E("git rev-parse --abbrev-ref HEAD",{cwd:process.cwd(),encoding:"utf8"});let t="";try{t=E("git rev-parse --abbrev-ref --symbolic-full-name '@{u}'",{cwd:process.cwd(),encoding:"utf8"})}catch{t=""}const o=this.readToken(a);if(E(`git push "https://${n}:${o}@${i.replace(/^https:\/\//,"")}" --follow-tags`,{cwd:process.cwd(),stdio:"inherit"}),t.trim().length>0)try{E(`git branch --set-upstream-to="${t.trim()}" "${e.trim()}"`,{cwd:process.cwd(),stdio:"inherit"})}catch{}}else E("git push --follow-tags",{cwd:process.cwd(),stdio:"inherit"});const c="public"===t?"public":"restricted";if(s.endsWith(O)&&this.hasToken(r)){const e=this.readToken(r);E(`NPM_TOKEN="${e}" npm publish --access "${c}"`,{cwd:process.cwd(),stdio:"inherit"})}}}class bt extends L{constructor(e,t,o,s="g"){super(e,t);try{this.regexp="string"==typeof o?RegExp(o,s):o}catch(e){throw Error("Invalid regular expression: "+e)}}test(e){let t;this.regexp.lastIndex=0;try{t=this.regexp.exec(e)}catch(e){return}return t}testAndResolve(e){const t=this.test(e);t&&this.resolve(t[0])}testAndReject(e){const t=this.test(e);t&&this.reject(t[0])}data(e){super.data(e),this.testAndResolve(e+"")}error(e){super.error(e),this.testAndReject(e+"")}}const wt="##VERSION##",vt="##COMMIT##",Tt="##FULL_VERSION##",kt="##PACKAGE##";export{U as AbortCode,Pe as BuildScripts,vt as COMMIT,ye as Command,I as DefaultCommandOptions,A as DefaultCommandValues,R as Encoding,Tt as FULL_VERSION,Se as HttpClient,nt as ModulesCommand,O as NoCIFLag,ht as NpmLinkCommand,ft as NpmTokenCommand,kt as PACKAGE_NAME,Te as PerformanceRunner,bt as RegexpOutputWriter,Qe as ReleaseChainCommand,et as ReleaseChainDispatchCommand,He as ReleaseChainRunner,_e as ReleaseScript,mt as RunAllCommand,M as SemVersion,j as SemVersionRegex,B as SetupScriptKey,L as StandardOutputWriter,St as TagReleaseCommand,P as Tokens,F as UserInput,wt as VERSION,V as chainAbortController,Z as copyFile,be as defaultCanvasOptions,Q as deletePath,We as dispatchReleaseChainWorkflow,X as getAllFiles,se as getDependencies,de as getFileSizeZipped,ee as getPackage,De as getPackageDependencies,oe as getPackageVersion,me as getSlogan,ce as installDependencies,ne as installIfNotAvailable,ge as listFolder,he as listNodeModulesPackages,_ as lockify,le as normalizeImport,Ce as packageToGlobal,ke as parseList,K as patchFile,pe as printBanner,ie as pushToGit,q as readFile,st as readGitModules,at as readGitModulesDeep,Y as renameFile,J as runCommand,Je as runReleaseChain,te as setPackageAttribute,H as spawnCommand,re as updateDependencies,z as writeFile};
|
|
2
2
|
//# sourceMappingURL=utils.js.map
|