hyperbook 0.8.8 → 0.8.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -140,4 +140,4 @@ var o=i(4300);var a=o.Buffer;function copyProps(t,r){for(var i in t){r[i]=t[i]}}
140
140
  * @license [MIT]{@link https://github.com/archiverjs/node-zip-stream/blob/master/LICENSE}
141
141
  * @copyright (c) 2014 Chris Talkington, contributors.
142
142
  */
143
- var o=i(3837).inherits;var a=i(2096).ZipArchiveOutputStream;var l=i(2096).ZipArchiveEntry;var u=i(1246);var c=t.exports=function(t){if(!(this instanceof c)){return new c(t)}t=this.options=t||{};t.zlib=t.zlib||{};a.call(this,t);if(typeof t.level==="number"&&t.level>=0){t.zlib.level=t.level;delete t.level}if(!t.forceZip64&&typeof t.zlib.level==="number"&&t.zlib.level===0){t.store=true}t.namePrependSlash=t.namePrependSlash||false;if(t.comment&&t.comment.length>0){this.setComment(t.comment)}};o(c,a);c.prototype._normalizeFileData=function(t){t=u.defaults(t,{type:"file",name:null,namePrependSlash:this.options.namePrependSlash,linkname:null,date:null,mode:null,store:this.options.store,comment:""});var r=t.type==="directory";var i=t.type==="symlink";if(t.name){t.name=u.sanitizePath(t.name);if(!i&&t.name.slice(-1)==="/"){r=true;t.type="directory"}else if(r){t.name+="/"}}if(r||i){t.store=true}t.date=u.dateify(t.date);return t};c.prototype.entry=function(t,r,i){if(typeof i!=="function"){i=this._emitErrorCallback.bind(this)}r=this._normalizeFileData(r);if(r.type!=="file"&&r.type!=="directory"&&r.type!=="symlink"){i(new Error(r.type+" entries not currently supported"));return}if(typeof r.name!=="string"||r.name.length===0){i(new Error("entry name must be a non-empty string value"));return}if(r.type==="symlink"&&typeof r.linkname!=="string"){i(new Error("entry linkname must be a non-empty string value when type equals symlink"));return}var o=new l(r.name);o.setTime(r.date,this.options.forceLocalTime);if(r.namePrependSlash){o.setName(r.name,true)}if(r.store){o.setMethod(0)}if(r.comment.length>0){o.setComment(r.comment)}if(r.type==="symlink"&&typeof r.mode!=="number"){r.mode=40960}if(typeof r.mode==="number"){if(r.type==="symlink"){r.mode|=40960}o.setUnixMode(r.mode)}if(r.type==="symlink"&&typeof r.linkname==="string"){t=Buffer.from(r.linkname)}return a.prototype.entry.call(this,o,t,i)};c.prototype.finalize=function(){this.finish()}},371:(t,r,i)=>{"use strict";i.r(r);const o=10;const wrapAnsi16=(t=0)=>r=>`[${r+t}m`;const wrapAnsi256=(t=0)=>r=>`[${38+t};5;${r}m`;const wrapAnsi16m=(t=0)=>(r,i,o)=>`[${38+t};2;${r};${i};${o}m`;const a={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};const l=Object.keys(a.modifier);const u=Object.keys(a.color);const c=Object.keys(a.bgColor);const h=[...u,...c];function assembleStyles(){const t=new Map;for(const[r,i]of Object.entries(a)){for(const[r,o]of Object.entries(i)){a[r]={open:`[${o[0]}m`,close:`[${o[1]}m`};i[r]=a[r];t.set(o[0],o[1])}Object.defineProperty(a,r,{value:i,enumerable:false})}Object.defineProperty(a,"codes",{value:t,enumerable:false});a.color.close="";a.bgColor.close="";a.color.ansi=wrapAnsi16();a.color.ansi256=wrapAnsi256();a.color.ansi16m=wrapAnsi16m();a.bgColor.ansi=wrapAnsi16(o);a.bgColor.ansi256=wrapAnsi256(o);a.bgColor.ansi16m=wrapAnsi16m(o);Object.defineProperties(a,{rgbToAnsi256:{value(t,r,i){if(t===r&&r===i){if(t<8){return 16}if(t>248){return 231}return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(i/255*5)},enumerable:false},hexToRgb:{value(t){const r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r){return[0,0,0]}let[i]=r;if(i.length===3){i=[...i].map((t=>t+t)).join("")}const o=Number.parseInt(i,16);return[o>>16&255,o>>8&255,o&255]},enumerable:false},hexToAnsi256:{value:t=>a.rgbToAnsi256(...a.hexToRgb(t)),enumerable:false},ansi256ToAnsi:{value(t){if(t<8){return 30+t}if(t<16){return 90+(t-8)}let r;let i;let o;if(t>=232){r=((t-232)*10+8)/255;i=r;o=r}else{t-=16;const a=t%36;r=Math.floor(t/36)/5;i=Math.floor(a/6)/5;o=a%6/5}const a=Math.max(r,i,o)*2;if(a===0){return 30}let l=30+(Math.round(o)<<2|Math.round(i)<<1|Math.round(r));if(a===2){l+=60}return l},enumerable:false},rgbToAnsi:{value:(t,r,i)=>a.ansi256ToAnsi(a.rgbToAnsi256(t,r,i)),enumerable:false},hexToAnsi:{value:t=>a.ansi256ToAnsi(a.hexToAnsi256(t)),enumerable:false}});return a}const p=assembleStyles();const d=p;const m=require("node:process");const g=require("node:os");const y=require("node:tty");function hasFlag(t,r=m.argv){const i=t.startsWith("-")?"":t.length===1?"-":"--";const o=r.indexOf(i+t);const a=r.indexOf("--");return o!==-1&&(a===-1||o<a)}const{env:v}=m;let b;if(hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")||hasFlag("color=never")){b=0}else if(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always")){b=1}function envForceColor(){if("FORCE_COLOR"in v){if(v.FORCE_COLOR==="true"){return 1}if(v.FORCE_COLOR==="false"){return 0}return v.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(v.FORCE_COLOR,10),3)}}function translateLevel(t){if(t===0){return false}return{level:t,hasBasic:true,has256:t>=2,has16m:t>=3}}function _supportsColor(t,{streamIsTTY:r,sniffFlags:i=true}={}){const o=envForceColor();if(o!==undefined){b=o}const a=i?b:o;if(a===0){return 0}if(i){if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor")){return 3}if(hasFlag("color=256")){return 2}}if(t&&!r&&a===undefined){return 0}const l=a||0;if(v.TERM==="dumb"){return l}if(m.platform==="win32"){const t=g.release().split(".");if(Number(t[0])>=10&&Number(t[2])>=10586){return Number(t[2])>=14931?3:2}return 1}if("CI"in v){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some((t=>t in v))||v.CI_NAME==="codeship"){return 1}return l}if("TEAMCITY_VERSION"in v){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(v.TEAMCITY_VERSION)?1:0}if("TF_BUILD"in v&&"AGENT_NAME"in v){return 1}if(v.COLORTERM==="truecolor"){return 3}if("TERM_PROGRAM"in v){const t=Number.parseInt((v.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(v.TERM_PROGRAM){case"iTerm.app":return t>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(v.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(v.TERM)){return 1}if("COLORTERM"in v){return 1}return l}function createSupportsColor(t,r={}){const i=_supportsColor(t,{streamIsTTY:t&&t.isTTY,...r});return translateLevel(i)}const _={stdout:createSupportsColor({isTTY:y.isatty(1)}),stderr:createSupportsColor({isTTY:y.isatty(2)})};const w=_;function stringReplaceAll(t,r,i){let o=t.indexOf(r);if(o===-1){return t}const a=r.length;let l=0;let u="";do{u+=t.slice(l,o)+r+i;l=o+a;o=t.indexOf(r,l)}while(o!==-1);u+=t.slice(l);return u}function stringEncaseCRLFWithFirstIndex(t,r,i,o){let a=0;let l="";do{const u=t[o-1]==="\r";l+=t.slice(a,u?o-1:o)+r+(u?"\r\n":"\n")+i;a=o+1;o=t.indexOf("\n",a)}while(o!==-1);l+=t.slice(a);return l}const{stdout:S,stderr:E}=w;const x=Symbol("GENERATOR");const A=Symbol("STYLER");const O=Symbol("IS_EMPTY");const k=["ansi","ansi","ansi256","ansi16m"];const R=Object.create(null);const applyOptions=(t,r={})=>{if(r.level&&!(Number.isInteger(r.level)&&r.level>=0&&r.level<=3)){throw new Error("The `level` option should be an integer from 0 to 3")}const i=S?S.level:0;t.level=r.level===undefined?i:r.level};class Chalk{constructor(t){return chalkFactory(t)}}const chalkFactory=t=>{const chalk=(...t)=>t.join(" ");applyOptions(chalk,t);Object.setPrototypeOf(chalk,createChalk.prototype);return chalk};function createChalk(t){return chalkFactory(t)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(const[t,r]of Object.entries(d)){R[t]={get(){const i=createBuilder(this,createStyler(r.open,r.close,this[A]),this[O]);Object.defineProperty(this,t,{value:i});return i}}}R.visible={get(){const t=createBuilder(this,this[A],true);Object.defineProperty(this,"visible",{value:t});return t}};const getModelAnsi=(t,r,i,...o)=>{if(t==="rgb"){if(r==="ansi16m"){return d[i].ansi16m(...o)}if(r==="ansi256"){return d[i].ansi256(d.rgbToAnsi256(...o))}return d[i].ansi(d.rgbToAnsi(...o))}if(t==="hex"){return getModelAnsi("rgb",r,i,...d.hexToRgb(...o))}return d[i][t](...o)};const T=["rgb","hex","ansi256"];for(const t of T){R[t]={get(){const{level:r}=this;return function(...i){const o=createStyler(getModelAnsi(t,k[r],"color",...i),d.color.close,this[A]);return createBuilder(this,o,this[O])}}};const r="bg"+t[0].toUpperCase()+t.slice(1);R[r]={get(){const{level:r}=this;return function(...i){const o=createStyler(getModelAnsi(t,k[r],"bgColor",...i),d.bgColor.close,this[A]);return createBuilder(this,o,this[O])}}}}const C=Object.defineProperties((()=>{}),{...R,level:{enumerable:true,get(){return this[x].level},set(t){this[x].level=t}}});const createStyler=(t,r,i)=>{let o;let a;if(i===undefined){o=t;a=r}else{o=i.openAll+t;a=r+i.closeAll}return{open:t,close:r,openAll:o,closeAll:a,parent:i}};const createBuilder=(t,r,i)=>{const builder=(...t)=>applyStyle(builder,t.length===1?""+t[0]:t.join(" "));Object.setPrototypeOf(builder,C);builder[x]=t;builder[A]=r;builder[O]=i;return builder};const applyStyle=(t,r)=>{if(t.level<=0||!r){return t[O]?"":r}let i=t[A];if(i===undefined){return r}const{openAll:o,closeAll:a}=i;if(r.includes("")){while(i!==undefined){r=stringReplaceAll(r,i.close,i.open);i=i.parent}}const l=r.indexOf("\n");if(l!==-1){r=stringEncaseCRLFWithFirstIndex(r,a,o,l)}return o+r+a};Object.defineProperties(createChalk.prototype,R);const P=createChalk();const I=createChalk({level:E?E.level:0});const L=P;var M=i(345);const{program:N,createCommand:D,createArgument:j,createOption:$,CommanderError:B,InvalidArgumentError:H,InvalidOptionArgumentError:W,Command:G,Argument:U,Option:V,Help:q}=M;var z=i(5656);var Y=i.n(z);var K=i(1017);var Q=i.n(K);var Z=i(7147);var X=i.n(Z);function isSetup(t){const r="Could not find .hyperbook folder. Be sure to run `hyperbook setup`.";try{const r=X().statSync(Q().join(t,".hyperbook"));if(!r.isDirectory()){throw Error()}}catch(t){console.log(L.red(`Could not find .hyperbook folder at ${r}. Be sure to run \`hyperbook setup\`.`));return false}if(process.env.HYPERBOOK_LOCAL_DEV){return true}const i=Q().join(t,".hyperbook","node_modules",".bin","next");try{X().statSync(i)}catch(t){console.log(L.red(`Could not find next binary at ${i}. Be sure to run \`hyperbook setup\`.`));return false}return true}var J=i(2202);var ee=i.n(J);async function archiveFolder(t,r,i){return new Promise(((o,a)=>{const l=Q().join(t,"public","archives");if(!X().existsSync(l)){X().mkdirSync(l,{recursive:true})}const u=Q().join(l,r+".zip");const c=X().createWriteStream(u);const h=ee()("zip",{zlib:{level:9}});h.on("finish",(()=>{console.log(`${L.green(`[${i}]`)} Archive ${r} zipped.`);o()}));h.on("error",(t=>{throw t}));h.pipe(c);h.directory(Q().join(t,"archives",r),false);h.finalize()}))}async function runArchive(t,r){const i=isSetup(t);if(!i){throw new Error("no setup")}return new Promise(((i,o)=>{if(!X().existsSync(Q().join(t,"archives"))){console.log(`${L.blue(`[${r}]`)} No archives found.`);i()}else{console.log(`${L.blue(`[${r}]`)} Zipping archives.`);const a=X().readdirSync(Q().join(t,"archives"),{withFileTypes:true}).filter((t=>t.isDirectory()));Promise.all(a.map((i=>archiveFolder(t,i.name,r)))).then((()=>{i()})).catch((()=>{o()}))}}))}var te=i(4488);var re=i.n(te);var ne=i(4521);var ie=i.n(ne);async function readHyperbook(t){return new Promise(((r,i)=>{X().readFile(Q().join(t,"hyperbook.json"),((t,o)=>{if(t){console.log(L.red("Could not find 'hyperbook.json'. Make sure you are in the right directory."));i()}else{const t=JSON.parse(o.toString());r(t)}}))}))}const se=require("fs/promises");var oe=i.n(se);var ae=i(659);const le=require("node:path");const ue=require("node:url");const ce=require("node:fs");class Node{value;next;constructor(t){this.value=t}}class yocto_queue_Queue{#e;#t;#r;constructor(){this.clear()}enqueue(t){const r=new Node(t);if(this.#e){this.#t.next=r;this.#t=r}else{this.#e=r;this.#t=r}this.#r++}dequeue(){const t=this.#e;if(!t){return}this.#e=this.#e.next;this.#r--;return t.value}clear(){this.#e=undefined;this.#t=undefined;this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let t=this.#e;while(t){yield t.value;t=t.next}}}function p_limit_pLimit(t){if(!((Number.isInteger(t)||t===Number.POSITIVE_INFINITY)&&t>0)){throw new TypeError("Expected `concurrency` to be a number from 1 and up")}const r=new Queue;let i=0;const next=()=>{i--;if(r.size>0){r.dequeue()()}};const run=async(t,r,o)=>{i++;const a=(async()=>t(...o))();r(a);try{await a}catch{}next()};const enqueue=(o,a,l)=>{r.enqueue(run.bind(undefined,o,a,l));(async()=>{await Promise.resolve();if(i<t&&r.size>0){r.dequeue()()}})()};const generator=(t,...r)=>new Promise((i=>{enqueue(t,i,r)}));Object.defineProperties(generator,{activeCount:{get:()=>i},pendingCount:{get:()=>r.size},clearQueue:{value:()=>{r.clear()}}});return generator}class EndError extends Error{constructor(t){super();this.value=t}}const testElement=async(t,r)=>r(await t);const finder=async t=>{const r=await Promise.all(t);if(r[1]===true){throw new EndError(r[0])}return false};async function p_locate_pLocate(t,r,{concurrency:i=Number.POSITIVE_INFINITY,preserveOrder:o=true}={}){const a=pLimit(i);const l=[...t].map((t=>[t,a(testElement,t,r)]));const u=pLimit(o?1:Number.POSITIVE_INFINITY);try{await Promise.all(l.map((t=>u(finder,t))))}catch(t){if(t instanceof EndError){return t.value}throw t}}const fe={directory:"isDirectory",file:"isFile"};function checkType(t){if(Object.hasOwnProperty.call(fe,t)){return}throw new Error(`Invalid type specified: ${t}`)}const matchType=(t,r)=>r[fe[t]]();const toPath=t=>t instanceof URL?fileURLToPath(t):t;async function locate_path_locatePath(t,{cwd:r=process.cwd(),type:i="file",allowSymlinks:o=true,concurrency:a,preserveOrder:l}={}){checkType(i);r=toPath(r);const u=o?fsPromises.stat:fsPromises.lstat;return pLocate(t,(async t=>{try{const o=await u(path.resolve(r,t));return matchType(i,o)}catch{return false}}),{concurrency:a,preserveOrder:l})}function locate_path_locatePathSync(t,{cwd:r=process.cwd(),type:i="file",allowSymlinks:o=true}={}){checkType(i);r=toPath(r);const a=o?fs.statSync:fs.lstatSync;for(const o of t){try{const t=a(path.resolve(r,o));if(matchType(i,t)){return o}}catch{}}}async function pathExists(t){try{await fsPromises.access(t);return true}catch{return false}}function pathExistsSync(t){try{fs.accessSync(t);return true}catch{return false}}const find_up_toPath=t=>t instanceof URL?fileURLToPath(t):t;const he=Symbol("findUpStop");async function findUpMultiple(t,r={}){let i=path.resolve(find_up_toPath(r.cwd)||"");const{root:o}=path.parse(i);const a=path.resolve(i,r.stopAt||o);const l=r.limit||Number.POSITIVE_INFINITY;const u=[t].flat();const runMatcher=async r=>{if(typeof t!=="function"){return locatePath(u,r)}const i=await t(r.cwd);if(typeof i==="string"){return locatePath([i],r)}return i};const c=[];while(true){const t=await runMatcher({...r,cwd:i});if(t===he){break}if(t){c.push(path.resolve(i,t))}if(i===a||c.length>=l){break}i=path.dirname(i)}return c}function findUpMultipleSync(t,r={}){let i=path.resolve(find_up_toPath(r.cwd)||"");const{root:o}=path.parse(i);const a=r.stopAt||o;const l=r.limit||Number.POSITIVE_INFINITY;const u=[t].flat();const runMatcher=r=>{if(typeof t!=="function"){return locatePathSync(u,r)}const i=t(r.cwd);if(typeof i==="string"){return locatePathSync([i],r)}return i};const c=[];while(true){const t=runMatcher({...r,cwd:i});if(t===he){break}if(t){c.push(path.resolve(i,t))}if(i===a||c.length>=l){break}i=path.dirname(i)}return c}async function find_up_findUp(t,r={}){const i=await findUpMultiple(t,{...r,limit:1});return i[0]}function findUpSync(t,r={}){const i=findUpMultipleSync(t,{...r,limit:1});return i[0]}var pe=Object.defineProperty;var de=Object.defineProperties;var me=Object.getOwnPropertyDescriptors;var ge=Object.getOwnPropertySymbols;var ye=Object.prototype.hasOwnProperty;var ve=Object.prototype.propertyIsEnumerable;var __defNormalProp=(t,r,i)=>r in t?pe(t,r,{enumerable:true,configurable:true,writable:true,value:i}):t[r]=i;var __spreadValues=(t,r)=>{for(var i in r||={})if(ye.call(r,i))__defNormalProp(t,i,r[i]);if(ge)for(var i of ge(r)){if(ve.call(r,i))__defNormalProp(t,i,r[i])}return t};var __spreadProps=(t,r)=>de(t,me(r));var __async=(t,r,i)=>new Promise(((o,a)=>{var fulfilled=t=>{try{step(i.next(t))}catch(t){a(t)}};var rejected=t=>{try{step(i.throw(t))}catch(t){a(t)}};var step=t=>t.done?o(t.value):Promise.resolve(t.value).then(fulfilled,rejected);step((i=i.apply(t,r)).next())}));var listFiles=(t,r="",i=true)=>__async(void 0,null,(function*(){const o=yield fs.readdir(path.join(t,r));return Promise.all(o.flatMap((o=>__async(void 0,null,(function*(){const a=yield fs.stat(path.join(t,r,o));if(a.isDirectory()){return listFiles(t,path.join(r,o),i)}else if(o.endsWith(".md")){if(i){return[path.join(t,r,o)]}else{return[path.join(r,o)]}}return[]}))))).then((t=>t.flat()))}));var readBook=(t,r=true)=>__async(void 0,null,(function*(){return listFiles(path.join(t,"book"),"",r)}));var readGlossary=(t,r=true)=>__async(void 0,null,(function*(){return listFiles(path.join(t,"glossary"),"",r)}));var makeGlossary=t=>__async(void 0,null,(function*(){const r=yield readGlossary(t);const i={};for(const o of r){const{content:r,data:a}=yield readFile(o);let l=path.basename(o,".md");if(a.name){l=a.name}else{console.log(`\n${chalk.yellow(`warn `)}- Glossary page ${o} does not specify a name. Defaulting to the filename ${l}.`)}const u=l[0].toUpperCase();if(!i[u]){i[u]=[]}const c=path.relative(t,o).replace(/\.md$/,"").split("/");i[u].push({name:l,href:"/"+c.join("/")})}return i}));var listPagesForTerm=(t,r)=>__async(void 0,null,(function*(){const i=yield readBook(t);const o=[];for(const a of i){const{content:i,data:l}=yield readFile(a);const u=new RegExp(`:t\\[.*\\]\\{#${r}(..*)?\\}|:t\\[${r}\\]`);const c=i.match(u);if(c&&!l.hide&&l.name){const r=path.relative(path.join(t,"book"),a).replace(/\.md$/,"").split("/");const i=r[r.length-1]==="index";if(i){r.pop()}o.push(__spreadProps(__spreadValues({},l),{href:"/"+r.join("/")}))}}return o}));var readFile=t=>__async(void 0,null,(function*(){const r=yield fs.readFile(t).catch((()=>fs.readFile(t+".md").catch((()=>fs.readFile(path.join(t,"index.md"))))));const{content:i,data:o}=matter(r);return{content:i,data:o}}));var index_esm_readHyperbook=t=>__async(void 0,null,(function*(){return se.readFile(K.join(t,"hyperbook.json")).then((t=>t.toString())).then(JSON.parse)}));var readHyperlibrary=t=>__async(void 0,null,(function*(){return se.readFile(K.join(t,"hyperlibrary.json")).then((t=>t.toString())).then(JSON.parse)}));var findHyperbook=t=>__async(void 0,null,(function*(){return findUp("hyperbook.json",{cwd:t}).then((t=>{if(!t){throw new Error("Could not find hyperbook.json")}return fs.readFile(t)})).then((t=>JSON.parse(t.toString())))}));var findHyperbookRoot=t=>__async(void 0,null,(function*(){return findUp("hyperbook.json",{cwd:t}).then((t=>{if(!t){throw new Error("Could not find hyperbook.json")}return path.parse(t).dir}))}));var readProject=(t,r)=>__async(void 0,null,(function*(){var i,o,a,l;if(r==null?void 0:r.src){t=K.join(t,r.src)}const u=yield index_esm_readHyperbook(t).catch((()=>null));if(u){return{type:"book",src:t,basePath:(i=r==null?void 0:r.basePath)!=null?i:u.basePath,name:(o=r==null?void 0:r.name)!=null?o:u.name,icon:r==null?void 0:r.icon}}const c=yield readHyperlibrary(t).catch((()=>null));if(c){return{type:"library",src:t,basePath:(a=r==null?void 0:r.basePath)!=null?a:c.basePath,name:(l=r==null?void 0:r.name)!=null?l:c.name,projects:yield Promise.all(c.library.map((i=>{var o,a;return readProject(t,__spreadProps(__spreadValues({},i),{basePath:K.join((a=(o=r==null?void 0:r.basePath)!=null?o:c.basePath)!=null?a:"",i.basePath)}))}))),icon:r==null?void 0:r.icon}}console.log(`${L.red("Error")} - Missing book or library for path ${t}.`);throw Error(`Missing book or library for path ${t}`)}));var getProjectName=(t,r)=>{let i="";if(typeof t.name==="string"){i=t.name}else{if(r){i=t.name[r]||""}else{i=Object.values(t.name)[0]}if(!i){console.log(L.red(`You need to provide a name for language ${r} in ${t.src}`));throw Error("")}}return i};var makeLinkForHyperproject=(t,...r)=>__async(void 0,[t,...r],(function*(t,r="en",i={}){var o,a,l,u,c,h;const p=getProjectName(t,r);if(t.type==="library"){return{label:p,links:yield Promise.all(t.projects.map((t=>makeLinkForHyperproject(t,r,i)))),icon:t.icon}}else{let r=(o=t.basePath)!=null?o:"/";if(!r.startsWith("/")){r="/"+r}if((a=i.href)==null?void 0:a.useSrc){r=t.src}if((l=i.href)==null?void 0:l.relative){r=K.relative(i.href.relative,r)}if((u=i.href)==null?void 0:u.prepend){r=K.join(...i.href.prepend,r)}if((c=i.href)==null?void 0:c.append){r=K.join(r,...i.href.append)}if((h=i.href)==null?void 0:h.protocol){if(r.startsWith("/")){r=r.slice(0,-1)}r=i.href.protocol+r}if(r.length>1&&r.endsWith("/")){r=r.slice(0,-1)}return{label:p,href:r,icon:t.icon}}}));var makeNavigationForHyperbook=(t,r="/")=>__async(void 0,null,(function*(){const i=yield index_esm_readHyperbook(t);const getSectionsAndPages=function(r){return __async(this,arguments,(function*(r,o=[]){const a=yield fs.readdir(r);let l=[];let u=[];for(const c of a){let a=path.join(r,c);let h=null;if(i.repo){h=i.repo+"/"+path.relative(t,a)}const p=yield fs.stat(a);if(p.isDirectory()){const{pages:r,sections:i}=yield getSectionsAndPages(a,o);const{content:l,data:c}=yield readFile(a);const p=__spreadProps(__spreadValues({},c),{href:"/"+path.relative(path.join(t,"book"),a),isEmpty:l.trim()==="",pages:r,sections:i});if(h){p.repo=h+"/index.md"}u.push(p)}else{const{data:r}=yield readFile(a);if(a.endsWith(".md")){a=a.substring(0,a.length-3);if(path.relative(path.join(t,"book"),a)==="index"){a=a.substring(0,a.length-5)}if(!a.endsWith("index")){const i=__spreadProps(__spreadValues({},r),{href:"/"+path.relative(path.join(t,"book"),a)});if(h){i.repo=h}l.push(i)}}}}l=l.sort(((t,r)=>t.name>r.name?1:-1));l=l.sort(((t,r)=>{const i=t.index!==void 0?t.index:9999;const o=r.index!==void 0?r.index:9999;return i-o}));u=u.sort(((t,r)=>t.name>r.name?1:-1));u=u.sort(((t,r)=>{const i=t.index!==void 0?t.index:9999;const o=r.index!==void 0?r.index:9999;return i-o}));return{pages:l,sections:u}}))};const getPageList=(t,r)=>{let i=[...r];for(const r of t){i=[...i,r,...getPageList(r.sections,r.pages)]}return i};const{sections:o,pages:a}=yield getSectionsAndPages(path.join(t,"book"));let l=getPageList(o,a);let u=l.findIndex((t=>t.href===r));const c=l[u]||null;l=l.filter((t=>!t.isEmpty&&!t.hide));u=l.findIndex((t=>t.href===r));const h=l[u+1]||null;const p=l[u-1]||null;return{next:h,current:c,previous:p,sections:o,pages:a}}));async function makeDir(t,r={recursive:true}){await X().promises.mkdir(t,r)}var be=i(4700);var _e=i.n(be);function makeEnv(){let t=process.env.NODE_PATH;let r=process.env.PATH;if(process.env.HYPERBOOK_LOCAL_DEV){t=Q().join(__dirname,"..","..","..","platforms","web","node_modules");r=Q().join(__dirname,"..","..","..","platforms","web","node_modules",".bin")+":"+r}const i={NODE_PATH:t,PATH:r};return i}async function runBuildProject(t,r,i){const o=getProjectName(t);if(t.type==="book"){console.log(`${L.blue(`[${o}]`)} Building Book.`);await runBuild(t.src,r,t.basePath,o,i)}else{if(!i){i=t.src;_e().sync(Q().join(i,".hyperbook","out"))}console.log(`${L.blue(`[${o}]`)} Building Library.`);for(const o of t.projects){await runBuildProject(o,r,i)}}}async function runBuild(t,r,i,o,a){const l=isSetup(t);if(!l){throw new Error("no setup")}await runArchive(t,o);const u=await readHyperbook(t);if(!i&&(u===null||u===void 0?void 0:u.basePath)){i=u.basePath}if(i&&!i.startsWith("/")){i="/"+i}if(i&&i.endsWith("/")){i=i.slice(0,-1)}X().writeFileSync(Q().join(t,".hyperbook","next.config.js"),`\nmodule.exports = {\n ${i?`basePath: '${i}',`:""}\n typescript: {\n ignoreBuildErrors: true,\n }\n}\n `);const c=await readHyperbook(t);let h=undefined;if(r.type==="library"){h=await makeLinkForHyperproject(r,c.language)}if(h){if(!c.links){c.links=[h]}else{c.links.push(h)}}c.basePath=i;X().cpSync(Q().join(t,"hyperbook.json"),Q().join(t,".hyperbook","hyperbook.json"),{force:true});X().writeFileSync(Q().join(t,".hyperbook","hyperbook.json"),JSON.stringify(c,null,2));return new Promise(((r,l)=>{var u;const c="npm";const h=["run","next:build"];const p=makeEnv();const d=re()(c,h,{stdio:"pipe",cwd:Q().join(t,".hyperbook"),env:{...process.env,...p,ADBLOCK:"1",DISABLE_OPENCOLLECTIVE:"1"}});const m=`${L.blue(`[${o}]`)} Exporting HTML files`;let g=0;const y=setInterval((()=>{if(!process.env.CI){ie().clearLine(process.stdout,0);ie().cursorTo(process.stdout,0);process.stdout.write(m+".".repeat(g));g=(g+1)%5}}),500);if(process.env.CI){process.stdout.write(m+".\n")}(u=d.stderr)===null||u===void 0?void 0:u.on("data",(t=>{if(!String(t).startsWith("warn")){console.log(`${L.red(`[${o}]`)} `+t)}}));d.on("close",(u=>{clearInterval(y);if(u!==0){process.stdout.write("\n");l({command:`${c} ${h.join(" ")}`});return}else{ie().clearLine(process.stdout,0);ie().cursorTo(process.stdout,0);const u=Q().join(t,".hyperbook","out");if(!a){process.stdout.write(`${L.green(`[${o}]`)} Export successful. Files written to ${u}.\n`);r()}else{const t=Q().join(a,".hyperbook","out",i||"");makeDir(t).then((()=>{X().cpSync(u,t,{recursive:true,force:true});process.stdout.write(`${L.green(`[${o}]`)} Export successful. Files written to ${t}.\n`);r()})).catch((t=>{process.stdout.write("\n");console.error(t);l()}))}}}))}))}async function runDev(){const t=process.cwd();const r=isSetup(t);if(!r){throw new Error("no setup")}return new Promise(((r,i)=>{const o="npm";const a=["run","next:dev"];const l=makeEnv();const u=re()(o,a,{stdio:"inherit",cwd:Q().join(t,".hyperbook"),env:{...process.env,...l,ADBLOCK:"1",DISABLE_OPENCOLLECTIVE:"1"}});u.on("close",(t=>{if(t!==0){i({command:`${o} ${a.join(" ")}`});return}r()}))}))}var we=i(2081);function getPkgManager(){try{const t=process.env.npm_config_user_agent;if(t){if(t.startsWith("yarn")){return"yarn"}else if(t.startsWith("pnpm")){return"pnpm"}}try{(0,we.execSync)("yarn --version",{stdio:"ignore"});return"yarn"}catch{(0,we.execSync)("pnpm --version",{stdio:"ignore"});return"pnpm"}}catch{return"npm"}}var Se=i(2037);var Ee=i.n(Se);const xe=require("node:events");function indentString(t,r=1,i={}){const{indent:o=" ",includeEmptyLines:a=false}=i;if(typeof t!=="string"){throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof t}\``)}if(typeof r!=="number"){throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof r}\``)}if(r<0){throw new RangeError(`Expected \`count\` to be at least 0, got \`${r}\``)}if(typeof o!=="string"){throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof o}\``)}if(r===0){return t}const l=a?/^/gm:/^(?!\s*$)/gm;return t.replace(l,o.repeat(r))}function escapeStringRegexp(t){if(typeof t!=="string"){throw new TypeError("Expected a string")}return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}const Ae=/\s+at.*[(\s](.*)\)?/;const Oe=/^(?:(?:(?:node|node:[\w/]+|(?:(?:node:)?internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)(?:\.js)?:\d+:\d+)|native)/;const ke=typeof Se.homedir==="undefined"?"":Se.homedir().replace(/\\/g,"/");function cleanStack(t,{pretty:r=false,basePath:i}={}){const o=i&&new RegExp(`(at | \\()${escapeStringRegexp(i.replace(/\\/g,"/"))}`,"g");if(typeof t!=="string"){return undefined}return t.replace(/\\/g,"/").split("\n").filter((t=>{const r=t.match(Ae);if(r===null||!r[1]){return true}const i=r[1];if(i.includes(".app/Contents/Resources/electron.asar")||i.includes(".app/Contents/Resources/default_app.asar")){return false}return!Oe.test(i)})).filter((t=>t.trim()!=="")).map((t=>{if(o){t=t.replace(o,"$1")}if(r){t=t.replace(Ae,((t,r)=>t.replace(r,r.replace(ke,"~"))))}return t})).join("\n")}const cleanInternalStack=t=>t.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g,"");class AggregateError extends Error{#n;name="AggregateError";constructor(t){if(!Array.isArray(t)){throw new TypeError(`Expected input to be an Array, got ${typeof t}`)}t=t.map((t=>{if(t instanceof Error){return t}if(t!==null&&typeof t==="object"){return Object.assign(new Error(t.message),t)}return new Error(t)}));let r=t.map((t=>typeof t.stack==="string"?cleanInternalStack(cleanStack(t.stack)):String(t))).join("\n");r="\n"+indentString(r,4);super(r);this.#n=t}get errors(){return this.#n.slice()}}async function pMap(t,r,{concurrency:i=Number.POSITIVE_INFINITY,stopOnError:o=true}={}){return new Promise(((a,l)=>{if(t[Symbol.iterator]===undefined&&t[Symbol.asyncIterator]===undefined){throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof t})`)}if(typeof r!=="function"){throw new TypeError("Mapper function is required")}if(!((Number.isSafeInteger(i)||i===Number.POSITIVE_INFINITY)&&i>=1)){throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${i}\` (${typeof i})`)}const u=[];const c=[];const h=new Map;let p=false;let d=false;let m=false;let g=0;let y=0;const v=t[Symbol.iterator]===undefined?t[Symbol.asyncIterator]():t[Symbol.iterator]();const reject=t=>{p=true;d=true;l(t)};const next=async()=>{if(d){return}const t=await v.next();const i=y;y++;if(t.done){m=true;if(g===0&&!d){if(!o&&c.length>0){reject(new AggregateError(c));return}d=true;if(!h.size){a(u);return}const t=[];for(const[r,i]of u.entries()){if(h.get(r)===Re){continue}t.push(i)}a(t)}return}g++;(async()=>{try{const o=await t.value;if(d){return}const a=await r(o,i);if(a===Re){h.set(i,a)}u[i]=a;g--;await next()}catch(t){if(o){reject(t)}else{c.push(t);g--;try{await next()}catch(t){reject(t)}}}})()};(async()=>{for(let t=0;t<i;t++){try{await next()}catch(t){reject(t);break}if(m||p){break}}})()}))}const Re=Symbol("skip");function arrify(t){if(t===null||t===undefined){return[]}if(Array.isArray(t)){return t}if(typeof t==="string"){return[t]}if(typeof t[Symbol.iterator]==="function"){return[...t]}return[t]}var Te=i(8174);class AbortError extends Error{constructor(t){super();this.name="AbortError";this.message=t}}const getDOMException=t=>globalThis.DOMException===undefined?new AbortError(t):new DOMException(t);const getAbortedReason=t=>{const r=t.reason===undefined?getDOMException("This operation was aborted."):t.reason;return r instanceof Error?r:getDOMException(r)};async function p_map_pMap(t,r,{concurrency:i=Number.POSITIVE_INFINITY,stopOnError:o=true,signal:a}={}){return new Promise(((l,u)=>{if(t[Symbol.iterator]===undefined&&t[Symbol.asyncIterator]===undefined){throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof t})`)}if(typeof r!=="function"){throw new TypeError("Mapper function is required")}if(!((Number.isSafeInteger(i)||i===Number.POSITIVE_INFINITY)&&i>=1)){throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${i}\` (${typeof i})`)}const c=[];const h=[];const p=new Map;let d=false;let m=false;let g=false;let y=0;let v=0;const b=t[Symbol.iterator]===undefined?t[Symbol.asyncIterator]():t[Symbol.iterator]();const reject=t=>{d=true;m=true;u(t)};if(a){if(a.aborted){reject(getAbortedReason(a))}a.addEventListener("abort",(()=>{reject(getAbortedReason(a))}))}const next=async()=>{if(m){return}const t=await b.next();const i=v;v++;if(t.done){g=true;if(y===0&&!m){if(!o&&h.length>0){reject(new AggregateError(h));return}m=true;if(p.size===0){l(c);return}const t=[];for(const[r,i]of c.entries()){if(p.get(r)===Ce){continue}t.push(i)}l(t)}return}y++;(async()=>{try{const o=await t.value;if(m){return}const a=await r(o,i);if(a===Ce){p.set(i,a)}c[i]=a;y--;await next()}catch(t){if(o){reject(t)}else{h.push(t);y--;try{await next()}catch(t){reject(t)}}}})()};(async()=>{for(let t=0;t<i;t++){try{await next()}catch(t){reject(t);break}if(g||d){break}}})()}))}const Ce=Symbol("skip");async function pFilter(t,r,i){const o=await p_map_pMap(t,((t,i)=>Promise.all([r(t,i),t])),i);return o.filter((t=>Boolean(t[0]))).map((t=>t[1]))}var Pe=i(9117);var Ie=i(2153);var Le=i(3286);var Me=i(7993);function slash(t){const r=/^\\\\\?\\/.test(t);const i=/[^\u0000-\u0080]+/.test(t);if(r||i){return t}return t.replace(/\\/g,"/")}const Ne=require("node:stream");const utilities_toPath=t=>t instanceof URL?(0,ue.fileURLToPath)(t):t;class FilterStream extends Ne.Transform{constructor(t){super({objectMode:true,transform(r,i,o){o(undefined,t(r)?r:undefined)}})}}const isNegativePattern=t=>t[0]==="!";const De={ignore:["**/node_modules","**/flow-typed","**/coverage","**/.git"],absolute:true,dot:true};const je="**/.gitignore";const applyBaseToPattern=(t,r)=>isNegativePattern(t)?"!"+le.posix.join(r,t.slice(1)):le.posix.join(r,t);const parseIgnoreFile=(t,r)=>{const i=slash(le.relative(r,le.dirname(t.filePath)));return t.content.split(/\r?\n/).filter((t=>t&&!t.startsWith("#"))).map((t=>applyBaseToPattern(t,i)))};const toRelativePath=(t,r)=>{r=slash(r);if(le.isAbsolute(t)){if(slash(t).startsWith(r)){return le.relative(r,t)}throw new Error(`Path ${t} is not in cwd ${r}`)}return t};const getIsIgnoredPredicate=(t,r)=>{const i=t.flatMap((t=>parseIgnoreFile(t,r)));const o=Me().add(i);return t=>{t=utilities_toPath(t);t=toRelativePath(t,r);return o.ignores(slash(t))}};const normalizeOptions=(t={})=>({cwd:utilities_toPath(t.cwd)||m.cwd()});const isIgnoredByIgnoreFiles=async(t,r)=>{const{cwd:i}=normalizeOptions(r);const o=await Ie(t,{cwd:i,...De});const a=await Promise.all(o.map((async t=>({filePath:t,content:await ce.promises.readFile(t,"utf8")}))));return getIsIgnoredPredicate(a,i)};const isIgnoredByIgnoreFilesSync=(t,r)=>{const{cwd:i}=normalizeOptions(r);const o=Ie.sync(t,{cwd:i,...De});const a=o.map((t=>({filePath:t,content:ce.readFileSync(t,"utf8")})));return getIsIgnoredPredicate(a,i)};const isGitIgnored=t=>isIgnoredByIgnoreFiles(je,t);const isGitIgnoredSync=t=>isIgnoredByIgnoreFilesSync(je,t);const assertPatternsInput=t=>{if(t.some((t=>typeof t!=="string"))){throw new TypeError("Patterns must be a string or an array of strings")}};const toPatternsArray=t=>{t=[...new Set([t].flat())];assertPatternsInput(t);return t};const checkCwdOption=t=>{if(!t.cwd){return}let r;try{r=ce.statSync(t.cwd)}catch{return}if(!r.isDirectory()){throw new Error("The `cwd` option must be a path to a directory")}};const globby_normalizeOptions=(t={})=>{t={ignore:[],expandDirectories:true,...t,cwd:utilities_toPath(t.cwd)};checkCwdOption(t);return t};const normalizeArguments=t=>async(r,i)=>t(toPatternsArray(r),globby_normalizeOptions(i));const normalizeArgumentsSync=t=>(r,i)=>t(toPatternsArray(r),globby_normalizeOptions(i));const getIgnoreFilesPatterns=t=>{const{ignoreFiles:r,gitignore:i}=t;const o=r?toPatternsArray(r):[];if(i){o.push(je)}return o};const getFilter=async t=>{const r=getIgnoreFilesPatterns(t);return createFilterFunction(r.length>0&&await isIgnoredByIgnoreFiles(r,{cwd:t.cwd}))};const getFilterSync=t=>{const r=getIgnoreFilesPatterns(t);return createFilterFunction(r.length>0&&isIgnoredByIgnoreFilesSync(r,{cwd:t.cwd}))};const createFilterFunction=t=>{const r=new Set;return i=>{const o=i.path||i;const a=le.normalize(o);const l=r.has(a)||t&&t(o);r.add(a);return!l}};const unionFastGlobResults=(t,r)=>t.flat().filter((t=>r(t)));const unionFastGlobStreams=(t,r)=>Pe(t).pipe(new FilterStream((t=>r(t))));const convertNegativePatterns=(t,r)=>{const i=[];while(t.length>0){const o=t.findIndex((t=>isNegativePattern(t)));if(o===-1){i.push({patterns:t,options:r});break}const a=t[o].slice(1);for(const t of i){t.options.ignore.push(a)}if(o!==0){i.push({patterns:t.slice(0,o),options:{...r,ignore:[...r.ignore,a]}})}t=t.slice(o+1)}return i};const getDirGlobOptions=(t,r)=>({...r?{cwd:r}:{},...Array.isArray(t)?{files:t}:t});const generateTasks=async(t,r)=>{const i=convertNegativePatterns(t,r);const{cwd:o,expandDirectories:a}=r;if(!a){return i}const l=getDirGlobOptions(a,o);const u=o?{cwd:o}:undefined;return Promise.all(i.map((async t=>{let{patterns:r,options:i}=t;[r,i.ignore]=await Promise.all([Le(r,l),Le(i.ignore,u)]);return{patterns:r,options:i}})))};const generateTasksSync=(t,r)=>{const i=convertNegativePatterns(t,r);const{cwd:o,expandDirectories:a}=r;if(!a){return i}const l=getDirGlobOptions(a,o);const u=o?{cwd:o}:undefined;return i.map((t=>{let{patterns:r,options:i}=t;r=Le.sync(r,l);i.ignore=Le.sync(i.ignore,u);return{patterns:r,options:i}}))};const Fe=normalizeArguments((async(t,r)=>{const[i,o]=await Promise.all([generateTasks(t,r),getFilter(r)]);const a=await Promise.all(i.map((t=>Ie(t.patterns,t.options))));return unionFastGlobResults(a,o)}));const $e=normalizeArgumentsSync(((t,r)=>{const i=generateTasksSync(t,r);const o=getFilterSync(r);const a=i.map((t=>Ie.sync(t.patterns,t.options)));return unionFastGlobResults(a,o)}));const Be=normalizeArgumentsSync(((t,r)=>{const i=generateTasksSync(t,r);const o=getFilterSync(r);const a=i.map((t=>Ie.stream(t.patterns,t.options)));return unionFastGlobStreams(a,o)}));const He=normalizeArgumentsSync(((t,r)=>t.some((t=>Ie.isDynamicPattern(t,r)))));const We=normalizeArguments(generateTasks);const Ge=normalizeArgumentsSync(generateTasksSync);var Ue=i(7971);var Ve=i(3134);class CpyError extends Ve{constructor(t,r){super(t,r);Object.assign(this,r);this.name="CpyError"}}const qe=["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^Desktop\\.ini$","@eaDir$"];const ze=new RegExp(qe.join("|"));function isJunk(t){return ze.test(t)}function isNotJunk(t){return!isJunk(t)}class GlobPattern{constructor(t,r,i){this.path=t;this.originalPath=t;this.destination=r;this.options=i;this.isDirectory=false;if(!He(t)&&ce.existsSync(t)&&ce.lstatSync(t).isDirectory()){this.path=[t,"**"].join("/");this.isDirectory=true}}get name(){return le.basename(this.originalPath)}get normalizedPath(){const t=this.originalPath.split("/");const r=t.findIndex((t=>t?He(t):false));const i=t.slice(0,r).join("/");if(i){return le.isAbsolute(i)?i:le.join(this.options.cwd,i)}return this.destination}hasMagic(){return He(this.options.flat?this.path:this.originalPath)}getMatches(){let t=$e(this.path,{...this.options,dot:true,absolute:true,onlyFiles:true});if(this.options.ignoreJunk){t=t.filter((t=>isNotJunk(le.basename(t))))}return t}}const Ye=(g.cpus().length||1)*2;const Ke={ignoreJunk:true,flat:false,cwd:m.cwd()};class Entry{constructor(t,r,i){this.path=t.split("/").join(le.sep);this.relativePath=r.split("/").join(le.sep);this.pattern=i;Object.freeze(this)}get name(){return le.basename(this.path)}get nameWithoutExtension(){return le.basename(this.path,le.extname(this.path))}get extension(){return le.extname(this.path).slice(1)}}const expandPatternsWithBraceExpansion=t=>t.flatMap((t=>Ue.braces(t,{expand:true,nodupes:true})));const preprocessDestinationPath=({entry:t,destination:r,options:i})=>{if(t.pattern.hasMagic()){if(i.flat){if(le.isAbsolute(r)){return le.join(r,t.name)}return le.join(i.cwd,r,t.name)}return le.join(r,le.relative(t.pattern.normalizedPath,t.path))}if(le.isAbsolute(r)){return le.join(r,t.name)}if(t.pattern.isDirectory&&le.relative(i.cwd,t.path).startsWith("..")){return le.join(i.cwd,r,le.basename(t.pattern.originalPath),le.relative(t.pattern.originalPath,t.path))}if(!t.pattern.isDirectory&&t.path===t.relativePath){return le.join(i.cwd,r,le.basename(t.pattern.originalPath),le.relative(t.pattern.originalPath,t.path))}if(!t.pattern.isDirectory&&i.flat){return le.join(i.cwd,r,le.basename(t.pattern.originalPath))}return le.join(i.cwd,r,le.relative(i.cwd,t.path))};const renameFile=(t,r)=>{const i=le.basename(t,le.extname(t));const o=le.extname(t);const a=le.dirname(t);if(typeof r==="string"){return le.join(a,r)}if(typeof r==="function"){return le.join(a,`${r(i)}${o}`)}return t};function cpy(t,r,{concurrency:i=Ye,...o}={}){const a=new Map;const l=new xe;o={...Ke,...o};const u=(async()=>{let u=[];let c=0;let h=0;let p=expandPatternsWithBraceExpansion(arrify(t)).map((t=>t.replace(/\\/g,"/")));const d=p.filter((t=>!t.startsWith("!")));const m=p.filter((t=>t.startsWith("!")));if(d.length===0||!r){throw new CpyError("`source` and `destination` required")}p=p.map((t=>new GlobPattern(t,r,{...o,ignore:m})));for(const t of p){let r=[];try{r=t.getMatches()}catch(r){throw new CpyError(`Cannot glob \`${t.originalPath}\`: ${r.message}`,r)}if(r.length===0&&!He(t.originalPath)&&!He(m)){throw new CpyError(`Cannot copy \`${t.originalPath}\`: the file doesn't exist`)}u=[...u,...r.map((r=>new Entry(r,le.relative(o.cwd,r),t)))]}if(o.filter!==undefined){u=await pFilter(u,o.filter,{concurrency:1024})}if(u.length===0){l.emit("progress",{totalFiles:0,percent:1,completedFiles:0,completedSize:0})}const fileProgressHandler=t=>{const r=a.get(t.sourcePath)||{writtenBytes:0,percent:0};if(r.writtenBytes!==t.writtenBytes||r.percent!==t.percent){h-=r.writtenBytes;h+=t.writtenBytes;if(t.percent===1&&r.percent!==1){c++}a.set(t.sourcePath,{writtenBytes:t.writtenBytes,percent:t.percent});l.emit("progress",{totalFiles:u.length,percent:c/u.length,completedFiles:c,completedSize:h})}};return pMap(u,(async t=>{const i=renameFile(preprocessDestinationPath({entry:t,destination:r,options:o}),o.rename);try{await Te(t.path,i,o).on("progress",fileProgressHandler)}catch(r){throw new CpyError(`Cannot copy from \`${t.relativePath}\` to \`${i}\`: ${r.message}`,r)}return i}),{concurrency:i})})();u.on=(...t)=>{l.on(...t);return u};return u}var Qe=i(5713);var Ze=i.n(Qe);function isFolderEmpty(t,r){const i=[".DS_Store",".git",".gitattributes",".gitignore",".gitlab-ci.yml",".hg",".hgcheck",".hgignore",".idea",".npmignore",".travis.yml","LICENSE","Thumbs.db","docs","mkdocs.yml","npm-debug.log","yarn-debug.log","yarn-error.log"];const o=X().readdirSync(t).filter((t=>!i.includes(t))).filter((t=>!/\.iml$/.test(t)));if(o.length>0){console.log(`The directory ${L.green(r)} contains files that could conflict:`);console.log();for(const r of o){try{const i=X().lstatSync(Q().join(t,r));if(i.isDirectory()){console.log(` ${L.blue(r)}/`)}else{console.log(` ${r}`)}}catch{console.log(` ${r}`)}}console.log();console.log("Either try using a new directory name, or remove the files listed above.");console.log();return false}return true}async function isWriteable(t){try{await X().promises.access(t,(X().constants||X()).W_OK);return true}catch(t){return false}}function isInGitRepository(){try{(0,we.execSync)("git rev-parse --is-inside-work-tree",{stdio:"ignore"});return true}catch(t){}return false}function isInMercurialRepository(){try{(0,we.execSync)("hg --cwd . root",{stdio:"ignore"});return true}catch(t){}return false}function tryGitInit(t){let r=false;try{(0,we.execSync)("git --version",{stdio:"ignore"});if(isInGitRepository()||isInMercurialRepository()){return false}(0,we.execSync)("git init",{stdio:"ignore"});r=true;(0,we.execSync)("git checkout -b main",{stdio:"ignore"});(0,we.execSync)("git add -A",{stdio:"ignore"});(0,we.execSync)('git commit -m "Initial commit from Hyperbook"',{stdio:"ignore"});return true}catch(i){if(r){try{_e().sync(Q().join(t,".git"))}catch(t){}}return false}}function install(t,r,{packageManager:i,isOnline:o,devDependencies:a}){const l=[];const u=[];return new Promise(((c,h)=>{let p;let d=i;const m=i==="yarn";if(r&&r.length){if(m){p=["add","--exact"];if(!o)p.push("--offline");p.push("--cwd",t);if(a)p.push("--dev");p.push(...r)}else{p=["install","--save-exact"];p.push(a?"--save-dev":"--save");p.push(...r)}}else{p=["install"];if(!o){console.log(L.yellow("You appear to be offline."));if(m){console.log(L.yellow("Falling back to the local Yarn cache."));console.log();p.push("--offline")}else{console.log()}}}if(m){p.push(...u)}else{p.push(...l)}const g=re()(d,p,{stdio:"inherit",cwd:t,env:{...process.env,ADBLOCK:"1",DISABLE_OPENCOLLECTIVE:"1"}});g.on("close",(t=>{if(t!==0){h({command:`${d} ${p.join(" ")}`});return}c()}))}))}const Xe=require("dns");var Je=i.n(Xe);var et=i(7310);var tt=i.n(et);function getProxy(){if(process.env.https_proxy){return process.env.https_proxy}try{const t=(0,we.execSync)("npm config get https-proxy").toString().trim();return t!=="null"?t:undefined}catch(t){return}}function getOnline(){return new Promise((t=>{Je().lookup("registry.yarnpkg.com",(r=>{if(!r){return t(true)}const i=getProxy();if(!i){return t(false)}const{hostname:o}=tt().parse(i);if(!o){return t(false)}Je().lookup(o,(r=>{t(r==null)}))}))}))}async function makeSymlink(t,r){const i=Ee().platform()=="win32"?"junction":null;return new Promise(((o,a)=>{X().symlink(t,r,i,(t=>{if(t){a()}else{o()}}))}))}async function runSetupProject(t,r){const o=getProjectName(t);console.log(`${L.blue(`[${o}]`)} Setup Project.`);const a=Q().join(t.src,".hyperbook");const l=Q().join((r===null||r===void 0?void 0:r.src)||"",".hyperbook");_e().sync(a);const u=i.ab+"templates";await makeDir(a);await cpy("default/.hyperbook/**",a,{cwd:i.ab+"templates",followSymbolicLinks:false});if(process.env.HYPERBOOK_LOCAL_DEV){const t=await oe().readFile(Q().join(__dirname,"..","..","..","platforms","web","package.json")).then((t=>JSON.parse(t.toString())));await oe().writeFile(Q().join(a,"package.json"),JSON.stringify({...t,name:`@docs/`+o.toLowerCase().replace(" ","-"),scripts:{"next:dev":"next-hyperbook-watch","next:build":"next build && next export"}},null,2))}else{if(!r){const t=await getOnline();await install(l,null,{packageManager:"npm",isOnline:t})}else{await makeSymlink(Q().join(l,"node_modules"),Q().join(a,"node_modules"))}}if(t.type==="library"){await makeSymlink(Q().join(t.src,"hyperlibrary.json"),Q().join(a,"hyperlibrary.json"));for(const i of t.projects){await runSetupProject(i,r)}return}await makeSymlink(Q().join(t.src,"archives"),Q().join(a,"archives"));await makeSymlink(Q().join(t.src,"book"),Q().join(a,"book"));await makeSymlink(Q().join(t.src,"glossary"),Q().join(a,"glossary"));await makeSymlink(Q().join(t.src,"public"),Q().join(a,"public"));await makeSymlink(Q().join(t.src,"hyperbook.json"),Q().join(a,"hyperbook.json"))}async function runNew({programName:t,bookPath:r}){if(typeof r==="string"){r=r.trim()}if(!r){const t=await Ze()({type:"text",name:"path",message:"What is your book named?",initial:"my-book"});if(typeof t.path==="string"){r=t.path.trim()}}if(!r){console.log();console.log("Please specify the book directory:");console.log(` ${L.cyan(t)} ${L.green("<book-directory>")}`);console.log();console.log("For example:");console.log(` ${L.cyan(t)} ${L.green("my-new-book")}`);console.log();console.log(`Run ${L.cyan(`${t} --help`)} to see all options.`);process.exit(1)}const o=Q().resolve(r);if(!await isWriteable(Q().dirname(o))){console.error("The book path is not writable, please check folder permissions and try again.");console.error("It is likely you do not have write permissions for this folder.");process.exit(1)}const a=Q().basename(o);await makeDir(o);if(!isFolderEmpty(o,a)){process.exit(1)}const l=process.cwd();console.log(`Creating a new hyperbook in ${L.green(o)}.`);console.log();process.chdir(o);const{description:u}=await Ze()({type:"text",name:"description",message:"What is your book about?",initial:""});const{author:c}=await Ze()({type:"text",name:"author",message:"Who is the author of the book?",initial:""});const{authorUrl:h}=await Ze()({type:"text",name:"authorUrl",message:"What is the link to the authors homepage?",initial:""});let{license:p}=await Ze()({type:"select",name:"license",message:"Pick a license for your book!",choices:[{title:"Creative Commons Zero (CC0)",value:"cc0"},{title:"Creative Commons Attribution (CC BY)",value:"cc-by"},{title:"Creative Commons Attribution-ShareAlike (CC BY-SA)",value:"cc-by-sa"},{title:"Creative Commons Attribution-NoDerivs (CC BY-ND)",value:"cc-by-nd"},{title:"Creative Commons Attribution-NonCommercial (CC BY-NC)",value:"cc-by-nc"},{title:"Creative Commons Attribution-NonCommercial-ShareAlike (CC BY-NC-SA)",value:"cc-by-nc-sa"},{title:"Creative Commons Attribution-NonCommercial-NoDervis (CC BY-NC-ND)",value:"cc-by-nc-nd"},{title:"Custom",value:"custom"}]});if(p==="custom"){const t=await Ze()({type:"text",name:"license",message:"Which custom license you want to use?"});p=t.license}const{language:d}=await Ze()({type:"text",name:"language",message:"In which language is your book written? Provide a short code, e.g.: en or de",initial:"en"});const m={name:a,version:"0.0.0",description:u,license:p,author:{name:c,url:h},language:d};X().writeFileSync(Q().join(o,"hyperbook.json"),JSON.stringify(m,null,2)+Ee().EOL);console.log();const g=i.ab+"templates";await cpy("default/**",o,{cwd:i.ab+"templates",rename:t=>{switch(t){case"gitignore":{return".".concat(t)}case"README-template.md":{return"README.md"}default:{return t}}}});await runSetupProject({type:"book",name:a,src:o});if(tryGitInit(o)){console.log("Initialized a git repository.");console.log()}let y;if(Q().join(l,a)===r){y=a}else{y=r}console.log(`${L.green("Success!")} Created ${a} at ${r}`);console.log("Inside that directory, you can run several commands:");console.log();console.log(L.cyan(` hyperbook dev`));console.log(" Starts the development server.");console.log();console.log(L.cyan(` hyperbook build`));console.log(" Builds the book for production.");console.log();console.log("We suggest that you begin by typing:");console.log();console.log(L.cyan(" cd"),y);console.log(` ${L.cyan(`hyperbook dev`)}`);console.log()}const rt=JSON.parse('{"name":"hyperbook","version":"0.8.8","author":"Mike Barkmin","homepage":"https://github.com/openpatch/hyperbook#readme","license":"MIT","bin":{"hyperbook":"./dist/index.js"},"files":["dist"],"publishConfig":{"access":"public"},"repository":{"type":"git","url":"git+https://github.com/openpatch/hyperbook.git","directory":"packages/hyperbook"},"bugs":{"url":"https://github.com/openpatch/hyperbook/issues"},"engines":{"node":">=12.22.0"},"scripts":{"version":"pnpm build","lint":"tsc --noEmit","dev":"ncc build ./index.ts -w -o dist/","build":"rimraf dist && ncc build ./index.ts -o ./dist/ -e \\"hyperbook-simple-template\\" --minify --no-cache --no-source-map-register && node ./postbuild.mjs"},"devDependencies":{"@pnpm/exportable-manifest":"4.0.2","@types/archiver":"5.3.1","@types/async-retry":"1.4.5","@types/cross-spawn":"6.0.2","@types/prompts":"2.4.1","@types/rimraf":"3.0.2","@types/tar":"6.1.3","@vercel/ncc":"0.34.0","archiver":"5.3.1","async-retry":"1.3.3","chalk":"5.1.2","commander":"9.4.1","cpy":"9.0.1","cross-spawn":"7.0.3","got":"12.5.3","prompts":"2.4.2","rimraf":"3.0.2","tar":"6.1.12","update-check":"1.5.4","@platforms/web":"workspace:*"},"dependencies":{"@hyperbook/fs":"workspace:*","@hyperbook/types":"workspace:*"}}');const nt=new G;nt.name(rt.name).version(rt.version).hook("preAction",(async()=>{await notifyUpdate()}));nt.command("new").description("create a new hyperbook").arguments("<book-directory>").usage(`${L.green("<book-directory>")}`).action((async t=>{await runNew({programName:nt.name(),bookPath:t}).catch((()=>process.exit(1)))}));nt.command("dev").description("start the development server for a hyperbook").action((async()=>{await runDev()}));nt.command("setup").description("downloads the latest version of the template of a hyperbook").action((async()=>{const t=await readProject(process.cwd()).catch((()=>{process.exit(1)}));await runSetupProject(t).catch((()=>{process.exit(1)}))}));nt.command("build").description("build a hyperbook").action((async()=>{const t=await readProject(process.cwd()).catch((()=>{process.exit(1)}));await runBuildProject(t,t).catch((()=>{process.exit(1)}))}));nt.command("archive").description("create archives from archives folder").action((async()=>{await runArchive(process.cwd()).catch((()=>process.exit(1)))}));nt.parseAsync(process.argv);const it=Y()(rt).catch((()=>null));async function notifyUpdate(){try{const t=await it;if(t===null||t===void 0?void 0:t.latest){const t=getPkgManager();console.log();console.log(L.yellow.bold("A new version of `hyperbook` is available!"));console.log("You can update by running: "+L.cyan(t==="yarn"?"yarn global add hyperbook":`${t} install --global hyperbook`));console.log()}process.exit()}catch{}}},9491:t=>{"use strict";t.exports=require("assert")},4300:t=>{"use strict";t.exports=require("buffer")},2081:t=>{"use strict";t.exports=require("child_process")},2057:t=>{"use strict";t.exports=require("constants")},2361:t=>{"use strict";t.exports=require("events")},7147:t=>{"use strict";t.exports=require("fs")},3685:t=>{"use strict";t.exports=require("http")},5687:t=>{"use strict";t.exports=require("https")},2037:t=>{"use strict";t.exports=require("os")},1017:t=>{"use strict";t.exports=require("path")},7282:t=>{"use strict";t.exports=require("process")},4521:t=>{"use strict";t.exports=require("readline")},2781:t=>{"use strict";t.exports=require("stream")},1576:t=>{"use strict";t.exports=require("string_decoder")},7310:t=>{"use strict";t.exports=require("url")},3837:t=>{"use strict";t.exports=require("util")},9796:t=>{"use strict";t.exports=require("zlib")},345:(t,r,i)=>{const{Argument:o}=i(4079);const{Command:a}=i(6505);const{CommanderError:l,InvalidArgumentError:u}=i(9027);const{Help:c}=i(9164);const{Option:h}=i(5205);r=t.exports=new a;r.program=r;r.Argument=o;r.Command=a;r.CommanderError=l;r.Help=c;r.InvalidArgumentError=u;r.InvalidOptionArgumentError=u;r.Option=h},4079:(t,r,i)=>{const{InvalidArgumentError:o}=i(9027);class Argument{constructor(t,r){this.description=r||"";this.variadic=false;this.parseArg=undefined;this.defaultValue=undefined;this.defaultValueDescription=undefined;this.argChoices=undefined;switch(t[0]){case"<":this.required=true;this._name=t.slice(1,-1);break;case"[":this.required=false;this._name=t.slice(1,-1);break;default:this.required=true;this._name=t;break}if(this._name.length>3&&this._name.slice(-3)==="..."){this.variadic=true;this._name=this._name.slice(0,-3)}}name(){return this._name}_concatValue(t,r){if(r===this.defaultValue||!Array.isArray(r)){return[t]}return r.concat(t)}default(t,r){this.defaultValue=t;this.defaultValueDescription=r;return this}argParser(t){this.parseArg=t;return this}choices(t){this.argChoices=t.slice();this.parseArg=(t,r)=>{if(!this.argChoices.includes(t)){throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,r)}return t};return this}argRequired(){this.required=true;return this}argOptional(){this.required=false;return this}}function humanReadableArgName(t){const r=t.name()+(t.variadic===true?"...":"");return t.required?"<"+r+">":"["+r+"]"}r.Argument=Argument;r.humanReadableArgName=humanReadableArgName},6505:(t,r,i)=>{const o=i(2361).EventEmitter;const a=i(2081);const l=i(1017);const u=i(7147);const c=i(7282);const{Argument:h,humanReadableArgName:p}=i(4079);const{CommanderError:d}=i(9027);const{Help:m}=i(9164);const{Option:g,splitOptionFlags:y,DualOptions:v}=i(5205);const{suggestSimilar:b}=i(211);class Command extends o{constructor(t){super();this.commands=[];this.options=[];this.parent=null;this._allowUnknownOption=false;this._allowExcessArguments=true;this._args=[];this.args=[];this.rawArgs=[];this.processedArgs=[];this._scriptPath=null;this._name=t||"";this._optionValues={};this._optionValueSources={};this._storeOptionsAsProperties=false;this._actionHandler=null;this._executableHandler=false;this._executableFile=null;this._executableDir=null;this._defaultCommandName=null;this._exitCallback=null;this._aliases=[];this._combineFlagAndOptionalValue=true;this._description="";this._summary="";this._argsDescription=undefined;this._enablePositionalOptions=false;this._passThroughOptions=false;this._lifeCycleHooks={};this._showHelpAfterError=false;this._showSuggestionAfterError=true;this._outputConfiguration={writeOut:t=>c.stdout.write(t),writeErr:t=>c.stderr.write(t),getOutHelpWidth:()=>c.stdout.isTTY?c.stdout.columns:undefined,getErrHelpWidth:()=>c.stderr.isTTY?c.stderr.columns:undefined,outputError:(t,r)=>r(t)};this._hidden=false;this._hasHelpOption=true;this._helpFlags="-h, --help";this._helpDescription="display help for command";this._helpShortFlag="-h";this._helpLongFlag="--help";this._addImplicitHelpCommand=undefined;this._helpCommandName="help";this._helpCommandnameAndArgs="help [command]";this._helpCommandDescription="display help for command";this._helpConfiguration={}}copyInheritedSettings(t){this._outputConfiguration=t._outputConfiguration;this._hasHelpOption=t._hasHelpOption;this._helpFlags=t._helpFlags;this._helpDescription=t._helpDescription;this._helpShortFlag=t._helpShortFlag;this._helpLongFlag=t._helpLongFlag;this._helpCommandName=t._helpCommandName;this._helpCommandnameAndArgs=t._helpCommandnameAndArgs;this._helpCommandDescription=t._helpCommandDescription;this._helpConfiguration=t._helpConfiguration;this._exitCallback=t._exitCallback;this._storeOptionsAsProperties=t._storeOptionsAsProperties;this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue;this._allowExcessArguments=t._allowExcessArguments;this._enablePositionalOptions=t._enablePositionalOptions;this._showHelpAfterError=t._showHelpAfterError;this._showSuggestionAfterError=t._showSuggestionAfterError;return this}command(t,r,i){let o=r;let a=i;if(typeof o==="object"&&o!==null){a=o;o=null}a=a||{};const[,l,u]=t.match(/([^ ]+) *(.*)/);const c=this.createCommand(l);if(o){c.description(o);c._executableHandler=true}if(a.isDefault)this._defaultCommandName=c._name;c._hidden=!!(a.noHelp||a.hidden);c._executableFile=a.executableFile||null;if(u)c.arguments(u);this.commands.push(c);c.parent=this;c.copyInheritedSettings(this);if(o)return this;return c}createCommand(t){return new Command(t)}createHelp(){return Object.assign(new m,this.configureHelp())}configureHelp(t){if(t===undefined)return this._helpConfiguration;this._helpConfiguration=t;return this}configureOutput(t){if(t===undefined)return this._outputConfiguration;Object.assign(this._outputConfiguration,t);return this}showHelpAfterError(t=true){if(typeof t!=="string")t=!!t;this._showHelpAfterError=t;return this}showSuggestionAfterError(t=true){this._showSuggestionAfterError=!!t;return this}addCommand(t,r){if(!t._name){throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`)}r=r||{};if(r.isDefault)this._defaultCommandName=t._name;if(r.noHelp||r.hidden)t._hidden=true;this.commands.push(t);t.parent=this;return this}createArgument(t,r){return new h(t,r)}argument(t,r,i,o){const a=this.createArgument(t,r);if(typeof i==="function"){a.default(o).argParser(i)}else{a.default(i)}this.addArgument(a);return this}arguments(t){t.split(/ +/).forEach((t=>{this.argument(t)}));return this}addArgument(t){const r=this._args.slice(-1)[0];if(r&&r.variadic){throw new Error(`only the last argument can be variadic '${r.name()}'`)}if(t.required&&t.defaultValue!==undefined&&t.parseArg===undefined){throw new Error(`a default value for a required argument is never used: '${t.name()}'`)}this._args.push(t);return this}addHelpCommand(t,r){if(t===false){this._addImplicitHelpCommand=false}else{this._addImplicitHelpCommand=true;if(typeof t==="string"){this._helpCommandName=t.split(" ")[0];this._helpCommandnameAndArgs=t}this._helpCommandDescription=r||this._helpCommandDescription}return this}_hasImplicitHelpCommand(){if(this._addImplicitHelpCommand===undefined){return this.commands.length&&!this._actionHandler&&!this._findCommand("help")}return this._addImplicitHelpCommand}hook(t,r){const i=["preSubcommand","preAction","postAction"];if(!i.includes(t)){throw new Error(`Unexpected value for event passed to hook : '${t}'.\nExpecting one of '${i.join("', '")}'`)}if(this._lifeCycleHooks[t]){this._lifeCycleHooks[t].push(r)}else{this._lifeCycleHooks[t]=[r]}return this}exitOverride(t){if(t){this._exitCallback=t}else{this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync"){throw t}else{}}}return this}_exit(t,r,i){if(this._exitCallback){this._exitCallback(new d(t,r,i))}c.exit(t)}action(t){const listener=r=>{const i=this._args.length;const o=r.slice(0,i);if(this._storeOptionsAsProperties){o[i]=this}else{o[i]=this.opts()}o.push(this);return t.apply(this,o)};this._actionHandler=listener;return this}createOption(t,r){return new g(t,r)}addOption(t){const r=t.name();const i=t.attributeName();if(t.negate){const r=t.long.replace(/^--no-/,"--");if(!this._findOption(r)){this.setOptionValueWithSource(i,t.defaultValue===undefined?true:t.defaultValue,"default")}}else if(t.defaultValue!==undefined){this.setOptionValueWithSource(i,t.defaultValue,"default")}this.options.push(t);const handleOptionValue=(r,o,a)=>{if(r==null&&t.presetArg!==undefined){r=t.presetArg}const l=this.getOptionValue(i);if(r!==null&&t.parseArg){try{r=t.parseArg(r,l)}catch(t){if(t.code==="commander.invalidArgument"){const r=`${o} ${t.message}`;this.error(r,{exitCode:t.exitCode,code:t.code})}throw t}}else if(r!==null&&t.variadic){r=t._concatValue(r,l)}if(r==null){if(t.negate){r=false}else if(t.isBoolean()||t.optional){r=true}else{r=""}}this.setOptionValueWithSource(i,r,a)};this.on("option:"+r,(r=>{const i=`error: option '${t.flags}' argument '${r}' is invalid.`;handleOptionValue(r,i,"cli")}));if(t.envVar){this.on("optionEnv:"+r,(r=>{const i=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;handleOptionValue(r,i,"env")}))}return this}_optionEx(t,r,i,o,a){if(typeof r==="object"&&r instanceof g){throw new Error("To add an Option object use addOption() instead of option() or requiredOption()")}const l=this.createOption(r,i);l.makeOptionMandatory(!!t.mandatory);if(typeof o==="function"){l.default(a).argParser(o)}else if(o instanceof RegExp){const t=o;o=(r,i)=>{const o=t.exec(r);return o?o[0]:i};l.default(a).argParser(o)}else{l.default(o)}return this.addOption(l)}option(t,r,i,o){return this._optionEx({},t,r,i,o)}requiredOption(t,r,i,o){return this._optionEx({mandatory:true},t,r,i,o)}combineFlagAndOptionalValue(t=true){this._combineFlagAndOptionalValue=!!t;return this}allowUnknownOption(t=true){this._allowUnknownOption=!!t;return this}allowExcessArguments(t=true){this._allowExcessArguments=!!t;return this}enablePositionalOptions(t=true){this._enablePositionalOptions=!!t;return this}passThroughOptions(t=true){this._passThroughOptions=!!t;if(!!this.parent&&t&&!this.parent._enablePositionalOptions){throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)")}return this}storeOptionsAsProperties(t=true){this._storeOptionsAsProperties=!!t;if(this.options.length){throw new Error("call .storeOptionsAsProperties() before adding options")}return this}getOptionValue(t){if(this._storeOptionsAsProperties){return this[t]}return this._optionValues[t]}setOptionValue(t,r){return this.setOptionValueWithSource(t,r,undefined)}setOptionValueWithSource(t,r,i){if(this._storeOptionsAsProperties){this[t]=r}else{this._optionValues[t]=r}this._optionValueSources[t]=i;return this}getOptionValueSource(t){return this._optionValueSources[t]}_prepareUserArgs(t,r){if(t!==undefined&&!Array.isArray(t)){throw new Error("first parameter to parse must be array or undefined")}r=r||{};if(t===undefined){t=c.argv;if(c.versions&&c.versions.electron){r.from="electron"}}this.rawArgs=t.slice();let i;switch(r.from){case undefined:case"node":this._scriptPath=t[1];i=t.slice(2);break;case"electron":if(c.defaultApp){this._scriptPath=t[1];i=t.slice(2)}else{i=t.slice(1)}break;case"user":i=t.slice(0);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);this._name=this._name||"program";return i}parse(t,r){const i=this._prepareUserArgs(t,r);this._parseCommand([],i);return this}async parseAsync(t,r){const i=this._prepareUserArgs(t,r);await this._parseCommand([],i);return this}_executeSubCommand(t,r){r=r.slice();let i=false;const o=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(t,r){const i=l.resolve(t,r);if(u.existsSync(i))return i;if(o.includes(l.extname(r)))return undefined;const a=o.find((t=>u.existsSync(`${i}${t}`)));if(a)return`${i}${a}`;return undefined}this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();let h=t._executableFile||`${this._name}-${t._name}`;let p=this._executableDir||"";if(this._scriptPath){let t;try{t=u.realpathSync(this._scriptPath)}catch(r){t=this._scriptPath}p=l.resolve(l.dirname(t),p)}if(p){let r=findFile(p,h);if(!r&&!t._executableFile&&this._scriptPath){const i=l.basename(this._scriptPath,l.extname(this._scriptPath));if(i!==this._name){r=findFile(p,`${i}-${t._name}`)}}h=r||h}i=o.includes(l.extname(h));let m;if(c.platform!=="win32"){if(i){r.unshift(h);r=incrementNodeInspectorPort(c.execArgv).concat(r);m=a.spawn(c.argv[0],r,{stdio:"inherit"})}else{m=a.spawn(h,r,{stdio:"inherit"})}}else{r.unshift(h);r=incrementNodeInspectorPort(c.execArgv).concat(r);m=a.spawn(c.execPath,r,{stdio:"inherit"})}if(!m.killed){const t=["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"];t.forEach((t=>{c.on(t,(()=>{if(m.killed===false&&m.exitCode===null){m.kill(t)}}))}))}const g=this._exitCallback;if(!g){m.on("close",c.exit.bind(c))}else{m.on("close",(()=>{g(new d(c.exitCode||0,"commander.executeSubCommandAsync","(close)"))}))}m.on("error",(r=>{if(r.code==="ENOENT"){const r=p?`searched for local subcommand relative to directory '${p}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory";const i=`'${h}' does not exist\n - if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${r}`;throw new Error(i)}else if(r.code==="EACCES"){throw new Error(`'${h}' not executable`)}if(!g){c.exit(1)}else{const t=new d(1,"commander.executeSubCommandAsync","(error)");t.nestedError=r;g(t)}}));this.runningCommand=m}_dispatchSubcommand(t,r,i){const o=this._findCommand(t);if(!o)this.help({error:true});let a;a=this._chainOrCallSubCommandHook(a,o,"preSubcommand");a=this._chainOrCall(a,(()=>{if(o._executableHandler){this._executeSubCommand(o,r.concat(i))}else{return o._parseCommand(r,i)}}));return a}_checkNumberOfArguments(){this._args.forEach(((t,r)=>{if(t.required&&this.args[r]==null){this.missingArgument(t.name())}}));if(this._args.length>0&&this._args[this._args.length-1].variadic){return}if(this.args.length>this._args.length){this._excessArguments(this.args)}}_processArguments(){const myParseArg=(t,r,i)=>{let o=r;if(r!==null&&t.parseArg){try{o=t.parseArg(r,i)}catch(i){if(i.code==="commander.invalidArgument"){const o=`error: command-argument value '${r}' is invalid for argument '${t.name()}'. ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}return o};this._checkNumberOfArguments();const t=[];this._args.forEach(((r,i)=>{let o=r.defaultValue;if(r.variadic){if(i<this.args.length){o=this.args.slice(i);if(r.parseArg){o=o.reduce(((t,i)=>myParseArg(r,i,t)),r.defaultValue)}}else if(o===undefined){o=[]}}else if(i<this.args.length){o=this.args[i];if(r.parseArg){o=myParseArg(r,o,r.defaultValue)}}t[i]=o}));this.processedArgs=t}_chainOrCall(t,r){if(t&&t.then&&typeof t.then==="function"){return t.then((()=>r()))}return r()}_chainOrCallHooks(t,r){let i=t;const o=[];getCommandAndParents(this).reverse().filter((t=>t._lifeCycleHooks[r]!==undefined)).forEach((t=>{t._lifeCycleHooks[r].forEach((r=>{o.push({hookedCommand:t,callback:r})}))}));if(r==="postAction"){o.reverse()}o.forEach((t=>{i=this._chainOrCall(i,(()=>t.callback(t.hookedCommand,this)))}));return i}_chainOrCallSubCommandHook(t,r,i){let o=t;if(this._lifeCycleHooks[i]!==undefined){this._lifeCycleHooks[i].forEach((t=>{o=this._chainOrCall(o,(()=>t(this,r)))}))}return o}_parseCommand(t,r){const i=this.parseOptions(r);this._parseOptionsEnv();this._parseOptionsImplied();t=t.concat(i.operands);r=i.unknown;this.args=t.concat(r);if(t&&this._findCommand(t[0])){return this._dispatchSubcommand(t[0],t.slice(1),r)}if(this._hasImplicitHelpCommand()&&t[0]===this._helpCommandName){if(t.length===1){this.help()}return this._dispatchSubcommand(t[1],[],[this._helpLongFlag])}if(this._defaultCommandName){outputHelpIfRequested(this,r);return this._dispatchSubcommand(this._defaultCommandName,t,r)}if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName){this.help({error:true})}outputHelpIfRequested(this,i.unknown);this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();const checkForUnknownOptions=()=>{if(i.unknown.length>0){this.unknownOption(i.unknown[0])}};const o=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions();this._processArguments();let i;i=this._chainOrCallHooks(i,"preAction");i=this._chainOrCall(i,(()=>this._actionHandler(this.processedArgs)));if(this.parent){i=this._chainOrCall(i,(()=>{this.parent.emit(o,t,r)}))}i=this._chainOrCallHooks(i,"postAction");return i}if(this.parent&&this.parent.listenerCount(o)){checkForUnknownOptions();this._processArguments();this.parent.emit(o,t,r)}else if(t.length){if(this._findCommand("*")){return this._dispatchSubcommand("*",t,r)}if(this.listenerCount("command:*")){this.emit("command:*",t,r)}else if(this.commands.length){this.unknownCommand()}else{checkForUnknownOptions();this._processArguments()}}else if(this.commands.length){checkForUnknownOptions();this.help({error:true})}else{checkForUnknownOptions();this._processArguments()}}_findCommand(t){if(!t)return undefined;return this.commands.find((r=>r._name===t||r._aliases.includes(t)))}_findOption(t){return this.options.find((r=>r.is(t)))}_checkForMissingMandatoryOptions(){for(let t=this;t;t=t.parent){t.options.forEach((r=>{if(r.mandatory&&t.getOptionValue(r.attributeName())===undefined){t.missingMandatoryOptionValue(r)}}))}}_checkForConflictingLocalOptions(){const t=this.options.filter((t=>{const r=t.attributeName();if(this.getOptionValue(r)===undefined){return false}return this.getOptionValueSource(r)!=="default"}));const r=t.filter((t=>t.conflictsWith.length>0));r.forEach((r=>{const i=t.find((t=>r.conflictsWith.includes(t.attributeName())));if(i){this._conflictingOption(r,i)}}))}_checkForConflictingOptions(){for(let t=this;t;t=t.parent){t._checkForConflictingLocalOptions()}}parseOptions(t){const r=[];const i=[];let o=r;const a=t.slice();function maybeOption(t){return t.length>1&&t[0]==="-"}let l=null;while(a.length){const t=a.shift();if(t==="--"){if(o===i)o.push(t);o.push(...a);break}if(l&&!maybeOption(t)){this.emit(`option:${l.name()}`,t);continue}l=null;if(maybeOption(t)){const r=this._findOption(t);if(r){if(r.required){const t=a.shift();if(t===undefined)this.optionMissingArgument(r);this.emit(`option:${r.name()}`,t)}else if(r.optional){let t=null;if(a.length>0&&!maybeOption(a[0])){t=a.shift()}this.emit(`option:${r.name()}`,t)}else{this.emit(`option:${r.name()}`)}l=r.variadic?r:null;continue}}if(t.length>2&&t[0]==="-"&&t[1]!=="-"){const r=this._findOption(`-${t[1]}`);if(r){if(r.required||r.optional&&this._combineFlagAndOptionalValue){this.emit(`option:${r.name()}`,t.slice(2))}else{this.emit(`option:${r.name()}`);a.unshift(`-${t.slice(2)}`)}continue}}if(/^--[^=]+=/.test(t)){const r=t.indexOf("=");const i=this._findOption(t.slice(0,r));if(i&&(i.required||i.optional)){this.emit(`option:${i.name()}`,t.slice(r+1));continue}}if(maybeOption(t)){o=i}if((this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&i.length===0){if(this._findCommand(t)){r.push(t);if(a.length>0)i.push(...a);break}else if(t===this._helpCommandName&&this._hasImplicitHelpCommand()){r.push(t);if(a.length>0)r.push(...a);break}else if(this._defaultCommandName){i.push(t);if(a.length>0)i.push(...a);break}}if(this._passThroughOptions){o.push(t);if(a.length>0)o.push(...a);break}o.push(t)}return{operands:r,unknown:i}}opts(){if(this._storeOptionsAsProperties){const t={};const r=this.options.length;for(let i=0;i<r;i++){const r=this.options[i].attributeName();t[r]=r===this._versionOptionName?this._version:this[r]}return t}return this._optionValues}optsWithGlobals(){return getCommandAndParents(this).reduce(((t,r)=>Object.assign(t,r.opts())),{})}error(t,r){this._outputConfiguration.outputError(`${t}\n`,this._outputConfiguration.writeErr);if(typeof this._showHelpAfterError==="string"){this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`)}else if(this._showHelpAfterError){this._outputConfiguration.writeErr("\n");this.outputHelp({error:true})}const i=r||{};const o=i.exitCode||1;const a=i.code||"commander.error";this._exit(o,a,t)}_parseOptionsEnv(){this.options.forEach((t=>{if(t.envVar&&t.envVar in c.env){const r=t.attributeName();if(this.getOptionValue(r)===undefined||["default","config","env"].includes(this.getOptionValueSource(r))){if(t.required||t.optional){this.emit(`optionEnv:${t.name()}`,c.env[t.envVar])}else{this.emit(`optionEnv:${t.name()}`)}}}}))}_parseOptionsImplied(){const t=new v(this.options);const hasCustomOptionValue=t=>this.getOptionValue(t)!==undefined&&!["default","implied"].includes(this.getOptionValueSource(t));this.options.filter((r=>r.implied!==undefined&&hasCustomOptionValue(r.attributeName())&&t.valueFromOption(this.getOptionValue(r.attributeName()),r))).forEach((t=>{Object.keys(t.implied).filter((t=>!hasCustomOptionValue(t))).forEach((r=>{this.setOptionValueWithSource(r,t.implied[r],"implied")}))}))}missingArgument(t){const r=`error: missing required argument '${t}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(t){const r=`error: option '${t.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){const r=`error: required option '${t.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,r){const findBestOptionFromValue=t=>{const r=t.attributeName();const i=this.getOptionValue(r);const o=this.options.find((t=>t.negate&&r===t.attributeName()));const a=this.options.find((t=>!t.negate&&r===t.attributeName()));if(o&&(o.presetArg===undefined&&i===false||o.presetArg!==undefined&&i===o.presetArg)){return o}return a||t};const getErrorMessage=t=>{const r=findBestOptionFromValue(t);const i=r.attributeName();const o=this.getOptionValueSource(i);if(o==="env"){return`environment variable '${r.envVar}'`}return`option '${r.flags}'`};const i=`error: ${getErrorMessage(t)} cannot be used with ${getErrorMessage(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let r="";if(t.startsWith("--")&&this._showSuggestionAfterError){let i=[];let o=this;do{const t=o.createHelp().visibleOptions(o).filter((t=>t.long)).map((t=>t.long));i=i.concat(t);o=o.parent}while(o&&!o._enablePositionalOptions);r=b(t,i)}const i=`error: unknown option '${t}'${r}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;const r=this._args.length;const i=r===1?"":"s";const o=this.parent?` for '${this.name()}'`:"";const a=`error: too many arguments${o}. Expected ${r} argument${i} but got ${t.length}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){const t=this.args[0];let r="";if(this._showSuggestionAfterError){const i=[];this.createHelp().visibleCommands(this).forEach((t=>{i.push(t.name());if(t.alias())i.push(t.alias())}));r=b(t,i)}const i=`error: unknown command '${t}'${r}`;this.error(i,{code:"commander.unknownCommand"})}version(t,r,i){if(t===undefined)return this._version;this._version=t;r=r||"-V, --version";i=i||"output the version number";const o=this.createOption(r,i);this._versionOptionName=o.attributeName();this.options.push(o);this.on("option:"+o.name(),(()=>{this._outputConfiguration.writeOut(`${t}\n`);this._exit(0,"commander.version",t)}));return this}description(t,r){if(t===undefined&&r===undefined)return this._description;this._description=t;if(r){this._argsDescription=r}return this}summary(t){if(t===undefined)return this._summary;this._summary=t;return this}alias(t){if(t===undefined)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler){r=this.commands[this.commands.length-1]}if(t===r._name)throw new Error("Command alias can't be the same as its name");r._aliases.push(t);return this}aliases(t){if(t===undefined)return this._aliases;t.forEach((t=>this.alias(t)));return this}usage(t){if(t===undefined){if(this._usage)return this._usage;const t=this._args.map((t=>p(t)));return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this._args.length?t:[]).join(" ")}this._usage=t;return this}name(t){if(t===undefined)return this._name;this._name=t;return this}nameFromFilename(t){this._name=l.basename(t,l.extname(t));return this}executableDir(t){if(t===undefined)return this._executableDir;this._executableDir=t;return this}helpInformation(t){const r=this.createHelp();if(r.helpWidth===undefined){r.helpWidth=t&&t.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()}return r.formatHelp(this,r)}_getHelpContext(t){t=t||{};const r={error:!!t.error};let i;if(r.error){i=t=>this._outputConfiguration.writeErr(t)}else{i=t=>this._outputConfiguration.writeOut(t)}r.write=t.write||i;r.command=this;return r}outputHelp(t){let r;if(typeof t==="function"){r=t;t=undefined}const i=this._getHelpContext(t);getCommandAndParents(this).reverse().forEach((t=>t.emit("beforeAllHelp",i)));this.emit("beforeHelp",i);let o=this.helpInformation(i);if(r){o=r(o);if(typeof o!=="string"&&!Buffer.isBuffer(o)){throw new Error("outputHelp callback must return a string or a Buffer")}}i.write(o);this.emit(this._helpLongFlag);this.emit("afterHelp",i);getCommandAndParents(this).forEach((t=>t.emit("afterAllHelp",i)))}helpOption(t,r){if(typeof t==="boolean"){this._hasHelpOption=t;return this}this._helpFlags=t||this._helpFlags;this._helpDescription=r||this._helpDescription;const i=y(this._helpFlags);this._helpShortFlag=i.shortFlag;this._helpLongFlag=i.longFlag;return this}help(t){this.outputHelp(t);let r=c.exitCode||0;if(r===0&&t&&typeof t!=="function"&&t.error){r=1}this._exit(r,"commander.help","(outputHelp)")}addHelpText(t,r){const i=["beforeAll","before","after","afterAll"];if(!i.includes(t)){throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${i.join("', '")}'`)}const o=`${t}Help`;this.on(o,(t=>{let i;if(typeof r==="function"){i=r({error:t.error,command:t.command})}else{i=r}if(i){t.write(`${i}\n`)}}));return this}}function outputHelpIfRequested(t,r){const i=t._hasHelpOption&&r.find((r=>r===t._helpLongFlag||r===t._helpShortFlag));if(i){t.outputHelp();t._exit(0,"commander.helpDisplayed","(outputHelp)")}}function incrementNodeInspectorPort(t){return t.map((t=>{if(!t.startsWith("--inspect")){return t}let r;let i="127.0.0.1";let o="9229";let a;if((a=t.match(/^(--inspect(-brk)?)$/))!==null){r=a[1]}else if((a=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null){r=a[1];if(/^\d+$/.test(a[3])){o=a[3]}else{i=a[3]}}else if((a=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null){r=a[1];i=a[3];o=a[4]}if(r&&o!=="0"){return`${r}=${i}:${parseInt(o)+1}`}return t}))}function getCommandAndParents(t){const r=[];for(let i=t;i;i=i.parent){r.push(i)}return r}r.Command=Command},9027:(t,r)=>{class CommanderError extends Error{constructor(t,r,i){super(i);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name;this.code=r;this.exitCode=t;this.nestedError=undefined}}class InvalidArgumentError extends CommanderError{constructor(t){super(1,"commander.invalidArgument",t);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name}}r.CommanderError=CommanderError;r.InvalidArgumentError=InvalidArgumentError},9164:(t,r,i)=>{const{humanReadableArgName:o}=i(4079);class Help{constructor(){this.helpWidth=undefined;this.sortSubcommands=false;this.sortOptions=false}visibleCommands(t){const r=t.commands.filter((t=>!t._hidden));if(t._hasImplicitHelpCommand()){const[,i,o]=t._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);const a=t.createCommand(i).helpOption(false);a.description(t._helpCommandDescription);if(o)a.arguments(o);r.push(a)}if(this.sortSubcommands){r.sort(((t,r)=>t.name().localeCompare(r.name())))}return r}visibleOptions(t){const r=t.options.filter((t=>!t.hidden));const i=t._hasHelpOption&&t._helpShortFlag&&!t._findOption(t._helpShortFlag);const o=t._hasHelpOption&&!t._findOption(t._helpLongFlag);if(i||o){let a;if(!i){a=t.createOption(t._helpLongFlag,t._helpDescription)}else if(!o){a=t.createOption(t._helpShortFlag,t._helpDescription)}else{a=t.createOption(t._helpFlags,t._helpDescription)}r.push(a)}if(this.sortOptions){const getSortKey=t=>t.short?t.short.replace(/^-/,""):t.long.replace(/^--/,"");r.sort(((t,r)=>getSortKey(t).localeCompare(getSortKey(r))))}return r}visibleArguments(t){if(t._argsDescription){t._args.forEach((r=>{r.description=r.description||t._argsDescription[r.name()]||""}))}if(t._args.find((t=>t.description))){return t._args}return[]}subcommandTerm(t){const r=t._args.map((t=>o(t))).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce(((t,i)=>Math.max(t,r.subcommandTerm(i).length)),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce(((t,i)=>Math.max(t,r.optionTerm(i).length)),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce(((t,i)=>Math.max(t,r.argumentTerm(i).length)),0)}commandUsage(t){let r=t._name;if(t._aliases[0]){r=r+"|"+t._aliases[0]}let i="";for(let r=t.parent;r;r=r.parent){i=r.name()+" "+i}return i+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){const r=[];if(t.argChoices){r.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){const i=t.required||t.optional||t.isBoolean()&&typeof t.defaultValue==="boolean";if(i){r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}}if(t.presetArg!==undefined&&t.optional){r.push(`preset: ${JSON.stringify(t.presetArg)}`)}if(t.envVar!==undefined){r.push(`env: ${t.envVar}`)}if(r.length>0){return`${t.description} (${r.join(", ")})`}return t.description}argumentDescription(t){const r=[];if(t.argChoices){r.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}if(r.length>0){const i=`(${r.join(", ")})`;if(t.description){return`${t.description} ${i}`}return i}return t.description}formatHelp(t,r){const i=r.padWidth(t,r);const o=r.helpWidth||80;const a=2;const l=2;function formatItem(t,u){if(u){const c=`${t.padEnd(i+l)}${u}`;return r.wrap(c,o-a,i+l)}return t}function formatList(t){return t.join("\n").replace(/^/gm," ".repeat(a))}let u=[`Usage: ${r.commandUsage(t)}`,""];const c=r.commandDescription(t);if(c.length>0){u=u.concat([c,""])}const h=r.visibleArguments(t).map((t=>formatItem(r.argumentTerm(t),r.argumentDescription(t))));if(h.length>0){u=u.concat(["Arguments:",formatList(h),""])}const p=r.visibleOptions(t).map((t=>formatItem(r.optionTerm(t),r.optionDescription(t))));if(p.length>0){u=u.concat(["Options:",formatList(p),""])}const d=r.visibleCommands(t).map((t=>formatItem(r.subcommandTerm(t),r.subcommandDescription(t))));if(d.length>0){u=u.concat(["Commands:",formatList(d),""])}return u.join("\n")}padWidth(t,r){return Math.max(r.longestOptionTermLength(t,r),r.longestSubcommandTermLength(t,r),r.longestArgumentTermLength(t,r))}wrap(t,r,i,o=40){if(t.match(/[\n]\s+/))return t;const a=r-i;if(a<o)return t;const l=t.slice(0,i);const u=t.slice(i);const c=" ".repeat(i);const h=new RegExp(".{1,"+(a-1)+"}([\\s​]|$)|[^\\s​]+?([\\s​]|$)","g");const p=u.match(h)||[];return l+p.map(((t,r)=>{if(t.slice(-1)==="\n"){t=t.slice(0,t.length-1)}return(r>0?c:"")+t.trimRight()})).join("\n")}}r.Help=Help},5205:(t,r,i)=>{const{InvalidArgumentError:o}=i(9027);class Option{constructor(t,r){this.flags=t;this.description=r||"";this.required=t.includes("<");this.optional=t.includes("[");this.variadic=/\w\.\.\.[>\]]$/.test(t);this.mandatory=false;const i=splitOptionFlags(t);this.short=i.shortFlag;this.long=i.longFlag;this.negate=false;if(this.long){this.negate=this.long.startsWith("--no-")}this.defaultValue=undefined;this.defaultValueDescription=undefined;this.presetArg=undefined;this.envVar=undefined;this.parseArg=undefined;this.hidden=false;this.argChoices=undefined;this.conflictsWith=[];this.implied=undefined}default(t,r){this.defaultValue=t;this.defaultValueDescription=r;return this}preset(t){this.presetArg=t;return this}conflicts(t){this.conflictsWith=this.conflictsWith.concat(t);return this}implies(t){this.implied=Object.assign(this.implied||{},t);return this}env(t){this.envVar=t;return this}argParser(t){this.parseArg=t;return this}makeOptionMandatory(t=true){this.mandatory=!!t;return this}hideHelp(t=true){this.hidden=!!t;return this}_concatValue(t,r){if(r===this.defaultValue||!Array.isArray(r)){return[t]}return r.concat(t)}choices(t){this.argChoices=t.slice();this.parseArg=(t,r)=>{if(!this.argChoices.includes(t)){throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,r)}return t};return this}name(){if(this.long){return this.long.replace(/^--/,"")}return this.short.replace(/^-/,"")}attributeName(){return camelcase(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class DualOptions{constructor(t){this.positiveOptions=new Map;this.negativeOptions=new Map;this.dualOptions=new Set;t.forEach((t=>{if(t.negate){this.negativeOptions.set(t.attributeName(),t)}else{this.positiveOptions.set(t.attributeName(),t)}}));this.negativeOptions.forEach(((t,r)=>{if(this.positiveOptions.has(r)){this.dualOptions.add(r)}}))}valueFromOption(t,r){const i=r.attributeName();if(!this.dualOptions.has(i))return true;const o=this.negativeOptions.get(i).presetArg;const a=o!==undefined?o:false;return r.negate===(a===t)}}function camelcase(t){return t.split("-").reduce(((t,r)=>t+r[0].toUpperCase()+r.slice(1)))}function splitOptionFlags(t){let r;let i;const o=t.split(/[ |,]+/);if(o.length>1&&!/^[[<]/.test(o[1]))r=o.shift();i=o.shift();if(!r&&/^-[^-]$/.test(i)){r=i;i=undefined}return{shortFlag:r,longFlag:i}}r.Option=Option;r.splitOptionFlags=splitOptionFlags;r.DualOptions=DualOptions},211:(t,r)=>{const i=3;function editDistance(t,r){if(Math.abs(t.length-r.length)>i)return Math.max(t.length,r.length);const o=[];for(let r=0;r<=t.length;r++){o[r]=[r]}for(let t=0;t<=r.length;t++){o[0][t]=t}for(let i=1;i<=r.length;i++){for(let a=1;a<=t.length;a++){let l=1;if(t[a-1]===r[i-1]){l=0}else{l=1}o[a][i]=Math.min(o[a-1][i]+1,o[a][i-1]+1,o[a-1][i-1]+l);if(a>1&&i>1&&t[a-1]===r[i-2]&&t[a-2]===r[i-1]){o[a][i]=Math.min(o[a][i],o[a-2][i-2]+1)}}}return o[t.length][r.length]}function suggestSimilar(t,r){if(!r||r.length===0)return"";r=Array.from(new Set(r));const o=t.startsWith("--");if(o){t=t.slice(2);r=r.map((t=>t.slice(2)))}let a=[];let l=i;const u=.4;r.forEach((r=>{if(r.length<=1)return;const i=editDistance(t,r);const o=Math.max(t.length,r.length);const c=(o-i)/o;if(c>u){if(i<l){l=i;a=[r]}else if(i===l){a.push(r)}}}));a.sort(((t,r)=>t.localeCompare(r)));if(o){a=a.map((t=>`--${t}`))}if(a.length>1){return`\n(Did you mean one of ${a.join(", ")}?)`}if(a.length===1){return`\n(Did you mean ${a[0]}?)`}return""}r.suggestSimilar=suggestSimilar}};var __webpack_module_cache__={};function __nccwpck_require__(t){var r=__webpack_module_cache__[t];if(r!==undefined){return r.exports}var i=__webpack_module_cache__[t]={exports:{}};var o=true;try{__webpack_modules__[t].call(i.exports,i,i.exports,__nccwpck_require__);o=false}finally{if(o)delete __webpack_module_cache__[t]}return i.exports}(()=>{__nccwpck_require__.n=t=>{var r=t&&t.__esModule?()=>t["default"]:()=>t;__nccwpck_require__.d(r,{a:r});return r}})();(()=>{__nccwpck_require__.d=(t,r)=>{for(var i in r){if(__nccwpck_require__.o(r,i)&&!__nccwpck_require__.o(t,i)){Object.defineProperty(t,i,{enumerable:true,get:r[i]})}}}})();(()=>{__nccwpck_require__.o=(t,r)=>Object.prototype.hasOwnProperty.call(t,r)})();(()=>{__nccwpck_require__.r=t=>{if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(t,"__esModule",{value:true})}})();if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(371);module.exports=__webpack_exports__})();
143
+ var o=i(3837).inherits;var a=i(2096).ZipArchiveOutputStream;var l=i(2096).ZipArchiveEntry;var u=i(1246);var c=t.exports=function(t){if(!(this instanceof c)){return new c(t)}t=this.options=t||{};t.zlib=t.zlib||{};a.call(this,t);if(typeof t.level==="number"&&t.level>=0){t.zlib.level=t.level;delete t.level}if(!t.forceZip64&&typeof t.zlib.level==="number"&&t.zlib.level===0){t.store=true}t.namePrependSlash=t.namePrependSlash||false;if(t.comment&&t.comment.length>0){this.setComment(t.comment)}};o(c,a);c.prototype._normalizeFileData=function(t){t=u.defaults(t,{type:"file",name:null,namePrependSlash:this.options.namePrependSlash,linkname:null,date:null,mode:null,store:this.options.store,comment:""});var r=t.type==="directory";var i=t.type==="symlink";if(t.name){t.name=u.sanitizePath(t.name);if(!i&&t.name.slice(-1)==="/"){r=true;t.type="directory"}else if(r){t.name+="/"}}if(r||i){t.store=true}t.date=u.dateify(t.date);return t};c.prototype.entry=function(t,r,i){if(typeof i!=="function"){i=this._emitErrorCallback.bind(this)}r=this._normalizeFileData(r);if(r.type!=="file"&&r.type!=="directory"&&r.type!=="symlink"){i(new Error(r.type+" entries not currently supported"));return}if(typeof r.name!=="string"||r.name.length===0){i(new Error("entry name must be a non-empty string value"));return}if(r.type==="symlink"&&typeof r.linkname!=="string"){i(new Error("entry linkname must be a non-empty string value when type equals symlink"));return}var o=new l(r.name);o.setTime(r.date,this.options.forceLocalTime);if(r.namePrependSlash){o.setName(r.name,true)}if(r.store){o.setMethod(0)}if(r.comment.length>0){o.setComment(r.comment)}if(r.type==="symlink"&&typeof r.mode!=="number"){r.mode=40960}if(typeof r.mode==="number"){if(r.type==="symlink"){r.mode|=40960}o.setUnixMode(r.mode)}if(r.type==="symlink"&&typeof r.linkname==="string"){t=Buffer.from(r.linkname)}return a.prototype.entry.call(this,o,t,i)};c.prototype.finalize=function(){this.finish()}},371:(t,r,i)=>{"use strict";i.r(r);const o=10;const wrapAnsi16=(t=0)=>r=>`[${r+t}m`;const wrapAnsi256=(t=0)=>r=>`[${38+t};5;${r}m`;const wrapAnsi16m=(t=0)=>(r,i,o)=>`[${38+t};2;${r};${i};${o}m`;const a={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};const l=Object.keys(a.modifier);const u=Object.keys(a.color);const c=Object.keys(a.bgColor);const h=[...u,...c];function assembleStyles(){const t=new Map;for(const[r,i]of Object.entries(a)){for(const[r,o]of Object.entries(i)){a[r]={open:`[${o[0]}m`,close:`[${o[1]}m`};i[r]=a[r];t.set(o[0],o[1])}Object.defineProperty(a,r,{value:i,enumerable:false})}Object.defineProperty(a,"codes",{value:t,enumerable:false});a.color.close="";a.bgColor.close="";a.color.ansi=wrapAnsi16();a.color.ansi256=wrapAnsi256();a.color.ansi16m=wrapAnsi16m();a.bgColor.ansi=wrapAnsi16(o);a.bgColor.ansi256=wrapAnsi256(o);a.bgColor.ansi16m=wrapAnsi16m(o);Object.defineProperties(a,{rgbToAnsi256:{value(t,r,i){if(t===r&&r===i){if(t<8){return 16}if(t>248){return 231}return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(i/255*5)},enumerable:false},hexToRgb:{value(t){const r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!r){return[0,0,0]}let[i]=r;if(i.length===3){i=[...i].map((t=>t+t)).join("")}const o=Number.parseInt(i,16);return[o>>16&255,o>>8&255,o&255]},enumerable:false},hexToAnsi256:{value:t=>a.rgbToAnsi256(...a.hexToRgb(t)),enumerable:false},ansi256ToAnsi:{value(t){if(t<8){return 30+t}if(t<16){return 90+(t-8)}let r;let i;let o;if(t>=232){r=((t-232)*10+8)/255;i=r;o=r}else{t-=16;const a=t%36;r=Math.floor(t/36)/5;i=Math.floor(a/6)/5;o=a%6/5}const a=Math.max(r,i,o)*2;if(a===0){return 30}let l=30+(Math.round(o)<<2|Math.round(i)<<1|Math.round(r));if(a===2){l+=60}return l},enumerable:false},rgbToAnsi:{value:(t,r,i)=>a.ansi256ToAnsi(a.rgbToAnsi256(t,r,i)),enumerable:false},hexToAnsi:{value:t=>a.ansi256ToAnsi(a.hexToAnsi256(t)),enumerable:false}});return a}const p=assembleStyles();const d=p;const m=require("node:process");const g=require("node:os");const y=require("node:tty");function hasFlag(t,r=m.argv){const i=t.startsWith("-")?"":t.length===1?"-":"--";const o=r.indexOf(i+t);const a=r.indexOf("--");return o!==-1&&(a===-1||o<a)}const{env:v}=m;let b;if(hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")||hasFlag("color=never")){b=0}else if(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always")){b=1}function envForceColor(){if("FORCE_COLOR"in v){if(v.FORCE_COLOR==="true"){return 1}if(v.FORCE_COLOR==="false"){return 0}return v.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(v.FORCE_COLOR,10),3)}}function translateLevel(t){if(t===0){return false}return{level:t,hasBasic:true,has256:t>=2,has16m:t>=3}}function _supportsColor(t,{streamIsTTY:r,sniffFlags:i=true}={}){const o=envForceColor();if(o!==undefined){b=o}const a=i?b:o;if(a===0){return 0}if(i){if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor")){return 3}if(hasFlag("color=256")){return 2}}if(t&&!r&&a===undefined){return 0}const l=a||0;if(v.TERM==="dumb"){return l}if(m.platform==="win32"){const t=g.release().split(".");if(Number(t[0])>=10&&Number(t[2])>=10586){return Number(t[2])>=14931?3:2}return 1}if("CI"in v){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some((t=>t in v))||v.CI_NAME==="codeship"){return 1}return l}if("TEAMCITY_VERSION"in v){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(v.TEAMCITY_VERSION)?1:0}if("TF_BUILD"in v&&"AGENT_NAME"in v){return 1}if(v.COLORTERM==="truecolor"){return 3}if("TERM_PROGRAM"in v){const t=Number.parseInt((v.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(v.TERM_PROGRAM){case"iTerm.app":return t>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(v.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(v.TERM)){return 1}if("COLORTERM"in v){return 1}return l}function createSupportsColor(t,r={}){const i=_supportsColor(t,{streamIsTTY:t&&t.isTTY,...r});return translateLevel(i)}const _={stdout:createSupportsColor({isTTY:y.isatty(1)}),stderr:createSupportsColor({isTTY:y.isatty(2)})};const w=_;function stringReplaceAll(t,r,i){let o=t.indexOf(r);if(o===-1){return t}const a=r.length;let l=0;let u="";do{u+=t.slice(l,o)+r+i;l=o+a;o=t.indexOf(r,l)}while(o!==-1);u+=t.slice(l);return u}function stringEncaseCRLFWithFirstIndex(t,r,i,o){let a=0;let l="";do{const u=t[o-1]==="\r";l+=t.slice(a,u?o-1:o)+r+(u?"\r\n":"\n")+i;a=o+1;o=t.indexOf("\n",a)}while(o!==-1);l+=t.slice(a);return l}const{stdout:S,stderr:E}=w;const x=Symbol("GENERATOR");const A=Symbol("STYLER");const O=Symbol("IS_EMPTY");const k=["ansi","ansi","ansi256","ansi16m"];const R=Object.create(null);const applyOptions=(t,r={})=>{if(r.level&&!(Number.isInteger(r.level)&&r.level>=0&&r.level<=3)){throw new Error("The `level` option should be an integer from 0 to 3")}const i=S?S.level:0;t.level=r.level===undefined?i:r.level};class Chalk{constructor(t){return chalkFactory(t)}}const chalkFactory=t=>{const chalk=(...t)=>t.join(" ");applyOptions(chalk,t);Object.setPrototypeOf(chalk,createChalk.prototype);return chalk};function createChalk(t){return chalkFactory(t)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(const[t,r]of Object.entries(d)){R[t]={get(){const i=createBuilder(this,createStyler(r.open,r.close,this[A]),this[O]);Object.defineProperty(this,t,{value:i});return i}}}R.visible={get(){const t=createBuilder(this,this[A],true);Object.defineProperty(this,"visible",{value:t});return t}};const getModelAnsi=(t,r,i,...o)=>{if(t==="rgb"){if(r==="ansi16m"){return d[i].ansi16m(...o)}if(r==="ansi256"){return d[i].ansi256(d.rgbToAnsi256(...o))}return d[i].ansi(d.rgbToAnsi(...o))}if(t==="hex"){return getModelAnsi("rgb",r,i,...d.hexToRgb(...o))}return d[i][t](...o)};const T=["rgb","hex","ansi256"];for(const t of T){R[t]={get(){const{level:r}=this;return function(...i){const o=createStyler(getModelAnsi(t,k[r],"color",...i),d.color.close,this[A]);return createBuilder(this,o,this[O])}}};const r="bg"+t[0].toUpperCase()+t.slice(1);R[r]={get(){const{level:r}=this;return function(...i){const o=createStyler(getModelAnsi(t,k[r],"bgColor",...i),d.bgColor.close,this[A]);return createBuilder(this,o,this[O])}}}}const C=Object.defineProperties((()=>{}),{...R,level:{enumerable:true,get(){return this[x].level},set(t){this[x].level=t}}});const createStyler=(t,r,i)=>{let o;let a;if(i===undefined){o=t;a=r}else{o=i.openAll+t;a=r+i.closeAll}return{open:t,close:r,openAll:o,closeAll:a,parent:i}};const createBuilder=(t,r,i)=>{const builder=(...t)=>applyStyle(builder,t.length===1?""+t[0]:t.join(" "));Object.setPrototypeOf(builder,C);builder[x]=t;builder[A]=r;builder[O]=i;return builder};const applyStyle=(t,r)=>{if(t.level<=0||!r){return t[O]?"":r}let i=t[A];if(i===undefined){return r}const{openAll:o,closeAll:a}=i;if(r.includes("")){while(i!==undefined){r=stringReplaceAll(r,i.close,i.open);i=i.parent}}const l=r.indexOf("\n");if(l!==-1){r=stringEncaseCRLFWithFirstIndex(r,a,o,l)}return o+r+a};Object.defineProperties(createChalk.prototype,R);const P=createChalk();const I=createChalk({level:E?E.level:0});const L=P;var M=i(345);const{program:N,createCommand:D,createArgument:j,createOption:$,CommanderError:B,InvalidArgumentError:H,InvalidOptionArgumentError:W,Command:G,Argument:U,Option:V,Help:q}=M;var z=i(5656);var Y=i.n(z);var K=i(1017);var Q=i.n(K);var Z=i(7147);var X=i.n(Z);function isSetup(t){const r="Could not find .hyperbook folder. Be sure to run `hyperbook setup`.";try{const r=X().statSync(Q().join(t,".hyperbook"));if(!r.isDirectory()){throw Error()}}catch(t){console.log(L.red(`Could not find .hyperbook folder at ${r}. Be sure to run \`hyperbook setup\`.`));return false}if(process.env.HYPERBOOK_LOCAL_DEV){return true}const i=Q().join(t,".hyperbook","node_modules",".bin","next");try{X().statSync(i)}catch(t){console.log(L.red(`Could not find next binary at ${i}. Be sure to run \`hyperbook setup\`.`));return false}return true}var J=i(2202);var ee=i.n(J);async function archiveFolder(t,r,i){return new Promise(((o,a)=>{const l=Q().join(t,"public","archives");if(!X().existsSync(l)){X().mkdirSync(l,{recursive:true})}const u=Q().join(l,r+".zip");const c=X().createWriteStream(u);const h=ee()("zip",{zlib:{level:9}});h.on("finish",(()=>{console.log(`${L.green(`[${i}]`)} Archive ${r} zipped.`);o()}));h.on("error",(t=>{throw t}));h.pipe(c);h.directory(Q().join(t,"archives",r),false);h.finalize()}))}async function runArchive(t,r){const i=isSetup(t);if(!i){throw new Error("no setup")}return new Promise(((i,o)=>{if(!X().existsSync(Q().join(t,"archives"))){console.log(`${L.blue(`[${r}]`)} No archives found.`);i()}else{console.log(`${L.blue(`[${r}]`)} Zipping archives.`);const a=X().readdirSync(Q().join(t,"archives"),{withFileTypes:true}).filter((t=>t.isDirectory()));Promise.all(a.map((i=>archiveFolder(t,i.name,r)))).then((()=>{i()})).catch((()=>{o()}))}}))}var te=i(4488);var re=i.n(te);var ne=i(4521);var ie=i.n(ne);async function readHyperbook(t){return new Promise(((r,i)=>{X().readFile(Q().join(t,"hyperbook.json"),((t,o)=>{if(t){console.log(L.red("Could not find 'hyperbook.json'. Make sure you are in the right directory."));i()}else{const t=JSON.parse(o.toString());r(t)}}))}))}const se=require("fs/promises");var oe=i.n(se);var ae=i(659);const le=require("node:path");const ue=require("node:url");const ce=require("node:fs");class Node{value;next;constructor(t){this.value=t}}class yocto_queue_Queue{#e;#t;#r;constructor(){this.clear()}enqueue(t){const r=new Node(t);if(this.#e){this.#t.next=r;this.#t=r}else{this.#e=r;this.#t=r}this.#r++}dequeue(){const t=this.#e;if(!t){return}this.#e=this.#e.next;this.#r--;return t.value}clear(){this.#e=undefined;this.#t=undefined;this.#r=0}get size(){return this.#r}*[Symbol.iterator](){let t=this.#e;while(t){yield t.value;t=t.next}}}function p_limit_pLimit(t){if(!((Number.isInteger(t)||t===Number.POSITIVE_INFINITY)&&t>0)){throw new TypeError("Expected `concurrency` to be a number from 1 and up")}const r=new Queue;let i=0;const next=()=>{i--;if(r.size>0){r.dequeue()()}};const run=async(t,r,o)=>{i++;const a=(async()=>t(...o))();r(a);try{await a}catch{}next()};const enqueue=(o,a,l)=>{r.enqueue(run.bind(undefined,o,a,l));(async()=>{await Promise.resolve();if(i<t&&r.size>0){r.dequeue()()}})()};const generator=(t,...r)=>new Promise((i=>{enqueue(t,i,r)}));Object.defineProperties(generator,{activeCount:{get:()=>i},pendingCount:{get:()=>r.size},clearQueue:{value:()=>{r.clear()}}});return generator}class EndError extends Error{constructor(t){super();this.value=t}}const testElement=async(t,r)=>r(await t);const finder=async t=>{const r=await Promise.all(t);if(r[1]===true){throw new EndError(r[0])}return false};async function p_locate_pLocate(t,r,{concurrency:i=Number.POSITIVE_INFINITY,preserveOrder:o=true}={}){const a=pLimit(i);const l=[...t].map((t=>[t,a(testElement,t,r)]));const u=pLimit(o?1:Number.POSITIVE_INFINITY);try{await Promise.all(l.map((t=>u(finder,t))))}catch(t){if(t instanceof EndError){return t.value}throw t}}const fe={directory:"isDirectory",file:"isFile"};function checkType(t){if(Object.hasOwnProperty.call(fe,t)){return}throw new Error(`Invalid type specified: ${t}`)}const matchType=(t,r)=>r[fe[t]]();const toPath=t=>t instanceof URL?fileURLToPath(t):t;async function locate_path_locatePath(t,{cwd:r=process.cwd(),type:i="file",allowSymlinks:o=true,concurrency:a,preserveOrder:l}={}){checkType(i);r=toPath(r);const u=o?fsPromises.stat:fsPromises.lstat;return pLocate(t,(async t=>{try{const o=await u(path.resolve(r,t));return matchType(i,o)}catch{return false}}),{concurrency:a,preserveOrder:l})}function locate_path_locatePathSync(t,{cwd:r=process.cwd(),type:i="file",allowSymlinks:o=true}={}){checkType(i);r=toPath(r);const a=o?fs.statSync:fs.lstatSync;for(const o of t){try{const t=a(path.resolve(r,o));if(matchType(i,t)){return o}}catch{}}}async function pathExists(t){try{await fsPromises.access(t);return true}catch{return false}}function pathExistsSync(t){try{fs.accessSync(t);return true}catch{return false}}const find_up_toPath=t=>t instanceof URL?fileURLToPath(t):t;const he=Symbol("findUpStop");async function findUpMultiple(t,r={}){let i=path.resolve(find_up_toPath(r.cwd)||"");const{root:o}=path.parse(i);const a=path.resolve(i,r.stopAt||o);const l=r.limit||Number.POSITIVE_INFINITY;const u=[t].flat();const runMatcher=async r=>{if(typeof t!=="function"){return locatePath(u,r)}const i=await t(r.cwd);if(typeof i==="string"){return locatePath([i],r)}return i};const c=[];while(true){const t=await runMatcher({...r,cwd:i});if(t===he){break}if(t){c.push(path.resolve(i,t))}if(i===a||c.length>=l){break}i=path.dirname(i)}return c}function findUpMultipleSync(t,r={}){let i=path.resolve(find_up_toPath(r.cwd)||"");const{root:o}=path.parse(i);const a=r.stopAt||o;const l=r.limit||Number.POSITIVE_INFINITY;const u=[t].flat();const runMatcher=r=>{if(typeof t!=="function"){return locatePathSync(u,r)}const i=t(r.cwd);if(typeof i==="string"){return locatePathSync([i],r)}return i};const c=[];while(true){const t=runMatcher({...r,cwd:i});if(t===he){break}if(t){c.push(path.resolve(i,t))}if(i===a||c.length>=l){break}i=path.dirname(i)}return c}async function find_up_findUp(t,r={}){const i=await findUpMultiple(t,{...r,limit:1});return i[0]}function findUpSync(t,r={}){const i=findUpMultipleSync(t,{...r,limit:1});return i[0]}var pe=Object.defineProperty;var de=Object.defineProperties;var me=Object.getOwnPropertyDescriptors;var ge=Object.getOwnPropertySymbols;var ye=Object.prototype.hasOwnProperty;var ve=Object.prototype.propertyIsEnumerable;var __defNormalProp=(t,r,i)=>r in t?pe(t,r,{enumerable:true,configurable:true,writable:true,value:i}):t[r]=i;var __spreadValues=(t,r)=>{for(var i in r||={})if(ye.call(r,i))__defNormalProp(t,i,r[i]);if(ge)for(var i of ge(r)){if(ve.call(r,i))__defNormalProp(t,i,r[i])}return t};var __spreadProps=(t,r)=>de(t,me(r));var __async=(t,r,i)=>new Promise(((o,a)=>{var fulfilled=t=>{try{step(i.next(t))}catch(t){a(t)}};var rejected=t=>{try{step(i.throw(t))}catch(t){a(t)}};var step=t=>t.done?o(t.value):Promise.resolve(t.value).then(fulfilled,rejected);step((i=i.apply(t,r)).next())}));var listFiles=(t,r="",i=true)=>__async(void 0,null,(function*(){const o=yield fs.readdir(path.join(t,r));return Promise.all(o.flatMap((o=>__async(void 0,null,(function*(){const a=yield fs.stat(path.join(t,r,o));if(a.isDirectory()){return listFiles(t,path.join(r,o),i)}else if(o.endsWith(".md")){if(i){return[path.join(t,r,o)]}else{return[path.join(r,o)]}}return[]}))))).then((t=>t.flat()))}));var readBook=(t,r=true)=>__async(void 0,null,(function*(){return listFiles(path.join(t,"book"),"",r)}));var readGlossary=(t,r=true)=>__async(void 0,null,(function*(){return listFiles(path.join(t,"glossary"),"",r)}));var makeGlossary=t=>__async(void 0,null,(function*(){const r=yield readGlossary(t);const i={};for(const o of r){const{content:r,data:a}=yield readFile(o);let l=path.basename(o,".md");if(a.name){l=a.name}else{console.log(`\n${chalk.yellow(`warn `)}- Glossary page ${o} does not specify a name. Defaulting to the filename ${l}.`)}const u=l[0].toUpperCase();if(!i[u]){i[u]=[]}const c=path.relative(t,o).replace(/\.md$/,"").split("/");i[u].push({name:l,href:"/"+c.join("/")})}return i}));var listPagesForTerm=(t,r)=>__async(void 0,null,(function*(){const i=yield readBook(t);const o=[];for(const a of i){const{content:i,data:l}=yield readFile(a);const u=new RegExp(`:t\\[.*\\]\\{#${r}(..*)?\\}|:t\\[${r}\\]`);const c=i.match(u);if(c&&!l.hide&&l.name){const r=path.relative(path.join(t,"book"),a).replace(/\.md$/,"").split("/");const i=r[r.length-1]==="index";if(i){r.pop()}o.push(__spreadProps(__spreadValues({},l),{href:"/"+r.join("/")}))}}return o}));var readFile=t=>__async(void 0,null,(function*(){const r=yield fs.readFile(t).catch((()=>fs.readFile(t+".md").catch((()=>fs.readFile(path.join(t,"index.md"))))));const{content:i,data:o}=matter(r);return{content:i,data:o}}));var index_esm_readHyperbook=t=>__async(void 0,null,(function*(){return se.readFile(K.join(t,"hyperbook.json")).then((t=>t.toString())).then(JSON.parse)}));var readHyperlibrary=t=>__async(void 0,null,(function*(){return se.readFile(K.join(t,"hyperlibrary.json")).then((t=>t.toString())).then(JSON.parse)}));var findHyperbook=t=>__async(void 0,null,(function*(){return findUp("hyperbook.json",{cwd:t}).then((t=>{if(!t){throw new Error("Could not find hyperbook.json")}return fs.readFile(t)})).then((t=>JSON.parse(t.toString())))}));var findHyperbookRoot=t=>__async(void 0,null,(function*(){return findUp("hyperbook.json",{cwd:t}).then((t=>{if(!t){throw new Error("Could not find hyperbook.json")}return path.parse(t).dir}))}));var readProject=(t,r)=>__async(void 0,null,(function*(){var i,o,a,l;if(r==null?void 0:r.src){t=K.join(t,r.src)}const u=yield index_esm_readHyperbook(t).catch((()=>null));if(u){return{type:"book",src:t,basePath:(i=r==null?void 0:r.basePath)!=null?i:u.basePath,name:(o=r==null?void 0:r.name)!=null?o:u.name,icon:r==null?void 0:r.icon}}const c=yield readHyperlibrary(t).catch((()=>null));if(c){return{type:"library",src:t,basePath:(a=r==null?void 0:r.basePath)!=null?a:c.basePath,name:(l=r==null?void 0:r.name)!=null?l:c.name,projects:yield Promise.all(c.library.map((i=>{var o,a;return readProject(t,__spreadProps(__spreadValues({},i),{basePath:K.join((a=(o=r==null?void 0:r.basePath)!=null?o:c.basePath)!=null?a:"",i.basePath)}))}))),icon:r==null?void 0:r.icon}}console.log(`${L.red("Error")} - Missing book or library for path ${t}.`);throw Error(`Missing book or library for path ${t}`)}));var getProjectName=(t,r)=>{let i="";if(typeof t.name==="string"){i=t.name}else{if(r){i=t.name[r]||""}else{i=Object.values(t.name)[0]}if(!i){console.log(L.red(`You need to provide a name for language ${r} in ${t.src}`));throw Error("")}}return i};var makeLinkForHyperproject=(t,...r)=>__async(void 0,[t,...r],(function*(t,r="en",i={}){var o,a,l,u,c,h;const p=getProjectName(t,r);if(t.type==="library"){return{label:p,links:yield Promise.all(t.projects.map((t=>makeLinkForHyperproject(t,r,i)))),icon:t.icon}}else{let r=(o=t.basePath)!=null?o:"/";if(!r.startsWith("/")){r="/"+r}if((a=i.href)==null?void 0:a.useSrc){r=t.src}if((l=i.href)==null?void 0:l.relative){r=K.relative(i.href.relative,r)}if((u=i.href)==null?void 0:u.prepend){r=K.join(...i.href.prepend,r)}if((c=i.href)==null?void 0:c.append){r=K.join(r,...i.href.append)}if((h=i.href)==null?void 0:h.protocol){if(r.startsWith("/")){r=r.slice(0,-1)}r=i.href.protocol+r}if(r.length>1&&r.endsWith("/")){r=r.slice(0,-1)}return{label:p,href:r,icon:t.icon}}}));var makeNavigationForHyperbook=(t,r="/")=>__async(void 0,null,(function*(){const i=yield index_esm_readHyperbook(t);const getSectionsAndPages=function(r){return __async(this,arguments,(function*(r,o=[]){const a=yield fs.readdir(r);let l=[];let u=[];for(const c of a){let a=path.join(r,c);let h=null;if(i.repo){h=i.repo+"/"+path.relative(t,a)}const p=yield fs.stat(a);if(p.isDirectory()){const{pages:r,sections:i}=yield getSectionsAndPages(a,o);const{content:l,data:c}=yield readFile(a);const p=__spreadProps(__spreadValues({},c),{href:"/"+path.relative(path.join(t,"book"),a),isEmpty:l.trim()==="",pages:r,sections:i});if(h){p.repo=h+"/index.md"}u.push(p)}else{const{data:r}=yield readFile(a);if(a.endsWith(".md")){a=a.substring(0,a.length-3);if(path.relative(path.join(t,"book"),a)==="index"){a=a.substring(0,a.length-5)}if(!a.endsWith("index")){const i=__spreadProps(__spreadValues({},r),{href:"/"+path.relative(path.join(t,"book"),a)});if(h){i.repo=h}l.push(i)}}}}l=l.sort(((t,r)=>t.name>r.name?1:-1));l=l.sort(((t,r)=>{const i=t.index!==void 0?t.index:9999;const o=r.index!==void 0?r.index:9999;return i-o}));u=u.sort(((t,r)=>t.name>r.name?1:-1));u=u.sort(((t,r)=>{const i=t.index!==void 0?t.index:9999;const o=r.index!==void 0?r.index:9999;return i-o}));return{pages:l,sections:u}}))};const getPageList=(t,r)=>{let i=[...r];for(const r of t){i=[...i,r,...getPageList(r.sections,r.pages)]}return i};const{sections:o,pages:a}=yield getSectionsAndPages(path.join(t,"book"));let l=getPageList(o,a);let u=l.findIndex((t=>t.href===r));const c=l[u]||null;l=l.filter((t=>!t.isEmpty&&!t.hide));u=l.findIndex((t=>t.href===r));const h=l[u+1]||null;const p=l[u-1]||null;return{next:h,current:c,previous:p,sections:o,pages:a}}));async function makeDir(t,r={recursive:true}){await X().promises.mkdir(t,r)}var be=i(4700);var _e=i.n(be);function makeEnv(){let t=process.env.NODE_PATH;let r=process.env.PATH;if(process.env.HYPERBOOK_LOCAL_DEV){t=Q().join(__dirname,"..","..","..","platforms","web","node_modules");r=Q().join(__dirname,"..","..","..","platforms","web","node_modules",".bin")+":"+r}const i={NODE_PATH:t,PATH:r};return i}async function runBuildProject(t,r,i){const o=getProjectName(t);if(t.type==="book"){console.log(`${L.blue(`[${o}]`)} Building Book.`);await runBuild(t.src,r,t.basePath,o,i)}else{if(!i){i=t.src;_e().sync(Q().join(i,".hyperbook","out"))}console.log(`${L.blue(`[${o}]`)} Building Library.`);for(const o of t.projects){await runBuildProject(o,r,i)}}}async function runBuild(t,r,i,o,a){const l=isSetup(t);if(!l){throw new Error("no setup")}await runArchive(t,o);const u=await readHyperbook(t);if(!i&&(u===null||u===void 0?void 0:u.basePath)){i=u.basePath}if(i&&!i.startsWith("/")){i="/"+i}if(i&&i.endsWith("/")){i=i.slice(0,-1)}X().writeFileSync(Q().join(t,".hyperbook","next.config.js"),`\nmodule.exports = {\n ${i?`basePath: '${i}',`:""}\n typescript: {\n ignoreBuildErrors: true,\n }\n}\n `);const c=await readHyperbook(t);let h=undefined;if(r.type==="library"){h=await makeLinkForHyperproject(r,c.language)}if(h){if(!c.links){c.links=[h]}else{c.links.push(h)}}c.basePath=i;X().cpSync(Q().join(t,"hyperbook.json"),Q().join(t,".hyperbook","hyperbook.json"),{force:true});X().writeFileSync(Q().join(t,".hyperbook","hyperbook.json"),JSON.stringify(c,null,2));return new Promise(((r,l)=>{var u;const c="npm";const h=["run","next:build"];const p=makeEnv();const d=re()(c,h,{stdio:"pipe",cwd:Q().join(t,".hyperbook"),env:{...process.env,...p,ADBLOCK:"1",DISABLE_OPENCOLLECTIVE:"1"}});const m=`${L.blue(`[${o}]`)} Exporting HTML files`;let g=0;const y=setInterval((()=>{if(!process.env.CI){ie().clearLine(process.stdout,0);ie().cursorTo(process.stdout,0);process.stdout.write(m+".".repeat(g));g=(g+1)%5}}),500);if(process.env.CI){process.stdout.write(m+".\n")}(u=d.stderr)===null||u===void 0?void 0:u.on("data",(t=>{if(!String(t).startsWith("warn")){console.log(`${L.red(`[${o}]`)} `+t)}}));d.on("close",(u=>{clearInterval(y);if(u!==0){process.stdout.write("\n");l({command:`${c} ${h.join(" ")}`});return}else{ie().clearLine(process.stdout,0);ie().cursorTo(process.stdout,0);const u=Q().join(t,".hyperbook","out");if(!a){process.stdout.write(`${L.green(`[${o}]`)} Export successful. Files written to ${u}.\n`);r()}else{const t=Q().join(a,".hyperbook","out",i||"");makeDir(t).then((()=>{X().cpSync(u,t,{recursive:true,force:true});process.stdout.write(`${L.green(`[${o}]`)} Export successful. Files written to ${t}.\n`);r()})).catch((t=>{process.stdout.write("\n");console.error(t);l()}))}}}))}))}async function runDev(){const t=process.cwd();const r=isSetup(t);if(!r){throw new Error("no setup")}return new Promise(((r,i)=>{const o="npm";const a=["run","next:dev"];const l=makeEnv();const u=re()(o,a,{stdio:"inherit",cwd:Q().join(t,".hyperbook"),env:{...process.env,...l,ADBLOCK:"1",DISABLE_OPENCOLLECTIVE:"1"}});u.on("close",(t=>{if(t!==0){i({command:`${o} ${a.join(" ")}`});return}r()}))}))}var we=i(2081);function getPkgManager(){try{const t=process.env.npm_config_user_agent;if(t){if(t.startsWith("yarn")){return"yarn"}else if(t.startsWith("pnpm")){return"pnpm"}}try{(0,we.execSync)("yarn --version",{stdio:"ignore"});return"yarn"}catch{(0,we.execSync)("pnpm --version",{stdio:"ignore"});return"pnpm"}}catch{return"npm"}}var Se=i(2037);var Ee=i.n(Se);const xe=require("node:events");function indentString(t,r=1,i={}){const{indent:o=" ",includeEmptyLines:a=false}=i;if(typeof t!=="string"){throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof t}\``)}if(typeof r!=="number"){throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof r}\``)}if(r<0){throw new RangeError(`Expected \`count\` to be at least 0, got \`${r}\``)}if(typeof o!=="string"){throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof o}\``)}if(r===0){return t}const l=a?/^/gm:/^(?!\s*$)/gm;return t.replace(l,o.repeat(r))}function escapeStringRegexp(t){if(typeof t!=="string"){throw new TypeError("Expected a string")}return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}const Ae=/\s+at.*[(\s](.*)\)?/;const Oe=/^(?:(?:(?:node|node:[\w/]+|(?:(?:node:)?internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)(?:\.js)?:\d+:\d+)|native)/;const ke=typeof Se.homedir==="undefined"?"":Se.homedir().replace(/\\/g,"/");function cleanStack(t,{pretty:r=false,basePath:i}={}){const o=i&&new RegExp(`(at | \\()${escapeStringRegexp(i.replace(/\\/g,"/"))}`,"g");if(typeof t!=="string"){return undefined}return t.replace(/\\/g,"/").split("\n").filter((t=>{const r=t.match(Ae);if(r===null||!r[1]){return true}const i=r[1];if(i.includes(".app/Contents/Resources/electron.asar")||i.includes(".app/Contents/Resources/default_app.asar")){return false}return!Oe.test(i)})).filter((t=>t.trim()!=="")).map((t=>{if(o){t=t.replace(o,"$1")}if(r){t=t.replace(Ae,((t,r)=>t.replace(r,r.replace(ke,"~"))))}return t})).join("\n")}const cleanInternalStack=t=>t.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g,"");class AggregateError extends Error{#n;name="AggregateError";constructor(t){if(!Array.isArray(t)){throw new TypeError(`Expected input to be an Array, got ${typeof t}`)}t=t.map((t=>{if(t instanceof Error){return t}if(t!==null&&typeof t==="object"){return Object.assign(new Error(t.message),t)}return new Error(t)}));let r=t.map((t=>typeof t.stack==="string"?cleanInternalStack(cleanStack(t.stack)):String(t))).join("\n");r="\n"+indentString(r,4);super(r);this.#n=t}get errors(){return this.#n.slice()}}async function pMap(t,r,{concurrency:i=Number.POSITIVE_INFINITY,stopOnError:o=true}={}){return new Promise(((a,l)=>{if(t[Symbol.iterator]===undefined&&t[Symbol.asyncIterator]===undefined){throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof t})`)}if(typeof r!=="function"){throw new TypeError("Mapper function is required")}if(!((Number.isSafeInteger(i)||i===Number.POSITIVE_INFINITY)&&i>=1)){throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${i}\` (${typeof i})`)}const u=[];const c=[];const h=new Map;let p=false;let d=false;let m=false;let g=0;let y=0;const v=t[Symbol.iterator]===undefined?t[Symbol.asyncIterator]():t[Symbol.iterator]();const reject=t=>{p=true;d=true;l(t)};const next=async()=>{if(d){return}const t=await v.next();const i=y;y++;if(t.done){m=true;if(g===0&&!d){if(!o&&c.length>0){reject(new AggregateError(c));return}d=true;if(!h.size){a(u);return}const t=[];for(const[r,i]of u.entries()){if(h.get(r)===Re){continue}t.push(i)}a(t)}return}g++;(async()=>{try{const o=await t.value;if(d){return}const a=await r(o,i);if(a===Re){h.set(i,a)}u[i]=a;g--;await next()}catch(t){if(o){reject(t)}else{c.push(t);g--;try{await next()}catch(t){reject(t)}}}})()};(async()=>{for(let t=0;t<i;t++){try{await next()}catch(t){reject(t);break}if(m||p){break}}})()}))}const Re=Symbol("skip");function arrify(t){if(t===null||t===undefined){return[]}if(Array.isArray(t)){return t}if(typeof t==="string"){return[t]}if(typeof t[Symbol.iterator]==="function"){return[...t]}return[t]}var Te=i(8174);class AbortError extends Error{constructor(t){super();this.name="AbortError";this.message=t}}const getDOMException=t=>globalThis.DOMException===undefined?new AbortError(t):new DOMException(t);const getAbortedReason=t=>{const r=t.reason===undefined?getDOMException("This operation was aborted."):t.reason;return r instanceof Error?r:getDOMException(r)};async function p_map_pMap(t,r,{concurrency:i=Number.POSITIVE_INFINITY,stopOnError:o=true,signal:a}={}){return new Promise(((l,u)=>{if(t[Symbol.iterator]===undefined&&t[Symbol.asyncIterator]===undefined){throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof t})`)}if(typeof r!=="function"){throw new TypeError("Mapper function is required")}if(!((Number.isSafeInteger(i)||i===Number.POSITIVE_INFINITY)&&i>=1)){throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${i}\` (${typeof i})`)}const c=[];const h=[];const p=new Map;let d=false;let m=false;let g=false;let y=0;let v=0;const b=t[Symbol.iterator]===undefined?t[Symbol.asyncIterator]():t[Symbol.iterator]();const reject=t=>{d=true;m=true;u(t)};if(a){if(a.aborted){reject(getAbortedReason(a))}a.addEventListener("abort",(()=>{reject(getAbortedReason(a))}))}const next=async()=>{if(m){return}const t=await b.next();const i=v;v++;if(t.done){g=true;if(y===0&&!m){if(!o&&h.length>0){reject(new AggregateError(h));return}m=true;if(p.size===0){l(c);return}const t=[];for(const[r,i]of c.entries()){if(p.get(r)===Ce){continue}t.push(i)}l(t)}return}y++;(async()=>{try{const o=await t.value;if(m){return}const a=await r(o,i);if(a===Ce){p.set(i,a)}c[i]=a;y--;await next()}catch(t){if(o){reject(t)}else{h.push(t);y--;try{await next()}catch(t){reject(t)}}}})()};(async()=>{for(let t=0;t<i;t++){try{await next()}catch(t){reject(t);break}if(g||d){break}}})()}))}const Ce=Symbol("skip");async function pFilter(t,r,i){const o=await p_map_pMap(t,((t,i)=>Promise.all([r(t,i),t])),i);return o.filter((t=>Boolean(t[0]))).map((t=>t[1]))}var Pe=i(9117);var Ie=i(2153);var Le=i(3286);var Me=i(7993);function slash(t){const r=/^\\\\\?\\/.test(t);const i=/[^\u0000-\u0080]+/.test(t);if(r||i){return t}return t.replace(/\\/g,"/")}const Ne=require("node:stream");const utilities_toPath=t=>t instanceof URL?(0,ue.fileURLToPath)(t):t;class FilterStream extends Ne.Transform{constructor(t){super({objectMode:true,transform(r,i,o){o(undefined,t(r)?r:undefined)}})}}const isNegativePattern=t=>t[0]==="!";const De={ignore:["**/node_modules","**/flow-typed","**/coverage","**/.git"],absolute:true,dot:true};const je="**/.gitignore";const applyBaseToPattern=(t,r)=>isNegativePattern(t)?"!"+le.posix.join(r,t.slice(1)):le.posix.join(r,t);const parseIgnoreFile=(t,r)=>{const i=slash(le.relative(r,le.dirname(t.filePath)));return t.content.split(/\r?\n/).filter((t=>t&&!t.startsWith("#"))).map((t=>applyBaseToPattern(t,i)))};const toRelativePath=(t,r)=>{r=slash(r);if(le.isAbsolute(t)){if(slash(t).startsWith(r)){return le.relative(r,t)}throw new Error(`Path ${t} is not in cwd ${r}`)}return t};const getIsIgnoredPredicate=(t,r)=>{const i=t.flatMap((t=>parseIgnoreFile(t,r)));const o=Me().add(i);return t=>{t=utilities_toPath(t);t=toRelativePath(t,r);return o.ignores(slash(t))}};const normalizeOptions=(t={})=>({cwd:utilities_toPath(t.cwd)||m.cwd()});const isIgnoredByIgnoreFiles=async(t,r)=>{const{cwd:i}=normalizeOptions(r);const o=await Ie(t,{cwd:i,...De});const a=await Promise.all(o.map((async t=>({filePath:t,content:await ce.promises.readFile(t,"utf8")}))));return getIsIgnoredPredicate(a,i)};const isIgnoredByIgnoreFilesSync=(t,r)=>{const{cwd:i}=normalizeOptions(r);const o=Ie.sync(t,{cwd:i,...De});const a=o.map((t=>({filePath:t,content:ce.readFileSync(t,"utf8")})));return getIsIgnoredPredicate(a,i)};const isGitIgnored=t=>isIgnoredByIgnoreFiles(je,t);const isGitIgnoredSync=t=>isIgnoredByIgnoreFilesSync(je,t);const assertPatternsInput=t=>{if(t.some((t=>typeof t!=="string"))){throw new TypeError("Patterns must be a string or an array of strings")}};const toPatternsArray=t=>{t=[...new Set([t].flat())];assertPatternsInput(t);return t};const checkCwdOption=t=>{if(!t.cwd){return}let r;try{r=ce.statSync(t.cwd)}catch{return}if(!r.isDirectory()){throw new Error("The `cwd` option must be a path to a directory")}};const globby_normalizeOptions=(t={})=>{t={ignore:[],expandDirectories:true,...t,cwd:utilities_toPath(t.cwd)};checkCwdOption(t);return t};const normalizeArguments=t=>async(r,i)=>t(toPatternsArray(r),globby_normalizeOptions(i));const normalizeArgumentsSync=t=>(r,i)=>t(toPatternsArray(r),globby_normalizeOptions(i));const getIgnoreFilesPatterns=t=>{const{ignoreFiles:r,gitignore:i}=t;const o=r?toPatternsArray(r):[];if(i){o.push(je)}return o};const getFilter=async t=>{const r=getIgnoreFilesPatterns(t);return createFilterFunction(r.length>0&&await isIgnoredByIgnoreFiles(r,{cwd:t.cwd}))};const getFilterSync=t=>{const r=getIgnoreFilesPatterns(t);return createFilterFunction(r.length>0&&isIgnoredByIgnoreFilesSync(r,{cwd:t.cwd}))};const createFilterFunction=t=>{const r=new Set;return i=>{const o=i.path||i;const a=le.normalize(o);const l=r.has(a)||t&&t(o);r.add(a);return!l}};const unionFastGlobResults=(t,r)=>t.flat().filter((t=>r(t)));const unionFastGlobStreams=(t,r)=>Pe(t).pipe(new FilterStream((t=>r(t))));const convertNegativePatterns=(t,r)=>{const i=[];while(t.length>0){const o=t.findIndex((t=>isNegativePattern(t)));if(o===-1){i.push({patterns:t,options:r});break}const a=t[o].slice(1);for(const t of i){t.options.ignore.push(a)}if(o!==0){i.push({patterns:t.slice(0,o),options:{...r,ignore:[...r.ignore,a]}})}t=t.slice(o+1)}return i};const getDirGlobOptions=(t,r)=>({...r?{cwd:r}:{},...Array.isArray(t)?{files:t}:t});const generateTasks=async(t,r)=>{const i=convertNegativePatterns(t,r);const{cwd:o,expandDirectories:a}=r;if(!a){return i}const l=getDirGlobOptions(a,o);const u=o?{cwd:o}:undefined;return Promise.all(i.map((async t=>{let{patterns:r,options:i}=t;[r,i.ignore]=await Promise.all([Le(r,l),Le(i.ignore,u)]);return{patterns:r,options:i}})))};const generateTasksSync=(t,r)=>{const i=convertNegativePatterns(t,r);const{cwd:o,expandDirectories:a}=r;if(!a){return i}const l=getDirGlobOptions(a,o);const u=o?{cwd:o}:undefined;return i.map((t=>{let{patterns:r,options:i}=t;r=Le.sync(r,l);i.ignore=Le.sync(i.ignore,u);return{patterns:r,options:i}}))};const Fe=normalizeArguments((async(t,r)=>{const[i,o]=await Promise.all([generateTasks(t,r),getFilter(r)]);const a=await Promise.all(i.map((t=>Ie(t.patterns,t.options))));return unionFastGlobResults(a,o)}));const $e=normalizeArgumentsSync(((t,r)=>{const i=generateTasksSync(t,r);const o=getFilterSync(r);const a=i.map((t=>Ie.sync(t.patterns,t.options)));return unionFastGlobResults(a,o)}));const Be=normalizeArgumentsSync(((t,r)=>{const i=generateTasksSync(t,r);const o=getFilterSync(r);const a=i.map((t=>Ie.stream(t.patterns,t.options)));return unionFastGlobStreams(a,o)}));const He=normalizeArgumentsSync(((t,r)=>t.some((t=>Ie.isDynamicPattern(t,r)))));const We=normalizeArguments(generateTasks);const Ge=normalizeArgumentsSync(generateTasksSync);var Ue=i(7971);var Ve=i(3134);class CpyError extends Ve{constructor(t,r){super(t,r);Object.assign(this,r);this.name="CpyError"}}const qe=["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^Desktop\\.ini$","@eaDir$"];const ze=new RegExp(qe.join("|"));function isJunk(t){return ze.test(t)}function isNotJunk(t){return!isJunk(t)}class GlobPattern{constructor(t,r,i){this.path=t;this.originalPath=t;this.destination=r;this.options=i;this.isDirectory=false;if(!He(t)&&ce.existsSync(t)&&ce.lstatSync(t).isDirectory()){this.path=[t,"**"].join("/");this.isDirectory=true}}get name(){return le.basename(this.originalPath)}get normalizedPath(){const t=this.originalPath.split("/");const r=t.findIndex((t=>t?He(t):false));const i=t.slice(0,r).join("/");if(i){return le.isAbsolute(i)?i:le.join(this.options.cwd,i)}return this.destination}hasMagic(){return He(this.options.flat?this.path:this.originalPath)}getMatches(){let t=$e(this.path,{...this.options,dot:true,absolute:true,onlyFiles:true});if(this.options.ignoreJunk){t=t.filter((t=>isNotJunk(le.basename(t))))}return t}}const Ye=(g.cpus().length||1)*2;const Ke={ignoreJunk:true,flat:false,cwd:m.cwd()};class Entry{constructor(t,r,i){this.path=t.split("/").join(le.sep);this.relativePath=r.split("/").join(le.sep);this.pattern=i;Object.freeze(this)}get name(){return le.basename(this.path)}get nameWithoutExtension(){return le.basename(this.path,le.extname(this.path))}get extension(){return le.extname(this.path).slice(1)}}const expandPatternsWithBraceExpansion=t=>t.flatMap((t=>Ue.braces(t,{expand:true,nodupes:true})));const preprocessDestinationPath=({entry:t,destination:r,options:i})=>{if(t.pattern.hasMagic()){if(i.flat){if(le.isAbsolute(r)){return le.join(r,t.name)}return le.join(i.cwd,r,t.name)}return le.join(r,le.relative(t.pattern.normalizedPath,t.path))}if(le.isAbsolute(r)){return le.join(r,t.name)}if(t.pattern.isDirectory&&le.relative(i.cwd,t.path).startsWith("..")){return le.join(i.cwd,r,le.basename(t.pattern.originalPath),le.relative(t.pattern.originalPath,t.path))}if(!t.pattern.isDirectory&&t.path===t.relativePath){return le.join(i.cwd,r,le.basename(t.pattern.originalPath),le.relative(t.pattern.originalPath,t.path))}if(!t.pattern.isDirectory&&i.flat){return le.join(i.cwd,r,le.basename(t.pattern.originalPath))}return le.join(i.cwd,r,le.relative(i.cwd,t.path))};const renameFile=(t,r)=>{const i=le.basename(t,le.extname(t));const o=le.extname(t);const a=le.dirname(t);if(typeof r==="string"){return le.join(a,r)}if(typeof r==="function"){return le.join(a,`${r(i)}${o}`)}return t};function cpy(t,r,{concurrency:i=Ye,...o}={}){const a=new Map;const l=new xe;o={...Ke,...o};const u=(async()=>{let u=[];let c=0;let h=0;let p=expandPatternsWithBraceExpansion(arrify(t)).map((t=>t.replace(/\\/g,"/")));const d=p.filter((t=>!t.startsWith("!")));const m=p.filter((t=>t.startsWith("!")));if(d.length===0||!r){throw new CpyError("`source` and `destination` required")}p=p.map((t=>new GlobPattern(t,r,{...o,ignore:m})));for(const t of p){let r=[];try{r=t.getMatches()}catch(r){throw new CpyError(`Cannot glob \`${t.originalPath}\`: ${r.message}`,r)}if(r.length===0&&!He(t.originalPath)&&!He(m)){throw new CpyError(`Cannot copy \`${t.originalPath}\`: the file doesn't exist`)}u=[...u,...r.map((r=>new Entry(r,le.relative(o.cwd,r),t)))]}if(o.filter!==undefined){u=await pFilter(u,o.filter,{concurrency:1024})}if(u.length===0){l.emit("progress",{totalFiles:0,percent:1,completedFiles:0,completedSize:0})}const fileProgressHandler=t=>{const r=a.get(t.sourcePath)||{writtenBytes:0,percent:0};if(r.writtenBytes!==t.writtenBytes||r.percent!==t.percent){h-=r.writtenBytes;h+=t.writtenBytes;if(t.percent===1&&r.percent!==1){c++}a.set(t.sourcePath,{writtenBytes:t.writtenBytes,percent:t.percent});l.emit("progress",{totalFiles:u.length,percent:c/u.length,completedFiles:c,completedSize:h})}};return pMap(u,(async t=>{const i=renameFile(preprocessDestinationPath({entry:t,destination:r,options:o}),o.rename);try{await Te(t.path,i,o).on("progress",fileProgressHandler)}catch(r){throw new CpyError(`Cannot copy from \`${t.relativePath}\` to \`${i}\`: ${r.message}`,r)}return i}),{concurrency:i})})();u.on=(...t)=>{l.on(...t);return u};return u}var Qe=i(5713);var Ze=i.n(Qe);function isFolderEmpty(t,r){const i=[".DS_Store",".git",".gitattributes",".gitignore",".gitlab-ci.yml",".hg",".hgcheck",".hgignore",".idea",".npmignore",".travis.yml","LICENSE","Thumbs.db","docs","mkdocs.yml","npm-debug.log","yarn-debug.log","yarn-error.log"];const o=X().readdirSync(t).filter((t=>!i.includes(t))).filter((t=>!/\.iml$/.test(t)));if(o.length>0){console.log(`The directory ${L.green(r)} contains files that could conflict:`);console.log();for(const r of o){try{const i=X().lstatSync(Q().join(t,r));if(i.isDirectory()){console.log(` ${L.blue(r)}/`)}else{console.log(` ${r}`)}}catch{console.log(` ${r}`)}}console.log();console.log("Either try using a new directory name, or remove the files listed above.");console.log();return false}return true}async function isWriteable(t){try{await X().promises.access(t,(X().constants||X()).W_OK);return true}catch(t){return false}}function isInGitRepository(){try{(0,we.execSync)("git rev-parse --is-inside-work-tree",{stdio:"ignore"});return true}catch(t){}return false}function isInMercurialRepository(){try{(0,we.execSync)("hg --cwd . root",{stdio:"ignore"});return true}catch(t){}return false}function tryGitInit(t){let r=false;try{(0,we.execSync)("git --version",{stdio:"ignore"});if(isInGitRepository()||isInMercurialRepository()){return false}(0,we.execSync)("git init",{stdio:"ignore"});r=true;(0,we.execSync)("git checkout -b main",{stdio:"ignore"});(0,we.execSync)("git add -A",{stdio:"ignore"});(0,we.execSync)('git commit -m "Initial commit from Hyperbook"',{stdio:"ignore"});return true}catch(i){if(r){try{_e().sync(Q().join(t,".git"))}catch(t){}}return false}}function install(t,r,{packageManager:i,isOnline:o,devDependencies:a}){const l=[];const u=[];return new Promise(((c,h)=>{let p;let d=i;const m=i==="yarn";if(r&&r.length){if(m){p=["add","--exact"];if(!o)p.push("--offline");p.push("--cwd",t);if(a)p.push("--dev");p.push(...r)}else{p=["install","--save-exact"];p.push(a?"--save-dev":"--save");p.push(...r)}}else{p=["install"];if(!o){console.log(L.yellow("You appear to be offline."));if(m){console.log(L.yellow("Falling back to the local Yarn cache."));console.log();p.push("--offline")}else{console.log()}}}if(m){p.push(...u)}else{p.push(...l)}const g=re()(d,p,{stdio:"inherit",cwd:t,env:{...process.env,ADBLOCK:"1",DISABLE_OPENCOLLECTIVE:"1"}});g.on("close",(t=>{if(t!==0){h({command:`${d} ${p.join(" ")}`});return}c()}))}))}const Xe=require("dns");var Je=i.n(Xe);var et=i(7310);var tt=i.n(et);function getProxy(){if(process.env.https_proxy){return process.env.https_proxy}try{const t=(0,we.execSync)("npm config get https-proxy").toString().trim();return t!=="null"?t:undefined}catch(t){return}}function getOnline(){return new Promise((t=>{Je().lookup("registry.yarnpkg.com",(r=>{if(!r){return t(true)}const i=getProxy();if(!i){return t(false)}const{hostname:o}=tt().parse(i);if(!o){return t(false)}Je().lookup(o,(r=>{t(r==null)}))}))}))}async function makeSymlink(t,r){const i=Ee().platform()=="win32"?"junction":null;return new Promise(((o,a)=>{X().symlink(t,r,i,(t=>{if(t){a()}else{o()}}))}))}async function runSetupProject(t,r){const o=getProjectName(t);console.log(`${L.blue(`[${o}]`)} Setup Project.`);const a=Q().join(t.src,".hyperbook");const l=Q().join((r===null||r===void 0?void 0:r.src)||"",".hyperbook");_e().sync(a);const u=i.ab+"templates";await makeDir(a);await cpy("default/.hyperbook/**",a,{cwd:i.ab+"templates",followSymbolicLinks:false});if(process.env.HYPERBOOK_LOCAL_DEV){const t=await oe().readFile(Q().join(__dirname,"..","..","..","platforms","web","package.json")).then((t=>JSON.parse(t.toString())));await oe().writeFile(Q().join(a,"package.json"),JSON.stringify({...t,name:`@docs/`+o.toLowerCase().replace(" ","-"),scripts:{"next:dev":"next-hyperbook-watch","next:build":"next build && next export"}},null,2))}else{if(!r){const t=await getOnline();await install(l,null,{packageManager:"npm",isOnline:t})}else{await makeSymlink(Q().join(l,"node_modules"),Q().join(a,"node_modules"))}}if(t.type==="library"){await makeSymlink(Q().join(t.src,"hyperlibrary.json"),Q().join(a,"hyperlibrary.json"));for(const i of t.projects){await runSetupProject(i,r)}return}await makeSymlink(Q().join(t.src,"archives"),Q().join(a,"archives"));await makeSymlink(Q().join(t.src,"book"),Q().join(a,"book"));await makeSymlink(Q().join(t.src,"glossary"),Q().join(a,"glossary"));await makeSymlink(Q().join(t.src,"public"),Q().join(a,"public"));await makeSymlink(Q().join(t.src,"hyperbook.json"),Q().join(a,"hyperbook.json"))}async function runNew({programName:t,bookPath:r}){if(typeof r==="string"){r=r.trim()}if(!r){const t=await Ze()({type:"text",name:"path",message:"What is your book named?",initial:"my-book"});if(typeof t.path==="string"){r=t.path.trim()}}if(!r){console.log();console.log("Please specify the book directory:");console.log(` ${L.cyan(t)} ${L.green("<book-directory>")}`);console.log();console.log("For example:");console.log(` ${L.cyan(t)} ${L.green("my-new-book")}`);console.log();console.log(`Run ${L.cyan(`${t} --help`)} to see all options.`);process.exit(1)}const o=Q().resolve(r);if(!await isWriteable(Q().dirname(o))){console.error("The book path is not writable, please check folder permissions and try again.");console.error("It is likely you do not have write permissions for this folder.");process.exit(1)}const a=Q().basename(o);await makeDir(o);if(!isFolderEmpty(o,a)){process.exit(1)}const l=process.cwd();console.log(`Creating a new hyperbook in ${L.green(o)}.`);console.log();process.chdir(o);const{description:u}=await Ze()({type:"text",name:"description",message:"What is your book about?",initial:""});const{author:c}=await Ze()({type:"text",name:"author",message:"Who is the author of the book?",initial:""});const{authorUrl:h}=await Ze()({type:"text",name:"authorUrl",message:"What is the link to the authors homepage?",initial:""});let{license:p}=await Ze()({type:"select",name:"license",message:"Pick a license for your book!",choices:[{title:"Creative Commons Zero (CC0)",value:"cc0"},{title:"Creative Commons Attribution (CC BY)",value:"cc-by"},{title:"Creative Commons Attribution-ShareAlike (CC BY-SA)",value:"cc-by-sa"},{title:"Creative Commons Attribution-NoDerivs (CC BY-ND)",value:"cc-by-nd"},{title:"Creative Commons Attribution-NonCommercial (CC BY-NC)",value:"cc-by-nc"},{title:"Creative Commons Attribution-NonCommercial-ShareAlike (CC BY-NC-SA)",value:"cc-by-nc-sa"},{title:"Creative Commons Attribution-NonCommercial-NoDervis (CC BY-NC-ND)",value:"cc-by-nc-nd"},{title:"Custom",value:"custom"}]});if(p==="custom"){const t=await Ze()({type:"text",name:"license",message:"Which custom license you want to use?"});p=t.license}const{language:d}=await Ze()({type:"text",name:"language",message:"In which language is your book written? Provide a short code, e.g.: en or de",initial:"en"});const m={name:a,version:"0.0.0",description:u,license:p,author:{name:c,url:h},language:d};X().writeFileSync(Q().join(o,"hyperbook.json"),JSON.stringify(m,null,2)+Ee().EOL);console.log();const g=i.ab+"templates";await cpy("default/**",o,{cwd:i.ab+"templates",rename:t=>{switch(t){case"gitignore":{return".".concat(t)}case"README-template.md":{return"README.md"}default:{return t}}}});await runSetupProject({type:"book",name:a,src:o});if(tryGitInit(o)){console.log("Initialized a git repository.");console.log()}let y;if(Q().join(l,a)===r){y=a}else{y=r}console.log(`${L.green("Success!")} Created ${a} at ${r}`);console.log("Inside that directory, you can run several commands:");console.log();console.log(L.cyan(` hyperbook dev`));console.log(" Starts the development server.");console.log();console.log(L.cyan(` hyperbook build`));console.log(" Builds the book for production.");console.log();console.log("We suggest that you begin by typing:");console.log();console.log(L.cyan(" cd"),y);console.log(` ${L.cyan(`hyperbook dev`)}`);console.log()}const rt=JSON.parse('{"name":"hyperbook","version":"0.8.9","author":"Mike Barkmin","homepage":"https://github.com/openpatch/hyperbook#readme","license":"MIT","bin":{"hyperbook":"./dist/index.js"},"files":["dist"],"publishConfig":{"access":"public"},"repository":{"type":"git","url":"git+https://github.com/openpatch/hyperbook.git","directory":"packages/hyperbook"},"bugs":{"url":"https://github.com/openpatch/hyperbook/issues"},"engines":{"node":">=12.22.0"},"scripts":{"version":"pnpm build","lint":"tsc --noEmit","dev":"ncc build ./index.ts -w -o dist/","build":"rimraf dist && ncc build ./index.ts -o ./dist/ -e \\"hyperbook-simple-template\\" --minify --no-cache --no-source-map-register && node ./postbuild.mjs"},"devDependencies":{"@pnpm/exportable-manifest":"4.0.2","@types/archiver":"5.3.1","@types/async-retry":"1.4.5","@types/cross-spawn":"6.0.2","@types/prompts":"2.4.1","@types/rimraf":"3.0.2","@types/tar":"6.1.3","@vercel/ncc":"0.34.0","archiver":"5.3.1","async-retry":"1.3.3","chalk":"5.1.2","commander":"9.4.1","cpy":"9.0.1","cross-spawn":"7.0.3","got":"12.5.3","prompts":"2.4.2","rimraf":"3.0.2","tar":"6.1.12","update-check":"1.5.4","@platforms/web":"workspace:*"},"dependencies":{"@hyperbook/fs":"workspace:*","@hyperbook/types":"workspace:*"}}');const nt=new G;nt.name(rt.name).version(rt.version).hook("preAction",(async()=>{await notifyUpdate()}));nt.command("new").description("create a new hyperbook").arguments("<book-directory>").usage(`${L.green("<book-directory>")}`).action((async t=>{await runNew({programName:nt.name(),bookPath:t}).catch((()=>process.exit(1)))}));nt.command("dev").description("start the development server for a hyperbook").action((async()=>{await runDev()}));nt.command("setup").description("downloads the latest version of the template of a hyperbook").action((async()=>{const t=await readProject(process.cwd()).catch((()=>{process.exit(1)}));await runSetupProject(t).catch((()=>{process.exit(1)}))}));nt.command("build").description("build a hyperbook").action((async()=>{const t=await readProject(process.cwd()).catch((()=>{process.exit(1)}));await runBuildProject(t,t).catch((()=>{process.exit(1)}))}));nt.command("archive").description("create archives from archives folder").action((async()=>{await runArchive(process.cwd()).catch((()=>process.exit(1)))}));nt.parseAsync(process.argv);const it=Y()(rt).catch((()=>null));async function notifyUpdate(){try{const t=await it;if(t===null||t===void 0?void 0:t.latest){const t=getPkgManager();console.log();console.log(L.yellow.bold("A new version of `hyperbook` is available!"));console.log("You can update by running: "+L.cyan(t==="yarn"?"yarn global add hyperbook":`${t} install --global hyperbook`));console.log()}process.exit()}catch{}}},9491:t=>{"use strict";t.exports=require("assert")},4300:t=>{"use strict";t.exports=require("buffer")},2081:t=>{"use strict";t.exports=require("child_process")},2057:t=>{"use strict";t.exports=require("constants")},2361:t=>{"use strict";t.exports=require("events")},7147:t=>{"use strict";t.exports=require("fs")},3685:t=>{"use strict";t.exports=require("http")},5687:t=>{"use strict";t.exports=require("https")},2037:t=>{"use strict";t.exports=require("os")},1017:t=>{"use strict";t.exports=require("path")},7282:t=>{"use strict";t.exports=require("process")},4521:t=>{"use strict";t.exports=require("readline")},2781:t=>{"use strict";t.exports=require("stream")},1576:t=>{"use strict";t.exports=require("string_decoder")},7310:t=>{"use strict";t.exports=require("url")},3837:t=>{"use strict";t.exports=require("util")},9796:t=>{"use strict";t.exports=require("zlib")},345:(t,r,i)=>{const{Argument:o}=i(4079);const{Command:a}=i(6505);const{CommanderError:l,InvalidArgumentError:u}=i(9027);const{Help:c}=i(9164);const{Option:h}=i(5205);r=t.exports=new a;r.program=r;r.Argument=o;r.Command=a;r.CommanderError=l;r.Help=c;r.InvalidArgumentError=u;r.InvalidOptionArgumentError=u;r.Option=h},4079:(t,r,i)=>{const{InvalidArgumentError:o}=i(9027);class Argument{constructor(t,r){this.description=r||"";this.variadic=false;this.parseArg=undefined;this.defaultValue=undefined;this.defaultValueDescription=undefined;this.argChoices=undefined;switch(t[0]){case"<":this.required=true;this._name=t.slice(1,-1);break;case"[":this.required=false;this._name=t.slice(1,-1);break;default:this.required=true;this._name=t;break}if(this._name.length>3&&this._name.slice(-3)==="..."){this.variadic=true;this._name=this._name.slice(0,-3)}}name(){return this._name}_concatValue(t,r){if(r===this.defaultValue||!Array.isArray(r)){return[t]}return r.concat(t)}default(t,r){this.defaultValue=t;this.defaultValueDescription=r;return this}argParser(t){this.parseArg=t;return this}choices(t){this.argChoices=t.slice();this.parseArg=(t,r)=>{if(!this.argChoices.includes(t)){throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,r)}return t};return this}argRequired(){this.required=true;return this}argOptional(){this.required=false;return this}}function humanReadableArgName(t){const r=t.name()+(t.variadic===true?"...":"");return t.required?"<"+r+">":"["+r+"]"}r.Argument=Argument;r.humanReadableArgName=humanReadableArgName},6505:(t,r,i)=>{const o=i(2361).EventEmitter;const a=i(2081);const l=i(1017);const u=i(7147);const c=i(7282);const{Argument:h,humanReadableArgName:p}=i(4079);const{CommanderError:d}=i(9027);const{Help:m}=i(9164);const{Option:g,splitOptionFlags:y,DualOptions:v}=i(5205);const{suggestSimilar:b}=i(211);class Command extends o{constructor(t){super();this.commands=[];this.options=[];this.parent=null;this._allowUnknownOption=false;this._allowExcessArguments=true;this._args=[];this.args=[];this.rawArgs=[];this.processedArgs=[];this._scriptPath=null;this._name=t||"";this._optionValues={};this._optionValueSources={};this._storeOptionsAsProperties=false;this._actionHandler=null;this._executableHandler=false;this._executableFile=null;this._executableDir=null;this._defaultCommandName=null;this._exitCallback=null;this._aliases=[];this._combineFlagAndOptionalValue=true;this._description="";this._summary="";this._argsDescription=undefined;this._enablePositionalOptions=false;this._passThroughOptions=false;this._lifeCycleHooks={};this._showHelpAfterError=false;this._showSuggestionAfterError=true;this._outputConfiguration={writeOut:t=>c.stdout.write(t),writeErr:t=>c.stderr.write(t),getOutHelpWidth:()=>c.stdout.isTTY?c.stdout.columns:undefined,getErrHelpWidth:()=>c.stderr.isTTY?c.stderr.columns:undefined,outputError:(t,r)=>r(t)};this._hidden=false;this._hasHelpOption=true;this._helpFlags="-h, --help";this._helpDescription="display help for command";this._helpShortFlag="-h";this._helpLongFlag="--help";this._addImplicitHelpCommand=undefined;this._helpCommandName="help";this._helpCommandnameAndArgs="help [command]";this._helpCommandDescription="display help for command";this._helpConfiguration={}}copyInheritedSettings(t){this._outputConfiguration=t._outputConfiguration;this._hasHelpOption=t._hasHelpOption;this._helpFlags=t._helpFlags;this._helpDescription=t._helpDescription;this._helpShortFlag=t._helpShortFlag;this._helpLongFlag=t._helpLongFlag;this._helpCommandName=t._helpCommandName;this._helpCommandnameAndArgs=t._helpCommandnameAndArgs;this._helpCommandDescription=t._helpCommandDescription;this._helpConfiguration=t._helpConfiguration;this._exitCallback=t._exitCallback;this._storeOptionsAsProperties=t._storeOptionsAsProperties;this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue;this._allowExcessArguments=t._allowExcessArguments;this._enablePositionalOptions=t._enablePositionalOptions;this._showHelpAfterError=t._showHelpAfterError;this._showSuggestionAfterError=t._showSuggestionAfterError;return this}command(t,r,i){let o=r;let a=i;if(typeof o==="object"&&o!==null){a=o;o=null}a=a||{};const[,l,u]=t.match(/([^ ]+) *(.*)/);const c=this.createCommand(l);if(o){c.description(o);c._executableHandler=true}if(a.isDefault)this._defaultCommandName=c._name;c._hidden=!!(a.noHelp||a.hidden);c._executableFile=a.executableFile||null;if(u)c.arguments(u);this.commands.push(c);c.parent=this;c.copyInheritedSettings(this);if(o)return this;return c}createCommand(t){return new Command(t)}createHelp(){return Object.assign(new m,this.configureHelp())}configureHelp(t){if(t===undefined)return this._helpConfiguration;this._helpConfiguration=t;return this}configureOutput(t){if(t===undefined)return this._outputConfiguration;Object.assign(this._outputConfiguration,t);return this}showHelpAfterError(t=true){if(typeof t!=="string")t=!!t;this._showHelpAfterError=t;return this}showSuggestionAfterError(t=true){this._showSuggestionAfterError=!!t;return this}addCommand(t,r){if(!t._name){throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`)}r=r||{};if(r.isDefault)this._defaultCommandName=t._name;if(r.noHelp||r.hidden)t._hidden=true;this.commands.push(t);t.parent=this;return this}createArgument(t,r){return new h(t,r)}argument(t,r,i,o){const a=this.createArgument(t,r);if(typeof i==="function"){a.default(o).argParser(i)}else{a.default(i)}this.addArgument(a);return this}arguments(t){t.split(/ +/).forEach((t=>{this.argument(t)}));return this}addArgument(t){const r=this._args.slice(-1)[0];if(r&&r.variadic){throw new Error(`only the last argument can be variadic '${r.name()}'`)}if(t.required&&t.defaultValue!==undefined&&t.parseArg===undefined){throw new Error(`a default value for a required argument is never used: '${t.name()}'`)}this._args.push(t);return this}addHelpCommand(t,r){if(t===false){this._addImplicitHelpCommand=false}else{this._addImplicitHelpCommand=true;if(typeof t==="string"){this._helpCommandName=t.split(" ")[0];this._helpCommandnameAndArgs=t}this._helpCommandDescription=r||this._helpCommandDescription}return this}_hasImplicitHelpCommand(){if(this._addImplicitHelpCommand===undefined){return this.commands.length&&!this._actionHandler&&!this._findCommand("help")}return this._addImplicitHelpCommand}hook(t,r){const i=["preSubcommand","preAction","postAction"];if(!i.includes(t)){throw new Error(`Unexpected value for event passed to hook : '${t}'.\nExpecting one of '${i.join("', '")}'`)}if(this._lifeCycleHooks[t]){this._lifeCycleHooks[t].push(r)}else{this._lifeCycleHooks[t]=[r]}return this}exitOverride(t){if(t){this._exitCallback=t}else{this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync"){throw t}else{}}}return this}_exit(t,r,i){if(this._exitCallback){this._exitCallback(new d(t,r,i))}c.exit(t)}action(t){const listener=r=>{const i=this._args.length;const o=r.slice(0,i);if(this._storeOptionsAsProperties){o[i]=this}else{o[i]=this.opts()}o.push(this);return t.apply(this,o)};this._actionHandler=listener;return this}createOption(t,r){return new g(t,r)}addOption(t){const r=t.name();const i=t.attributeName();if(t.negate){const r=t.long.replace(/^--no-/,"--");if(!this._findOption(r)){this.setOptionValueWithSource(i,t.defaultValue===undefined?true:t.defaultValue,"default")}}else if(t.defaultValue!==undefined){this.setOptionValueWithSource(i,t.defaultValue,"default")}this.options.push(t);const handleOptionValue=(r,o,a)=>{if(r==null&&t.presetArg!==undefined){r=t.presetArg}const l=this.getOptionValue(i);if(r!==null&&t.parseArg){try{r=t.parseArg(r,l)}catch(t){if(t.code==="commander.invalidArgument"){const r=`${o} ${t.message}`;this.error(r,{exitCode:t.exitCode,code:t.code})}throw t}}else if(r!==null&&t.variadic){r=t._concatValue(r,l)}if(r==null){if(t.negate){r=false}else if(t.isBoolean()||t.optional){r=true}else{r=""}}this.setOptionValueWithSource(i,r,a)};this.on("option:"+r,(r=>{const i=`error: option '${t.flags}' argument '${r}' is invalid.`;handleOptionValue(r,i,"cli")}));if(t.envVar){this.on("optionEnv:"+r,(r=>{const i=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;handleOptionValue(r,i,"env")}))}return this}_optionEx(t,r,i,o,a){if(typeof r==="object"&&r instanceof g){throw new Error("To add an Option object use addOption() instead of option() or requiredOption()")}const l=this.createOption(r,i);l.makeOptionMandatory(!!t.mandatory);if(typeof o==="function"){l.default(a).argParser(o)}else if(o instanceof RegExp){const t=o;o=(r,i)=>{const o=t.exec(r);return o?o[0]:i};l.default(a).argParser(o)}else{l.default(o)}return this.addOption(l)}option(t,r,i,o){return this._optionEx({},t,r,i,o)}requiredOption(t,r,i,o){return this._optionEx({mandatory:true},t,r,i,o)}combineFlagAndOptionalValue(t=true){this._combineFlagAndOptionalValue=!!t;return this}allowUnknownOption(t=true){this._allowUnknownOption=!!t;return this}allowExcessArguments(t=true){this._allowExcessArguments=!!t;return this}enablePositionalOptions(t=true){this._enablePositionalOptions=!!t;return this}passThroughOptions(t=true){this._passThroughOptions=!!t;if(!!this.parent&&t&&!this.parent._enablePositionalOptions){throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)")}return this}storeOptionsAsProperties(t=true){this._storeOptionsAsProperties=!!t;if(this.options.length){throw new Error("call .storeOptionsAsProperties() before adding options")}return this}getOptionValue(t){if(this._storeOptionsAsProperties){return this[t]}return this._optionValues[t]}setOptionValue(t,r){return this.setOptionValueWithSource(t,r,undefined)}setOptionValueWithSource(t,r,i){if(this._storeOptionsAsProperties){this[t]=r}else{this._optionValues[t]=r}this._optionValueSources[t]=i;return this}getOptionValueSource(t){return this._optionValueSources[t]}_prepareUserArgs(t,r){if(t!==undefined&&!Array.isArray(t)){throw new Error("first parameter to parse must be array or undefined")}r=r||{};if(t===undefined){t=c.argv;if(c.versions&&c.versions.electron){r.from="electron"}}this.rawArgs=t.slice();let i;switch(r.from){case undefined:case"node":this._scriptPath=t[1];i=t.slice(2);break;case"electron":if(c.defaultApp){this._scriptPath=t[1];i=t.slice(2)}else{i=t.slice(1)}break;case"user":i=t.slice(0);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);this._name=this._name||"program";return i}parse(t,r){const i=this._prepareUserArgs(t,r);this._parseCommand([],i);return this}async parseAsync(t,r){const i=this._prepareUserArgs(t,r);await this._parseCommand([],i);return this}_executeSubCommand(t,r){r=r.slice();let i=false;const o=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(t,r){const i=l.resolve(t,r);if(u.existsSync(i))return i;if(o.includes(l.extname(r)))return undefined;const a=o.find((t=>u.existsSync(`${i}${t}`)));if(a)return`${i}${a}`;return undefined}this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();let h=t._executableFile||`${this._name}-${t._name}`;let p=this._executableDir||"";if(this._scriptPath){let t;try{t=u.realpathSync(this._scriptPath)}catch(r){t=this._scriptPath}p=l.resolve(l.dirname(t),p)}if(p){let r=findFile(p,h);if(!r&&!t._executableFile&&this._scriptPath){const i=l.basename(this._scriptPath,l.extname(this._scriptPath));if(i!==this._name){r=findFile(p,`${i}-${t._name}`)}}h=r||h}i=o.includes(l.extname(h));let m;if(c.platform!=="win32"){if(i){r.unshift(h);r=incrementNodeInspectorPort(c.execArgv).concat(r);m=a.spawn(c.argv[0],r,{stdio:"inherit"})}else{m=a.spawn(h,r,{stdio:"inherit"})}}else{r.unshift(h);r=incrementNodeInspectorPort(c.execArgv).concat(r);m=a.spawn(c.execPath,r,{stdio:"inherit"})}if(!m.killed){const t=["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"];t.forEach((t=>{c.on(t,(()=>{if(m.killed===false&&m.exitCode===null){m.kill(t)}}))}))}const g=this._exitCallback;if(!g){m.on("close",c.exit.bind(c))}else{m.on("close",(()=>{g(new d(c.exitCode||0,"commander.executeSubCommandAsync","(close)"))}))}m.on("error",(r=>{if(r.code==="ENOENT"){const r=p?`searched for local subcommand relative to directory '${p}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory";const i=`'${h}' does not exist\n - if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${r}`;throw new Error(i)}else if(r.code==="EACCES"){throw new Error(`'${h}' not executable`)}if(!g){c.exit(1)}else{const t=new d(1,"commander.executeSubCommandAsync","(error)");t.nestedError=r;g(t)}}));this.runningCommand=m}_dispatchSubcommand(t,r,i){const o=this._findCommand(t);if(!o)this.help({error:true});let a;a=this._chainOrCallSubCommandHook(a,o,"preSubcommand");a=this._chainOrCall(a,(()=>{if(o._executableHandler){this._executeSubCommand(o,r.concat(i))}else{return o._parseCommand(r,i)}}));return a}_checkNumberOfArguments(){this._args.forEach(((t,r)=>{if(t.required&&this.args[r]==null){this.missingArgument(t.name())}}));if(this._args.length>0&&this._args[this._args.length-1].variadic){return}if(this.args.length>this._args.length){this._excessArguments(this.args)}}_processArguments(){const myParseArg=(t,r,i)=>{let o=r;if(r!==null&&t.parseArg){try{o=t.parseArg(r,i)}catch(i){if(i.code==="commander.invalidArgument"){const o=`error: command-argument value '${r}' is invalid for argument '${t.name()}'. ${i.message}`;this.error(o,{exitCode:i.exitCode,code:i.code})}throw i}}return o};this._checkNumberOfArguments();const t=[];this._args.forEach(((r,i)=>{let o=r.defaultValue;if(r.variadic){if(i<this.args.length){o=this.args.slice(i);if(r.parseArg){o=o.reduce(((t,i)=>myParseArg(r,i,t)),r.defaultValue)}}else if(o===undefined){o=[]}}else if(i<this.args.length){o=this.args[i];if(r.parseArg){o=myParseArg(r,o,r.defaultValue)}}t[i]=o}));this.processedArgs=t}_chainOrCall(t,r){if(t&&t.then&&typeof t.then==="function"){return t.then((()=>r()))}return r()}_chainOrCallHooks(t,r){let i=t;const o=[];getCommandAndParents(this).reverse().filter((t=>t._lifeCycleHooks[r]!==undefined)).forEach((t=>{t._lifeCycleHooks[r].forEach((r=>{o.push({hookedCommand:t,callback:r})}))}));if(r==="postAction"){o.reverse()}o.forEach((t=>{i=this._chainOrCall(i,(()=>t.callback(t.hookedCommand,this)))}));return i}_chainOrCallSubCommandHook(t,r,i){let o=t;if(this._lifeCycleHooks[i]!==undefined){this._lifeCycleHooks[i].forEach((t=>{o=this._chainOrCall(o,(()=>t(this,r)))}))}return o}_parseCommand(t,r){const i=this.parseOptions(r);this._parseOptionsEnv();this._parseOptionsImplied();t=t.concat(i.operands);r=i.unknown;this.args=t.concat(r);if(t&&this._findCommand(t[0])){return this._dispatchSubcommand(t[0],t.slice(1),r)}if(this._hasImplicitHelpCommand()&&t[0]===this._helpCommandName){if(t.length===1){this.help()}return this._dispatchSubcommand(t[1],[],[this._helpLongFlag])}if(this._defaultCommandName){outputHelpIfRequested(this,r);return this._dispatchSubcommand(this._defaultCommandName,t,r)}if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName){this.help({error:true})}outputHelpIfRequested(this,i.unknown);this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();const checkForUnknownOptions=()=>{if(i.unknown.length>0){this.unknownOption(i.unknown[0])}};const o=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions();this._processArguments();let i;i=this._chainOrCallHooks(i,"preAction");i=this._chainOrCall(i,(()=>this._actionHandler(this.processedArgs)));if(this.parent){i=this._chainOrCall(i,(()=>{this.parent.emit(o,t,r)}))}i=this._chainOrCallHooks(i,"postAction");return i}if(this.parent&&this.parent.listenerCount(o)){checkForUnknownOptions();this._processArguments();this.parent.emit(o,t,r)}else if(t.length){if(this._findCommand("*")){return this._dispatchSubcommand("*",t,r)}if(this.listenerCount("command:*")){this.emit("command:*",t,r)}else if(this.commands.length){this.unknownCommand()}else{checkForUnknownOptions();this._processArguments()}}else if(this.commands.length){checkForUnknownOptions();this.help({error:true})}else{checkForUnknownOptions();this._processArguments()}}_findCommand(t){if(!t)return undefined;return this.commands.find((r=>r._name===t||r._aliases.includes(t)))}_findOption(t){return this.options.find((r=>r.is(t)))}_checkForMissingMandatoryOptions(){for(let t=this;t;t=t.parent){t.options.forEach((r=>{if(r.mandatory&&t.getOptionValue(r.attributeName())===undefined){t.missingMandatoryOptionValue(r)}}))}}_checkForConflictingLocalOptions(){const t=this.options.filter((t=>{const r=t.attributeName();if(this.getOptionValue(r)===undefined){return false}return this.getOptionValueSource(r)!=="default"}));const r=t.filter((t=>t.conflictsWith.length>0));r.forEach((r=>{const i=t.find((t=>r.conflictsWith.includes(t.attributeName())));if(i){this._conflictingOption(r,i)}}))}_checkForConflictingOptions(){for(let t=this;t;t=t.parent){t._checkForConflictingLocalOptions()}}parseOptions(t){const r=[];const i=[];let o=r;const a=t.slice();function maybeOption(t){return t.length>1&&t[0]==="-"}let l=null;while(a.length){const t=a.shift();if(t==="--"){if(o===i)o.push(t);o.push(...a);break}if(l&&!maybeOption(t)){this.emit(`option:${l.name()}`,t);continue}l=null;if(maybeOption(t)){const r=this._findOption(t);if(r){if(r.required){const t=a.shift();if(t===undefined)this.optionMissingArgument(r);this.emit(`option:${r.name()}`,t)}else if(r.optional){let t=null;if(a.length>0&&!maybeOption(a[0])){t=a.shift()}this.emit(`option:${r.name()}`,t)}else{this.emit(`option:${r.name()}`)}l=r.variadic?r:null;continue}}if(t.length>2&&t[0]==="-"&&t[1]!=="-"){const r=this._findOption(`-${t[1]}`);if(r){if(r.required||r.optional&&this._combineFlagAndOptionalValue){this.emit(`option:${r.name()}`,t.slice(2))}else{this.emit(`option:${r.name()}`);a.unshift(`-${t.slice(2)}`)}continue}}if(/^--[^=]+=/.test(t)){const r=t.indexOf("=");const i=this._findOption(t.slice(0,r));if(i&&(i.required||i.optional)){this.emit(`option:${i.name()}`,t.slice(r+1));continue}}if(maybeOption(t)){o=i}if((this._enablePositionalOptions||this._passThroughOptions)&&r.length===0&&i.length===0){if(this._findCommand(t)){r.push(t);if(a.length>0)i.push(...a);break}else if(t===this._helpCommandName&&this._hasImplicitHelpCommand()){r.push(t);if(a.length>0)r.push(...a);break}else if(this._defaultCommandName){i.push(t);if(a.length>0)i.push(...a);break}}if(this._passThroughOptions){o.push(t);if(a.length>0)o.push(...a);break}o.push(t)}return{operands:r,unknown:i}}opts(){if(this._storeOptionsAsProperties){const t={};const r=this.options.length;for(let i=0;i<r;i++){const r=this.options[i].attributeName();t[r]=r===this._versionOptionName?this._version:this[r]}return t}return this._optionValues}optsWithGlobals(){return getCommandAndParents(this).reduce(((t,r)=>Object.assign(t,r.opts())),{})}error(t,r){this._outputConfiguration.outputError(`${t}\n`,this._outputConfiguration.writeErr);if(typeof this._showHelpAfterError==="string"){this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`)}else if(this._showHelpAfterError){this._outputConfiguration.writeErr("\n");this.outputHelp({error:true})}const i=r||{};const o=i.exitCode||1;const a=i.code||"commander.error";this._exit(o,a,t)}_parseOptionsEnv(){this.options.forEach((t=>{if(t.envVar&&t.envVar in c.env){const r=t.attributeName();if(this.getOptionValue(r)===undefined||["default","config","env"].includes(this.getOptionValueSource(r))){if(t.required||t.optional){this.emit(`optionEnv:${t.name()}`,c.env[t.envVar])}else{this.emit(`optionEnv:${t.name()}`)}}}}))}_parseOptionsImplied(){const t=new v(this.options);const hasCustomOptionValue=t=>this.getOptionValue(t)!==undefined&&!["default","implied"].includes(this.getOptionValueSource(t));this.options.filter((r=>r.implied!==undefined&&hasCustomOptionValue(r.attributeName())&&t.valueFromOption(this.getOptionValue(r.attributeName()),r))).forEach((t=>{Object.keys(t.implied).filter((t=>!hasCustomOptionValue(t))).forEach((r=>{this.setOptionValueWithSource(r,t.implied[r],"implied")}))}))}missingArgument(t){const r=`error: missing required argument '${t}'`;this.error(r,{code:"commander.missingArgument"})}optionMissingArgument(t){const r=`error: option '${t.flags}' argument missing`;this.error(r,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){const r=`error: required option '${t.flags}' not specified`;this.error(r,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,r){const findBestOptionFromValue=t=>{const r=t.attributeName();const i=this.getOptionValue(r);const o=this.options.find((t=>t.negate&&r===t.attributeName()));const a=this.options.find((t=>!t.negate&&r===t.attributeName()));if(o&&(o.presetArg===undefined&&i===false||o.presetArg!==undefined&&i===o.presetArg)){return o}return a||t};const getErrorMessage=t=>{const r=findBestOptionFromValue(t);const i=r.attributeName();const o=this.getOptionValueSource(i);if(o==="env"){return`environment variable '${r.envVar}'`}return`option '${r.flags}'`};const i=`error: ${getErrorMessage(t)} cannot be used with ${getErrorMessage(r)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let r="";if(t.startsWith("--")&&this._showSuggestionAfterError){let i=[];let o=this;do{const t=o.createHelp().visibleOptions(o).filter((t=>t.long)).map((t=>t.long));i=i.concat(t);o=o.parent}while(o&&!o._enablePositionalOptions);r=b(t,i)}const i=`error: unknown option '${t}'${r}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;const r=this._args.length;const i=r===1?"":"s";const o=this.parent?` for '${this.name()}'`:"";const a=`error: too many arguments${o}. Expected ${r} argument${i} but got ${t.length}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){const t=this.args[0];let r="";if(this._showSuggestionAfterError){const i=[];this.createHelp().visibleCommands(this).forEach((t=>{i.push(t.name());if(t.alias())i.push(t.alias())}));r=b(t,i)}const i=`error: unknown command '${t}'${r}`;this.error(i,{code:"commander.unknownCommand"})}version(t,r,i){if(t===undefined)return this._version;this._version=t;r=r||"-V, --version";i=i||"output the version number";const o=this.createOption(r,i);this._versionOptionName=o.attributeName();this.options.push(o);this.on("option:"+o.name(),(()=>{this._outputConfiguration.writeOut(`${t}\n`);this._exit(0,"commander.version",t)}));return this}description(t,r){if(t===undefined&&r===undefined)return this._description;this._description=t;if(r){this._argsDescription=r}return this}summary(t){if(t===undefined)return this._summary;this._summary=t;return this}alias(t){if(t===undefined)return this._aliases[0];let r=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler){r=this.commands[this.commands.length-1]}if(t===r._name)throw new Error("Command alias can't be the same as its name");r._aliases.push(t);return this}aliases(t){if(t===undefined)return this._aliases;t.forEach((t=>this.alias(t)));return this}usage(t){if(t===undefined){if(this._usage)return this._usage;const t=this._args.map((t=>p(t)));return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this._args.length?t:[]).join(" ")}this._usage=t;return this}name(t){if(t===undefined)return this._name;this._name=t;return this}nameFromFilename(t){this._name=l.basename(t,l.extname(t));return this}executableDir(t){if(t===undefined)return this._executableDir;this._executableDir=t;return this}helpInformation(t){const r=this.createHelp();if(r.helpWidth===undefined){r.helpWidth=t&&t.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()}return r.formatHelp(this,r)}_getHelpContext(t){t=t||{};const r={error:!!t.error};let i;if(r.error){i=t=>this._outputConfiguration.writeErr(t)}else{i=t=>this._outputConfiguration.writeOut(t)}r.write=t.write||i;r.command=this;return r}outputHelp(t){let r;if(typeof t==="function"){r=t;t=undefined}const i=this._getHelpContext(t);getCommandAndParents(this).reverse().forEach((t=>t.emit("beforeAllHelp",i)));this.emit("beforeHelp",i);let o=this.helpInformation(i);if(r){o=r(o);if(typeof o!=="string"&&!Buffer.isBuffer(o)){throw new Error("outputHelp callback must return a string or a Buffer")}}i.write(o);this.emit(this._helpLongFlag);this.emit("afterHelp",i);getCommandAndParents(this).forEach((t=>t.emit("afterAllHelp",i)))}helpOption(t,r){if(typeof t==="boolean"){this._hasHelpOption=t;return this}this._helpFlags=t||this._helpFlags;this._helpDescription=r||this._helpDescription;const i=y(this._helpFlags);this._helpShortFlag=i.shortFlag;this._helpLongFlag=i.longFlag;return this}help(t){this.outputHelp(t);let r=c.exitCode||0;if(r===0&&t&&typeof t!=="function"&&t.error){r=1}this._exit(r,"commander.help","(outputHelp)")}addHelpText(t,r){const i=["beforeAll","before","after","afterAll"];if(!i.includes(t)){throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${i.join("', '")}'`)}const o=`${t}Help`;this.on(o,(t=>{let i;if(typeof r==="function"){i=r({error:t.error,command:t.command})}else{i=r}if(i){t.write(`${i}\n`)}}));return this}}function outputHelpIfRequested(t,r){const i=t._hasHelpOption&&r.find((r=>r===t._helpLongFlag||r===t._helpShortFlag));if(i){t.outputHelp();t._exit(0,"commander.helpDisplayed","(outputHelp)")}}function incrementNodeInspectorPort(t){return t.map((t=>{if(!t.startsWith("--inspect")){return t}let r;let i="127.0.0.1";let o="9229";let a;if((a=t.match(/^(--inspect(-brk)?)$/))!==null){r=a[1]}else if((a=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null){r=a[1];if(/^\d+$/.test(a[3])){o=a[3]}else{i=a[3]}}else if((a=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null){r=a[1];i=a[3];o=a[4]}if(r&&o!=="0"){return`${r}=${i}:${parseInt(o)+1}`}return t}))}function getCommandAndParents(t){const r=[];for(let i=t;i;i=i.parent){r.push(i)}return r}r.Command=Command},9027:(t,r)=>{class CommanderError extends Error{constructor(t,r,i){super(i);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name;this.code=r;this.exitCode=t;this.nestedError=undefined}}class InvalidArgumentError extends CommanderError{constructor(t){super(1,"commander.invalidArgument",t);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name}}r.CommanderError=CommanderError;r.InvalidArgumentError=InvalidArgumentError},9164:(t,r,i)=>{const{humanReadableArgName:o}=i(4079);class Help{constructor(){this.helpWidth=undefined;this.sortSubcommands=false;this.sortOptions=false}visibleCommands(t){const r=t.commands.filter((t=>!t._hidden));if(t._hasImplicitHelpCommand()){const[,i,o]=t._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);const a=t.createCommand(i).helpOption(false);a.description(t._helpCommandDescription);if(o)a.arguments(o);r.push(a)}if(this.sortSubcommands){r.sort(((t,r)=>t.name().localeCompare(r.name())))}return r}visibleOptions(t){const r=t.options.filter((t=>!t.hidden));const i=t._hasHelpOption&&t._helpShortFlag&&!t._findOption(t._helpShortFlag);const o=t._hasHelpOption&&!t._findOption(t._helpLongFlag);if(i||o){let a;if(!i){a=t.createOption(t._helpLongFlag,t._helpDescription)}else if(!o){a=t.createOption(t._helpShortFlag,t._helpDescription)}else{a=t.createOption(t._helpFlags,t._helpDescription)}r.push(a)}if(this.sortOptions){const getSortKey=t=>t.short?t.short.replace(/^-/,""):t.long.replace(/^--/,"");r.sort(((t,r)=>getSortKey(t).localeCompare(getSortKey(r))))}return r}visibleArguments(t){if(t._argsDescription){t._args.forEach((r=>{r.description=r.description||t._argsDescription[r.name()]||""}))}if(t._args.find((t=>t.description))){return t._args}return[]}subcommandTerm(t){const r=t._args.map((t=>o(t))).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,r){return r.visibleCommands(t).reduce(((t,i)=>Math.max(t,r.subcommandTerm(i).length)),0)}longestOptionTermLength(t,r){return r.visibleOptions(t).reduce(((t,i)=>Math.max(t,r.optionTerm(i).length)),0)}longestArgumentTermLength(t,r){return r.visibleArguments(t).reduce(((t,i)=>Math.max(t,r.argumentTerm(i).length)),0)}commandUsage(t){let r=t._name;if(t._aliases[0]){r=r+"|"+t._aliases[0]}let i="";for(let r=t.parent;r;r=r.parent){i=r.name()+" "+i}return i+r+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){const r=[];if(t.argChoices){r.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){const i=t.required||t.optional||t.isBoolean()&&typeof t.defaultValue==="boolean";if(i){r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}}if(t.presetArg!==undefined&&t.optional){r.push(`preset: ${JSON.stringify(t.presetArg)}`)}if(t.envVar!==undefined){r.push(`env: ${t.envVar}`)}if(r.length>0){return`${t.description} (${r.join(", ")})`}return t.description}argumentDescription(t){const r=[];if(t.argChoices){r.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){r.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}if(r.length>0){const i=`(${r.join(", ")})`;if(t.description){return`${t.description} ${i}`}return i}return t.description}formatHelp(t,r){const i=r.padWidth(t,r);const o=r.helpWidth||80;const a=2;const l=2;function formatItem(t,u){if(u){const c=`${t.padEnd(i+l)}${u}`;return r.wrap(c,o-a,i+l)}return t}function formatList(t){return t.join("\n").replace(/^/gm," ".repeat(a))}let u=[`Usage: ${r.commandUsage(t)}`,""];const c=r.commandDescription(t);if(c.length>0){u=u.concat([c,""])}const h=r.visibleArguments(t).map((t=>formatItem(r.argumentTerm(t),r.argumentDescription(t))));if(h.length>0){u=u.concat(["Arguments:",formatList(h),""])}const p=r.visibleOptions(t).map((t=>formatItem(r.optionTerm(t),r.optionDescription(t))));if(p.length>0){u=u.concat(["Options:",formatList(p),""])}const d=r.visibleCommands(t).map((t=>formatItem(r.subcommandTerm(t),r.subcommandDescription(t))));if(d.length>0){u=u.concat(["Commands:",formatList(d),""])}return u.join("\n")}padWidth(t,r){return Math.max(r.longestOptionTermLength(t,r),r.longestSubcommandTermLength(t,r),r.longestArgumentTermLength(t,r))}wrap(t,r,i,o=40){if(t.match(/[\n]\s+/))return t;const a=r-i;if(a<o)return t;const l=t.slice(0,i);const u=t.slice(i);const c=" ".repeat(i);const h=new RegExp(".{1,"+(a-1)+"}([\\s​]|$)|[^\\s​]+?([\\s​]|$)","g");const p=u.match(h)||[];return l+p.map(((t,r)=>{if(t.slice(-1)==="\n"){t=t.slice(0,t.length-1)}return(r>0?c:"")+t.trimRight()})).join("\n")}}r.Help=Help},5205:(t,r,i)=>{const{InvalidArgumentError:o}=i(9027);class Option{constructor(t,r){this.flags=t;this.description=r||"";this.required=t.includes("<");this.optional=t.includes("[");this.variadic=/\w\.\.\.[>\]]$/.test(t);this.mandatory=false;const i=splitOptionFlags(t);this.short=i.shortFlag;this.long=i.longFlag;this.negate=false;if(this.long){this.negate=this.long.startsWith("--no-")}this.defaultValue=undefined;this.defaultValueDescription=undefined;this.presetArg=undefined;this.envVar=undefined;this.parseArg=undefined;this.hidden=false;this.argChoices=undefined;this.conflictsWith=[];this.implied=undefined}default(t,r){this.defaultValue=t;this.defaultValueDescription=r;return this}preset(t){this.presetArg=t;return this}conflicts(t){this.conflictsWith=this.conflictsWith.concat(t);return this}implies(t){this.implied=Object.assign(this.implied||{},t);return this}env(t){this.envVar=t;return this}argParser(t){this.parseArg=t;return this}makeOptionMandatory(t=true){this.mandatory=!!t;return this}hideHelp(t=true){this.hidden=!!t;return this}_concatValue(t,r){if(r===this.defaultValue||!Array.isArray(r)){return[t]}return r.concat(t)}choices(t){this.argChoices=t.slice();this.parseArg=(t,r)=>{if(!this.argChoices.includes(t)){throw new o(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,r)}return t};return this}name(){if(this.long){return this.long.replace(/^--/,"")}return this.short.replace(/^-/,"")}attributeName(){return camelcase(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class DualOptions{constructor(t){this.positiveOptions=new Map;this.negativeOptions=new Map;this.dualOptions=new Set;t.forEach((t=>{if(t.negate){this.negativeOptions.set(t.attributeName(),t)}else{this.positiveOptions.set(t.attributeName(),t)}}));this.negativeOptions.forEach(((t,r)=>{if(this.positiveOptions.has(r)){this.dualOptions.add(r)}}))}valueFromOption(t,r){const i=r.attributeName();if(!this.dualOptions.has(i))return true;const o=this.negativeOptions.get(i).presetArg;const a=o!==undefined?o:false;return r.negate===(a===t)}}function camelcase(t){return t.split("-").reduce(((t,r)=>t+r[0].toUpperCase()+r.slice(1)))}function splitOptionFlags(t){let r;let i;const o=t.split(/[ |,]+/);if(o.length>1&&!/^[[<]/.test(o[1]))r=o.shift();i=o.shift();if(!r&&/^-[^-]$/.test(i)){r=i;i=undefined}return{shortFlag:r,longFlag:i}}r.Option=Option;r.splitOptionFlags=splitOptionFlags;r.DualOptions=DualOptions},211:(t,r)=>{const i=3;function editDistance(t,r){if(Math.abs(t.length-r.length)>i)return Math.max(t.length,r.length);const o=[];for(let r=0;r<=t.length;r++){o[r]=[r]}for(let t=0;t<=r.length;t++){o[0][t]=t}for(let i=1;i<=r.length;i++){for(let a=1;a<=t.length;a++){let l=1;if(t[a-1]===r[i-1]){l=0}else{l=1}o[a][i]=Math.min(o[a-1][i]+1,o[a][i-1]+1,o[a-1][i-1]+l);if(a>1&&i>1&&t[a-1]===r[i-2]&&t[a-2]===r[i-1]){o[a][i]=Math.min(o[a][i],o[a-2][i-2]+1)}}}return o[t.length][r.length]}function suggestSimilar(t,r){if(!r||r.length===0)return"";r=Array.from(new Set(r));const o=t.startsWith("--");if(o){t=t.slice(2);r=r.map((t=>t.slice(2)))}let a=[];let l=i;const u=.4;r.forEach((r=>{if(r.length<=1)return;const i=editDistance(t,r);const o=Math.max(t.length,r.length);const c=(o-i)/o;if(c>u){if(i<l){l=i;a=[r]}else if(i===l){a.push(r)}}}));a.sort(((t,r)=>t.localeCompare(r)));if(o){a=a.map((t=>`--${t}`))}if(a.length>1){return`\n(Did you mean one of ${a.join(", ")}?)`}if(a.length===1){return`\n(Did you mean ${a[0]}?)`}return""}r.suggestSimilar=suggestSimilar}};var __webpack_module_cache__={};function __nccwpck_require__(t){var r=__webpack_module_cache__[t];if(r!==undefined){return r.exports}var i=__webpack_module_cache__[t]={exports:{}};var o=true;try{__webpack_modules__[t].call(i.exports,i,i.exports,__nccwpck_require__);o=false}finally{if(o)delete __webpack_module_cache__[t]}return i.exports}(()=>{__nccwpck_require__.n=t=>{var r=t&&t.__esModule?()=>t["default"]:()=>t;__nccwpck_require__.d(r,{a:r});return r}})();(()=>{__nccwpck_require__.d=(t,r)=>{for(var i in r){if(__nccwpck_require__.o(r,i)&&!__nccwpck_require__.o(t,i)){Object.defineProperty(t,i,{enumerable:true,get:r[i]})}}}})();(()=>{__nccwpck_require__.o=(t,r)=>Object.prototype.hasOwnProperty.call(t,r)})();(()=>{__nccwpck_require__.r=t=>{if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(t,"__esModule",{value:true})}})();if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var __webpack_exports__=__nccwpck_require__(371);module.exports=__webpack_exports__})();
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@platforms/web",
3
- "version": "0.8.8",
3
+ "version": "0.8.9",
4
4
  "private": true,
5
5
  "dependencies": {
6
6
  "@hyperbook/element-alert": "0.1.8",
@@ -22,7 +22,7 @@
22
22
  "@hyperbook/shell": "0.1.3",
23
23
  "@hyperbook/store": "0.1.2",
24
24
  "@hyperbook/styles": "0.1.8",
25
- "@hyperbook/toc": "0.1.0",
25
+ "@hyperbook/toc": "0.2.0",
26
26
  "gray-matter": "4.0.3",
27
27
  "next": "12.3.4",
28
28
  "react": "18.2.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hyperbook",
3
- "version": "0.8.8",
3
+ "version": "0.8.9",
4
4
  "author": "Mike Barkmin",
5
5
  "homepage": "https://github.com/openpatch/hyperbook#readme",
6
6
  "license": "MIT",
@@ -44,7 +44,7 @@
44
44
  "rimraf": "3.0.2",
45
45
  "tar": "6.1.12",
46
46
  "update-check": "1.5.4",
47
- "@platforms/web": "0.8.8"
47
+ "@platforms/web": "0.8.9"
48
48
  },
49
49
  "dependencies": {
50
50
  "@hyperbook/fs": "0.1.1",