ts-pantry 0.10.11 → 0.10.13
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/bin/cli.js +9 -8
- package/dist/chunk-0xfx7txg.js +1 -0
- package/dist/{chunk-22yfeqn3.js → chunk-4qa9dfjs.js} +3 -3
- package/dist/chunk-ax2wz06f.js +313 -0
- package/dist/{chunk-xzyv7d5n.js → chunk-byp71bz1.js} +1 -1
- package/dist/{chunk-58tv7cc0.js → chunk-c0pn1x0j.js} +1 -1
- package/dist/chunk-c7csvans.js +2 -0
- package/dist/{chunk-0knvy8da.js → chunk-dnw4x7bh.js} +1 -1
- package/dist/{chunk-t3d44dpr.js → chunk-hk7ns20y.js} +1 -1
- package/dist/{chunk-2pdwb50x.js → chunk-jkfbbcs7.js} +1 -1
- package/dist/{chunk-6e7x6std.js → chunk-py3ymxjf.js} +1 -1
- package/dist/{chunk-f1bj0d0n.js → chunk-qyfapvcb.js} +2 -2
- package/dist/chunk-sa2nn9dg.js +1 -0
- package/dist/chunk-tbgzzd68.js +1 -0
- package/dist/{chunk-9h0h2rjw.js → chunk-wavfc3dt.js} +1 -1
- package/dist/{chunk-jrr4wpkp.js → chunk-wcn78wgj.js} +1 -1
- package/dist/{chunk-3zr85kfx.js → chunk-wzw3xbn2.js} +2 -2
- package/dist/{chunk-rvwbbg4d.js → chunk-zg4d4yqd.js} +1 -1
- package/dist/packages/anthropic.com/claude-code.d.ts +1 -1
- package/dist/packages/apps/cursorcom.d.ts +1 -1
- package/dist/packages/apps/discordcom.d.ts +1 -1
- package/dist/packages/apps/raycastcom.d.ts +1 -1
- package/dist/packages/apps/rectangleapp.d.ts +1 -1
- package/dist/packages/apps/zeddev.d.ts +1 -1
- package/dist/packages/aux4io.d.ts +1 -1
- package/dist/packages/certbotefforg.d.ts +1 -1
- package/dist/packages/cnqueryio.d.ts +1 -1
- package/dist/packages/denoland.d.ts +1 -1
- package/dist/packages/depotdev.d.ts +1 -1
- package/dist/packages/dozzledev.d.ts +1 -1
- package/dist/packages/dprintdev.d.ts +1 -1
- package/dist/packages/flyio.d.ts +1 -1
- package/dist/packages/github.com/ggerganov/llama.cpp.d.ts +1 -1
- package/dist/packages/github.com/shaka-project/shaka-packager.d.ts +1 -1
- package/dist/packages/libgeosorg.d.ts +1 -1
- package/dist/packages/materializecom.d.ts +1 -1
- package/dist/packages/misejdxdev.d.ts +1 -1
- package/dist/packages/nginxorg.d.ts +1 -1
- package/dist/packages/ohmyposhdev.d.ts +1 -1
- package/dist/packages/opencodeai.d.ts +1 -1
- package/dist/packages/openshiftcom.d.ts +1 -1
- package/dist/packages/pnpmio.d.ts +1 -1
- package/dist/packages/prefixdev.d.ts +1 -1
- package/dist/packages/projenio.d.ts +1 -1
- package/dist/packages/rucio.cern.ch/rucio-client.d.ts +1 -1
- package/dist/packages/traefikio.d.ts +1 -1
- package/dist/packages/tursotech.d.ts +1 -1
- package/dist/packages/werfio.d.ts +1 -1
- package/dist/packages/ziglangorg.d.ts +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/testing/index.js +1 -0
- package/package.json +4 -3
- package/dist/chunk-ax48nzbg.js +0 -1
- package/dist/chunk-exna5ztv.js +0 -2
- package/dist/chunk-wk0mrxvx.js +0 -1
- package/dist/chunk-zb7ytjww.js +0 -313
package/dist/bin/cli.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{Da as c6,Ea as n6,Ga as l6,Ja as p6,L as C6,La as r6,M as S6,N as v6,P as y6,V as k6,W as h6,X as _6,Y as g6,Z as f6,ba as G6,ca as u6,da as i6}from"../chunk-ax2wz06f.js";import"../chunk-c0pn1x0j.js";import"../chunk-sa2nn9dg.js";import{kb as p,lb as m6,nb as X6,ob as r,tb as d6,xb as U6}from"../chunk-4qa9dfjs.js";import"../chunk-jkfbbcs7.js";import"../chunk-qyfapvcb.js";import{Pb as l,Qb as q6,Rb as J6}from"../chunk-py3ymxjf.js";import"../chunk-wzw3xbn2.js";import"../chunk-c7csvans.js";import{jc as P6,kc as Q4}from"../chunk-dnw4x7bh.js";import{oc as h}from"../chunk-ghzc37v7.js";import V from"node:fs";import B from"node:path";import H from"node:process";import{existsSync as t6}from"node:fs";import a from"node:fs/promises";import K6 from"node:os";import s from"node:path";import k from"node:process";import{EventEmitter as o6}from"node:events";import v from"node:process";import V6 from"node:process";import z6 from"node:process";import u from"node:process";import f from"node:process";import L6 from"node:tty";import fz,{stdin as E4,stdout as x4}from"node:process";import M6,{stdin as uz,stdout as iz}from"node:process";import cz from"node:readline";class B6{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let z=K6.homedir(),$=s.join(z,".config","clapp");this.configPath=s.join($,"telemetry.json")}async isEnabled(){if(k.env.DO_NOT_TRACK==="1"||k.env.DO_NOT_TRACK==="true")return!1;if(k.env.NO_TELEMETRY==="1"||k.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let z=await this.loadConfig();if(z.enabled=!0,!z.userId)z.userId=this.generateUserId();await this.saveConfig(z)}async disable(){let z=await this.loadConfig();z.enabled=!1,await this.saveConfig(z)}async track(z,$){if(!await this.isEnabled())return;let Z={event:z,...$,timestamp:Date.now(),platform:K6.platform(),nodeVersion:k.version};if(this.events.push(Z),this.events.length>=10)await this.send()}async trackCommand(z,$){await this.track("command",{command:z,duration:$})}async trackError(z,$){await this.track("error",{error:z,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(z){return new Promise(($)=>setTimeout($,z))}async status(){let z=await this.loadConfig();return{enabled:z.enabled,doNotTrack:k.env.DO_NOT_TRACK==="1"||k.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(t6(this.configPath)){let z=await a.readFile(this.configPath,"utf-8");return this.config=JSON.parse(z),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(z){this.config=z;try{let $=s.dirname(this.configPath);await a.mkdir($,{recursive:!0}),await a.writeFile(this.configPath,JSON.stringify(z,null,2),"utf-8")}catch{}}generateUserId(){let z=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${z}-${$}`}}var V4=new B6;function e6(z,$={}){let Q={_:[]},Z=$.alias||{},Y=new Set($.boolean||[]),q={};for(let U of Object.keys(Z))for(let X of Z[U])q[X]=U;for(let U of Y)if(Z[U])for(let X of Z[U])Y.add(X);function J(U,X){let G=q[U]||U;if(Q[G]=X,Z[G])for(let K of Z[G])Q[K]=X;if(q[U]&&Z[q[U]])for(let K of Z[q[U]])Q[K]=X;Q[U]=X}for(let U=0;U<z.length;U++){let X=z[U];if(X==="--"){Q._.push(...z.slice(U+1));break}if(X.startsWith("--")){let G=X.indexOf("=");if(G!==-1){let K=X.slice(2,G),W=X.slice(G+1);J(K,W)}else{let K=X.slice(2);if(K.startsWith("no-")){let j=K.slice(3);J(j,!1);continue}let W=q[K]||K;if(Y.has(W)||Y.has(K))J(K,!0);else{let j=z[U+1];if(j!==void 0&&!j.startsWith("-"))J(K,j),U++;else J(K,!0)}}}else if(X.startsWith("-")&&X.length>1){let G=X.slice(1);for(let K=0;K<G.length;K++){let W=G[K],j=q[W]||W;if(K===G.length-1&&!Y.has(j)&&!Y.has(W)){let F=z[U+1];if(F!==void 0&&!F.startsWith("-"))J(W,F),U++;else J(W,!0)}else J(W,!0)}}else Q._.push(X)}return Q}function e(z){return z.replace(/[<[].+/,"").trim()}function zz(z){let $=/<([^>]+)>/g,Q=/\[([^\]]+)\]/g,Z=[],Y=(U)=>{let X=!1,G=U[1];if(G.startsWith("..."))G=G.slice(3),X=!0;return{required:U[0].startsWith("<"),value:G,variadic:X}},q;while(q=$.exec(z))Z.push(Y(q));let J;while(J=Q.exec(z))Z.push(Y(J));return Z}function $z(z){let $={alias:{},boolean:[]};for(let[Q,Z]of z.entries()){if(Z.names.length>1)$.alias[Z.names[0]]=Z.names.slice(1);if(Z.isBoolean)if(Z.negated){if(!z.some((q,J)=>{return J!==Q&&q.names.some((U)=>Z.names.includes(U))&&typeof q.required==="boolean"}))$.boolean.push(Z.names[0])}else $.boolean.push(Z.names[0])}return $}function F6(z){return z.reduce(($,Q)=>$.length>=Q.length?$:Q,"")}function t(z,$){return z.length>=$?z:`${z}${" ".repeat($-z.length)}`}function Qz(z){return z.replace(/([a-z])-([a-z])/g,($,Q,Z)=>{return Q+Z.toUpperCase()})}function Zz(z,$,Q){let Z=0,Y=$.length,q=z,J;for(;Z<Y;++Z)J=q[$[Z]],q=q[$[Z]]=Z===Y-1?Q:J!=null?J:!!~$[Z+1].indexOf(".")||!(+$[Z+1]>-1)?{}:[]}function Yz(z,$){for(let Q of Object.keys($)){let Z=$[Q];if(Z.shouldTransform){if(z[Q]=Array.prototype.concat.call([],z[Q]),typeof Z.transformFunction==="function")z[Q]=z[Q].map(Z.transformFunction)}}}function qz(z){let $=/([^\\/]+)$/.exec(z);return $?$[1]:""}function N6(z){return z.split(".").map(($,Q)=>{return Q===0?Qz($):$}).join(".")}class d extends Error{exitCode=2;isUsageError=!0;constructor(z){super(z);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(z).stack}format(z=!1){if(z&&this.stack)return`${this.message}
|
|
2
3
|
|
|
3
4
|
Stack trace:
|
|
4
5
|
${this.stack}`;return this.message}}function Jz(){let{env:z}=V6,{TERM:$,TERM_PROGRAM:Q}=z;if(V6.platform!=="win32")return $!=="linux";return Boolean(z.WT_SESSION)||Boolean(z.TERMINUS_SUBLIME)||z.ConEmuTask==="{cmd::Cmder}"||Q==="Terminus-Sublime"||Q==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||z.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var n="\x1B",x=`${n}[`;var S={to(z,$){if(!$)return`${x}${z+1}G`;return`${x}${$+1};${z+1}H`},move(z,$){let Q="";if(z<0)Q+=`${x}${-z}D`;else if(z>0)Q+=`${x}${z}C`;if($<0)Q+=`${x}${-$}A`;else if($>0)Q+=`${x}${$}B`;return Q},up:(z=1)=>`${x}${z}A`,down:(z=1)=>`${x}${z}B`,forward:(z=1)=>`${x}${z}C`,backward:(z=1)=>`${x}${z}D`,nextLine:(z=1)=>`${x}E`.repeat(z),prevLine:(z=1)=>`${x}F`.repeat(z),left:`${x}G`,hide:`${x}?25l`,show:`${x}?25h`,save:`${n}7`,restore:`${n}8`};var o={screen:`${x}2J`,up:(z=1)=>`${x}1J`.repeat(z),down:(z=1)=>`${x}J`.repeat(z),line:`${x}2K`,lineEnd:`${x}K`,lineStart:`${x}1K`,lines(z){let $="";for(let Q=0;Q<z;Q++)$+=this.line+(Q<z-1?S.up():"");if(z)$+=S.left;return $}},w4={screen:`${n}c`};function Xz(z,$){let Q=[];for(let Z=0;Z<=$.length;Z++)Q[Z]=[Z];for(let Z=0;Z<=z.length;Z++)Q[0][Z]=Z;for(let Z=1;Z<=$.length;Z++)for(let Y=1;Y<=z.length;Y++)if($.charAt(Z-1)===z.charAt(Y-1))Q[Z][Y]=Q[Z-1][Y-1];else Q[Z][Y]=Math.min(Q[Z-1][Y-1]+1,Q[Z][Y-1]+1,Q[Z-1][Y]+1);return Q[$.length][z.length]}function b6(z,$,Q=2,Z=3){return $.map((Y)=>({cmd:Y,distance:Xz(z,Y)})).filter(({distance:Y})=>Y<=Q).sort((Y,q)=>Y.distance-q.distance).slice(0,Z).map(({cmd:Y})=>Y)}class D6{rawName;description;name;names;isBoolean;required;config;negated;constructor(z,$,Q){if(this.rawName=z,this.description=$,this.config=Object.assign({},Q),z=z.replace(/\.\*/g,""),this.negated=!1,this.names=e(z).split(",").map((Z)=>{let Y=Z.trim().replace(/^-{1,2}/,"");if(Y.startsWith("no-"))this.negated=!0,Y=Y.replace(/^no-/,"");return N6(Y)}).sort((Z,Y)=>Z.length>Y.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(z.includes("<"))this.required=!0;else if(z.includes("["))this.required=!1;else this.isBoolean=!0}}var O4=z6.argv,Uz=`${z6.platform}-${z6.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,W6=u.argv,Gz=`${u.platform}-${u.arch} node-${u.version}`;class $6{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(z,$,Q,Z){this.rawName=z,this.description=$,this.config=Q,this.cli=Z,this.options=[],this.aliasNames=[],this.name=e(z);let Y=e(z),q=Y.indexOf(":");if(q>0)this.namespace=Y.substring(0,q),this.name=Y.substring(q+1);if(this.args=zz(z),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Q)this.config={}}usage(z){return this.usageText=z,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(z,$="-v, --version"){return this.versionNumber=z,this.option($,"Display version number"),this}example(z){return this.examples.push(z),this}option(z,$,Q){let Z=new D6(z,$,Q);return this.options.push(Z),this}alias(z){return this.aliasNames.push(z),this}action(z){return this.commandAction=z,this}before(z){return this.beforeHooks.push(z),this}after(z){return this.afterHooks.push(z),this}use(z){return this.middleware.push(z),this}isMatched(z){if(this.aliasNames.includes(z))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===z;return this.name===z}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof Q6}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(z){return z=z.split(".")[0],!!this.options.find(($)=>{return $.names.includes(z)})}outputHelp(){let{name:z,commands:$}=this.cli,{versionNumber:Q,options:Z,helpCallback:Y}=this.cli.globalCommand,q=[{body:`${z}${Q?`/${Q}`:""}`}];if(q.push({title:"Usage",body:` $ ${z} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let X=F6($.map((F)=>F.rawName)),G=new Map,K=[];for(let F of $)if(F.namespace){if(!G.has(F.namespace))G.set(F.namespace,[]);G.get(F.namespace).push(F)}else K.push(F);let W="";if(K.length>0)W+=K.map((F)=>{return` ${t(F.rawName,X.length)} ${F.description}`}).join(`
|
|
@@ -36,7 +37,7 @@ Run \`${this.name??"cli"} --help\` for usage.`;v.stderr.write(`${q}${Y}${J}
|
|
|
36
37
|
`).length-1;this.output.write(S.move(-999,z*-1))}render(){let z=O6(this._render(this)??"",M6.stdout.columns,{hard:!0,trim:!1});if(z===this._prevFrame)return;if(this.state==="initial")this.output.write(S.hide);else{let $=dz(this._prevFrame,z);if(this.restoreCursor(),$&&$?.length===1){let Q=$[0];this.output.write(S.move(0,Q)),this.output.write(o.lines(1));let Z=z.split(`
|
|
37
38
|
`);this.output.write(Z[Q]),this._prevFrame=z,this.output.write(S.move(0,Z.length-Q-1));return}if($&&$?.length>1){let Q=$[0];this.output.write(S.move(0,Q)),this.output.write(o.down());let Y=z.split(`
|
|
38
39
|
`).slice(Q);this.output.write(Y.join(`
|
|
39
|
-
`)),this._prevFrame=z;return}this.output.write(o.down())}if(this.output.write(z),this.state==="initial")this.state="active";this._prevFrame=z}}function pz(z,$){if(z===void 0)return 0;if($.length===0)return 0;let Z=$.findIndex((Y)=>Y.value===z);return Z!==-1?Z:0}function rz(z,$){return($.label??String($.value)).toLowerCase().includes(z.toLowerCase())}function az(z,$){if(!$)return;if(z)return $;return $[0]}class sz extends Y6{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#z=0;#Q="";#Z;#$;get cursor(){return this.#z}get userInputWithCursor(){if(!this.userInput)return i.inverse(i.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let z=this.userInput.slice(0,this._cursor),[$,...Q]=this.userInput.slice(this._cursor);return`${z}${i.inverse($)}${Q.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(z){super(z);this.#$=z.options;let $=this.options;this.filteredOptions=[...$],this.multiple=z.multiple===!0,this.#Z=z.filter??rz;let Q;if(z.initialValue&&Array.isArray(z.initialValue))if(this.multiple)Q=z.initialValue;else Q=z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Q=[this.options[0].value];if(Q)for(let Z of Q){let Y=$.findIndex((q)=>q.value===Z);if(Y!==-1)this.toggleSelected(Z),this.#z=Y}this.focusedValue=this.options[this.#z]?.value,this.on("key",(Z,Y)=>this.#Y(Z,Y)),this.on("userInput",(Z)=>this.#q(Z))}_isActionKey(z,$){return z==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&z!==void 0&&z!==""}#Y(z,$){let Q=$.name==="up",Z=$.name==="down",Y=$.name==="return";if(Q||Z){if(this.#z=Math.max(0,Math.min(this.#z+(Q?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Y)this.value=az(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(z))this.selectedValues=this.selectedValues.filter(($)=>$!==z);else this.selectedValues=[...this.selectedValues,z];else this.selectedValues=[z]}#q(z){if(z!==this.#Q){this.#Q=z;let $=this.options;if(z)this.filteredOptions=$.filter((Q)=>this.#Z(z,Q));else this.filteredOptions=[...$];if(this.#z=pz(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class tz extends Y6{options;cursor=0;#z;getGroupItems(z){return this.options.filter(($)=>$.group===z)}isGroupSelected(z){let $=this.getGroupItems(z),Q=this.value;if(Q===void 0)return!1;return $.every((Z)=>Q.includes(Z.value))}toggleValue(){let z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(z.group===!0){let $=String(z.value),Q=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((Z)=>Q.findIndex((Y)=>Y.value===Z)===-1);else this.value=[...this.value,...Q.map((Z)=>Z.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(z.value);this.value=$?this.value.filter((Q)=>Q!==z.value):[...this.value,z.value]}}constructor(z){super(z,!1);let{options:$}=z;this.#z=z.selectableGroups!==!1,this.options=Object.entries($).flatMap(([Q,Z])=>[{value:Q,group:!0,label:Q},...Z.map((Y)=>({...Y,group:Q}))]),this.value=[...z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Q})=>Q===z.cursorAt),this.#z?0:1),this.on("cursor",(Q)=>{switch(Q){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var oz=Jz();var b=(z,$)=>oz?z:$,P4=b("◆","*"),C4=b("■","x"),S4=b("▲","x"),v4=b("◇","o"),y4=b("┌","T"),ez=b("│","|"),k4=b("└","—"),h4=b("●",">"),_4=b("○"," "),g4=b("◻","[•]"),f4=b("◼","[+]"),m4=b("◻","[ ]"),d4=b("▪","•"),u4=b("─","-"),i4=b("╮","+"),c4=b("├","+"),n4=b("╯","+"),l4=b("●","•"),p4=b("◆","*"),r4=b("▲","!"),a4=b("■","x");var s4={light:b("─","-"),heavy:b("━","="),block:b("█","#")};function z4(){return`${i.gray(ez)} `}var t4=z4();var I6="0.10.
|
|
40
|
+
`)),this._prevFrame=z;return}this.output.write(o.down())}if(this.output.write(z),this.state==="initial")this.state="active";this._prevFrame=z}}function pz(z,$){if(z===void 0)return 0;if($.length===0)return 0;let Z=$.findIndex((Y)=>Y.value===z);return Z!==-1?Z:0}function rz(z,$){return($.label??String($.value)).toLowerCase().includes(z.toLowerCase())}function az(z,$){if(!$)return;if(z)return $;return $[0]}class sz extends Y6{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#z=0;#Q="";#Z;#$;get cursor(){return this.#z}get userInputWithCursor(){if(!this.userInput)return i.inverse(i.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let z=this.userInput.slice(0,this._cursor),[$,...Q]=this.userInput.slice(this._cursor);return`${z}${i.inverse($)}${Q.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(z){super(z);this.#$=z.options;let $=this.options;this.filteredOptions=[...$],this.multiple=z.multiple===!0,this.#Z=z.filter??rz;let Q;if(z.initialValue&&Array.isArray(z.initialValue))if(this.multiple)Q=z.initialValue;else Q=z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Q=[this.options[0].value];if(Q)for(let Z of Q){let Y=$.findIndex((q)=>q.value===Z);if(Y!==-1)this.toggleSelected(Z),this.#z=Y}this.focusedValue=this.options[this.#z]?.value,this.on("key",(Z,Y)=>this.#Y(Z,Y)),this.on("userInput",(Z)=>this.#q(Z))}_isActionKey(z,$){return z==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&z!==void 0&&z!==""}#Y(z,$){let Q=$.name==="up",Z=$.name==="down",Y=$.name==="return";if(Q||Z){if(this.#z=Math.max(0,Math.min(this.#z+(Q?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Y)this.value=az(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(z))this.selectedValues=this.selectedValues.filter(($)=>$!==z);else this.selectedValues=[...this.selectedValues,z];else this.selectedValues=[z]}#q(z){if(z!==this.#Q){this.#Q=z;let $=this.options;if(z)this.filteredOptions=$.filter((Q)=>this.#Z(z,Q));else this.filteredOptions=[...$];if(this.#z=pz(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class tz extends Y6{options;cursor=0;#z;getGroupItems(z){return this.options.filter(($)=>$.group===z)}isGroupSelected(z){let $=this.getGroupItems(z),Q=this.value;if(Q===void 0)return!1;return $.every((Z)=>Q.includes(Z.value))}toggleValue(){let z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(z.group===!0){let $=String(z.value),Q=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((Z)=>Q.findIndex((Y)=>Y.value===Z)===-1);else this.value=[...this.value,...Q.map((Z)=>Z.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(z.value);this.value=$?this.value.filter((Q)=>Q!==z.value):[...this.value,z.value]}}constructor(z){super(z,!1);let{options:$}=z;this.#z=z.selectableGroups!==!1,this.options=Object.entries($).flatMap(([Q,Z])=>[{value:Q,group:!0,label:Q},...Z.map((Y)=>({...Y,group:Q}))]),this.value=[...z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Q})=>Q===z.cursorAt),this.#z?0:1),this.on("cursor",(Q)=>{switch(Q){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var oz=Jz();var b=(z,$)=>oz?z:$,P4=b("◆","*"),C4=b("■","x"),S4=b("▲","x"),v4=b("◇","o"),y4=b("┌","T"),ez=b("│","|"),k4=b("└","—"),h4=b("●",">"),_4=b("○"," "),g4=b("◻","[•]"),f4=b("◼","[+]"),m4=b("◻","[ ]"),d4=b("▪","•"),u4=b("─","-"),i4=b("╮","+"),c4=b("├","+"),n4=b("╯","+"),l4=b("●","•"),p4=b("◆","*"),r4=b("▲","!"),a4=b("■","x");var s4={light:b("─","-"),heavy:b("━","="),block:b("█","#")};function z4(){return`${i.gray(ez)} `}var t4=z4();var I6="0.10.13";Q4();async function Z4(z="src/pantry"){if(!V.existsSync(z))throw Error(`Pantry directory not found: ${z}. Please run 'bun ./bin/cli.ts update-pantry' first.`);let $=[];function Q(Z,Y=""){let q=V.readdirSync(Z,{withFileTypes:!0}),J=B.join(Z,"package.yml");if(Y&&V.existsSync(J))$.push(Y);for(let U of q)if(U.isDirectory()&&!U.name.startsWith(".")){let X=Y?`${Y}/${U.name}`:U.name,G=B.join(Z,U.name);Q(G,X)}}return Q(z),console.log(`\uD83D\uDCE6 Found ${$.length} packages in local pantry`),$.sort()}async function Y4(z=!1){async function $(J){let U=new URL("https://s3.amazonaws.com/dist.tea.xyz/");if(U.searchParams.set("list-type","2"),U.searchParams.set("prefix",""),U.searchParams.set("max-keys","1000"),J)U.searchParams.set("continuation-token",J);let X=await fetch(U.toString());if(!X.ok)throw Error(`Failed to fetch S3 listing: ${X.status}`);let G=await X.text(),K=[],W=G.match(/<Key>([^<]+)<\/Key>/g);if(W)for(let T of W){let E=T.replace(/<Key>([^<]+)<\/Key>/,"$1");K.push({Key:E})}let j=G.includes("<IsTruncated>true</IsTruncated>"),F=G.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/),L=F?F[1]:void 0;return{IsTruncated:j,NextContinuationToken:L,Contents:K}}console.log("Scraping packages from S3 registry...");let Q=new Set,Z;do{let J=await $(Z);for(let U of J.Contents){let X=U.Key,G=X.split("/");if(G.length===0)continue;if(G[0].startsWith(".")||G[0].includes(" ")||X.match(/\.(md|txt|yml|yaml|json)$/i))continue;let K=["darwin","linux","windows"],W=-1;for(let j=1;j<G.length;j++)if(K.includes(G[j])){W=j;break}if(W>0){let j=G.slice(0,W).join("/");if(j.includes("."))Q.add(j)}else if(G.length>=2&&G[0].includes(".")&&!G[1].startsWith("v")&&!G[1].match(/^\d/)){let j=`${G[0]}/${G[1]}`;Q.add(j)}else if(G.length>=1&&G[0].includes("."))Q.add(G[0])}Z=J.NextContinuationToken,console.log(`Found ${Q.size} packages so far...`)}while(Z);let Y=Array.from(Q).sort(),q=[];for(let J of Y){if(!J.includes(".")||J.match(/^[a-z0-9.-]+\.[a-z]{2,}(\/[\w.-]+){0,20}$/i)===null)continue;if(J.endsWith("/README.rst")||J.endsWith("/README")||J.includes("/docs/"))continue;if(J.endsWith("/.pkgroot"))continue;if(["amazon.com/aws","charm.sh","code.videolan.org","crates.io"].includes(J))continue;q.push(J)}return console.log(`\uD83D\uDCE6 Found ${q.length} valid packages in registry`),q}async function q4(z,$){let Z=`/**
|
|
40
41
|
* Constants used throughout the ts-pantry package
|
|
41
42
|
* This file is auto-generated from ${$}. Do not edit manually.
|
|
42
43
|
* Generated on ${new Date().toISOString()}
|
|
@@ -99,18 +100,18 @@ ${Y.join(`
|
|
|
99
100
|
Conflicts found:`),j.conflicts.forEach((L)=>{console.log(` ${L.package}: ${L.versions.join(", ")}`)});if(console.log(`
|
|
100
101
|
\uD83D\uDCCB All unique packages to install:`),j.uniquePackages.forEach((L,T)=>{let E=j.allDependencies.find((N)=>N.name===L),w=E&&E.version&&E.version!=="latest"?` (${E.version})`:"";console.log(` ${T+1}. ${L}${w}`)}),G)console.log(`
|
|
101
102
|
\uD83D\uDE80 Install command:`),console.log(`pantry install ${j.uniquePackages.join(" ")}`);if(Object.values(j.osSpecificDeps).reduce((L,T)=>L+T.length,0)>0)console.log(`
|
|
102
|
-
\uD83D\uDDA5️ OS-specific dependencies:`),Object.entries(j.osSpecificDeps).forEach(([L,T])=>{if(T.length>0)console.log(` ${L}: ${T.map((E)=>E.name).join(", ")}`)})}H.exit(0)}catch(Q){if($.json){let Z={success:!1,error:String(Q),timestamp:new Date().toISOString()};console.log(JSON.stringify(Z))}else console.error("Error resolving dependencies:",Q);H.exit(1)}});I.command("get-php-versions","Get PHP versions suitable for CI/CD workflows").option("--format <type>","Output format: json (default), yaml, or csv",{default:"json"}).option("--branches <branches>","Comma-separated list of PHP branches to include (e.g., 8.4,8.3,8.2)").option("--fallback <versions>","Comma-separated list of fallback versions if detection fails").action(async(z)=>{try{let{getPhpVersionsForWorkflow:$}=await import("../chunk-
|
|
103
|
+
\uD83D\uDDA5️ OS-specific dependencies:`),Object.entries(j.osSpecificDeps).forEach(([L,T])=>{if(T.length>0)console.log(` ${L}: ${T.map((E)=>E.name).join(", ")}`)})}H.exit(0)}catch(Q){if($.json){let Z={success:!1,error:String(Q),timestamp:new Date().toISOString()};console.log(JSON.stringify(Z))}else console.error("Error resolving dependencies:",Q);H.exit(1)}});I.command("get-php-versions","Get PHP versions suitable for CI/CD workflows").option("--format <type>","Output format: json (default), yaml, or csv",{default:"json"}).option("--branches <branches>","Comma-separated list of PHP branches to include (e.g., 8.4,8.3,8.2)").option("--fallback <versions>","Comma-separated list of fallback versions if detection fails").action(async(z)=>{try{let{getPhpVersionsForWorkflow:$}=await import("../chunk-hk7ns20y.js"),Q={};if(z.branches)Q.supportedBranches=z.branches.split(",").map((Y)=>Y.trim());if(z.fallback)Q.fallbackVersions=z.fallback.split(",").map((Y)=>Y.trim());let Z=$(Q);switch(z.format.toLowerCase()){case"yaml":console.log(`php_versions:
|
|
103
104
|
${Z.map((Y)=>` - "${Y}"`).join(`
|
|
104
|
-
`)}`);break;case"csv":console.log(Z.join(","));break;case"json":default:console.log(JSON.stringify(Z));break}H.exit(0)}catch($){console.error("Error getting PHP versions:",$),H.exit(1)}});I.command("generate-zig","Generate Zig package definitions from TypeScript packages").option("--packages-dir <dir>","Directory containing TypeScript package files",{default:"src/packages"}).option("--output <file>","Output Zig file path",{default:"packages.zig"}).option("--aliases","Also generate aliases file").option("--aliases-output <file>","Output file for Zig aliases",{default:"aliases.zig"}).action(async(z)=>{try{let{generateZigDefinitions:$,generateZigAliases:Q}=await import("../chunk-
|
|
105
|
+
`)}`);break;case"csv":console.log(Z.join(","));break;case"json":default:console.log(JSON.stringify(Z));break}H.exit(0)}catch($){console.error("Error getting PHP versions:",$),H.exit(1)}});I.command("generate-zig","Generate Zig package definitions from TypeScript packages").option("--packages-dir <dir>","Directory containing TypeScript package files",{default:"src/packages"}).option("--output <file>","Output Zig file path",{default:"packages.zig"}).option("--aliases","Also generate aliases file").option("--aliases-output <file>","Output file for Zig aliases",{default:"aliases.zig"}).action(async(z)=>{try{let{generateZigDefinitions:$,generateZigAliases:Q}=await import("../chunk-wavfc3dt.js"),{packagesDir:Z="src/packages",output:Y="packages.zig",aliases:q=!1,aliasesOutput:J="aliases.zig"}=z;if(console.log("\uD83D\uDE80 Generating Zig package definitions..."),await $(Z,Y),q)console.log(`
|
|
105
106
|
\uD83D\uDE80 Generating Zig package aliases...`),await Q(Z,J);console.log(`
|
|
106
|
-
✅ Zig code generation complete!`),H.exit(0)}catch($){console.error("Error generating Zig definitions:",$),H.exit(1)}});I.command("release [type]","Release a Zig package (changelog, bump, commit, tag, push, publish)").option("-y, --yes","Non-interactive mode (skip confirmation prompts)").option("--dry-run","Preview the release without changing anything").option("--no-changelog","Skip changelog generation").option("--no-push","Skip pushing the commit and tag").option("--no-publish","Skip publishing to the pantry registry").action(async(z,$)=>{let Q=(z??"patch").toLowerCase();if(!["patch","minor","major"].includes(Q))console.error(`error: invalid release type "${Q}" (expected: patch | minor | major)`),H.exit(1);let{runRelease:Z}=await import("../chunk-msxp1kh3.js"),Y=await Z({type:Q,yes:$.yes,dryRun:$.dryRun,noChangelog:$.changelog===!1,noPush:$.push===!1,noPublish:$.publish===!1});H.exit(Y.exitCode)});I.command("apps","List installed desktop applications with version info").option("-j, --json","Output as JSON").action(async(z)=>{try{let{scanInstalledApps:$}=await import("../chunk-
|
|
107
|
+
✅ Zig code generation complete!`),H.exit(0)}catch($){console.error("Error generating Zig definitions:",$),H.exit(1)}});I.command("release [type]","Release a Zig package (changelog, bump, commit, tag, push, publish)").option("-y, --yes","Non-interactive mode (skip confirmation prompts)").option("--dry-run","Preview the release without changing anything").option("--no-changelog","Skip changelog generation").option("--no-push","Skip pushing the commit and tag").option("--no-publish","Skip publishing to the pantry registry").action(async(z,$)=>{let Q=(z??"patch").toLowerCase();if(!["patch","minor","major"].includes(Q))console.error(`error: invalid release type "${Q}" (expected: patch | minor | major)`),H.exit(1);let{runRelease:Z}=await import("../chunk-msxp1kh3.js"),Y=await Z({type:Q,yes:$.yes,dryRun:$.dryRun,noChangelog:$.changelog===!1,noPush:$.push===!1,noPublish:$.publish===!1});H.exit(Y.exitCode)});I.command("apps","List installed desktop applications with version info").option("-j, --json","Output as JSON").action(async(z)=>{try{let{scanInstalledApps:$}=await import("../chunk-byp71bz1.js"),Q=$();if(z.json)console.log(JSON.stringify({success:!0,apps:Q,total:Q.length}));else{console.log(`
|
|
107
108
|
Installed Desktop Apps (${Q.length}):
|
|
108
|
-
`),console.log("Application".padEnd(40)+"Version"),console.log("-".repeat(60));for(let Z of Q)console.log(`${Z.name.padEnd(40)}${Z.version}`)}H.exit(0)}catch($){console.error("Error listing apps:",$),H.exit(1)}});I.command("apps-outdated","Check for outdated desktop applications").option("-j, --json","Output as JSON").action(async(z)=>{try{let{checkAppUpdates:$}=await import("../chunk-
|
|
109
|
+
`),console.log("Application".padEnd(40)+"Version"),console.log("-".repeat(60));for(let Z of Q)console.log(`${Z.name.padEnd(40)}${Z.version}`)}H.exit(0)}catch($){console.error("Error listing apps:",$),H.exit(1)}});I.command("apps-outdated","Check for outdated desktop applications").option("-j, --json","Output as JSON").action(async(z)=>{try{let{checkAppUpdates:$}=await import("../chunk-byp71bz1.js");if(!z.json)console.log("Checking desktop apps for updates...");let Q=await $(),Z=Q.filter((Y)=>Y.updateAvailable);if(z.json)console.log(JSON.stringify({success:!0,apps:Q,outdated:Z.length,total:Q.length,timestamp:new Date().toISOString()}));else{if(Z.length>0){console.log(`
|
|
109
110
|
Outdated Apps (${Z.length}):
|
|
110
111
|
`),console.log("Application".padEnd(30)+"Current".padEnd(16)+"Latest".padEnd(16)+"Source"),console.log("-".repeat(75));for(let q of Z)console.log(`${q.name.padEnd(30)}${q.currentVersion.padEnd(16)}${(q.latestVersion||"?").padEnd(16)}${q.source}`)}else console.log(`
|
|
111
112
|
All desktop apps are up to date!`);let Y=Q.filter((q)=>!q.updateAvailable&&q.source!=="system"&&q.source!=="unknown");if(Y.length>0)console.log(`
|
|
112
|
-
${Y.length} app(s) up to date, ${Q.filter((q)=>q.source==="unknown").length} unchecked`)}H.exit(0)}catch($){console.error("Error checking app updates:",$),H.exit(1)}});I.command("apps-update <name>","Update a desktop application from the pantry registry").action(async(z)=>{try{let{updateApp:$}=await import("../chunk-
|
|
113
|
+
${Y.length} app(s) up to date, ${Q.filter((q)=>q.source==="unknown").length} unchecked`)}H.exit(0)}catch($){console.error("Error checking app updates:",$),H.exit(1)}});I.command("apps-update <name>","Update a desktop application from the pantry registry").action(async(z)=>{try{let{updateApp:$}=await import("../chunk-byp71bz1.js");console.log(`Updating ${z} from the pantry registry...`);let Q=await $(z);if(Q.success)console.log(`Successfully updated ${z} to ${Q.version}`);else console.error(`Failed to update ${z}: ${Q.error}`),H.exit(1);H.exit(0)}catch($){console.error("Error updating app:",$),H.exit(1)}});I.command("install <pkg>","Install a system package (e.g. ziglang.org@0.17.0-dev)").option("--global","Link binaries into the user-level global bin so they appear on PATH").option("--install-dir <dir>","Where to download into (default: ./pantry)").option("--platform <target>","Install for a target platform (e.g. linux-x86_64)").option("--no-bin-links","Skip creating local .bin/ symlinks").option("--quiet","Suppress progress output").action(async(z,$)=>{let Q=z.lastIndexOf("@"),Z=Q>0,Y=Z?z.slice(0,Q):z,q=Z?z.slice(Q+1):"latest";try{let J=await y6(Y,q,{installDir:$.installDir,platform:J4($.platform),createBinLinks:$.binLinks!==!1,quiet:$.quiet,globalBin:$.global?!0:void 0});if(!$.quiet){if(console.log(`
|
|
113
114
|
✓ ${J.name}@${J.version}`),console.log(` installed to: ${J.installPath}`),J.globalLinks&&J.globalLinks.length>0){if(console.log(` linked into: ${B.dirname(J.globalLinks[0])}`),!H.env.PATH?.split(B.delimiter).includes(B.dirname(J.globalLinks[0])))console.log(`
|
|
114
115
|
⚠ ${B.dirname(J.globalLinks[0])} is not on your PATH yet.`),console.log(" Run `ts-pantry shell-init --install` once to fix that.")}}H.exit(0)}catch(J){console.error(`Error installing ${z}:`,J instanceof Error?J.message:J),H.exit(1)}});I.command("shell-init","Print the shell snippet that puts pantry-installed packages on PATH").option("--install","Append the snippet to your shell rc file (idempotent)").option("--uninstall","Remove a previously installed snippet").option("--shell <shell>","Force a shell (zsh|bash|fish) instead of autodetect").action(async(z)=>{let $=z.shell??k6();try{if(z.uninstall){let Z=f6({shell:$});console.log(Z.changed?`✓ Removed pantry shell-init from ${Z.rcFile}`:`Nothing to remove (no pantry shell-init block in ${Z.rcFile})`),H.exit(0)}if(z.install){let Z=g6({shell:$});if(Z.changed)console.log(`✓ Added pantry shell-init to ${Z.rcFile}`),console.log(` Restart your shell or run: source ${Z.rcFile}`);else console.log(`✓ Already integrated in ${Z.rcFile}`);H.exit(0)}let Q=h6($);if(H.stdout.isTTY){if(console.log(`# Detected shell: ${$}`),console.log(`# Global bin dir: ${v6()}`),Q)console.log(`# Append this to: ${Q}`);console.log("# Or run: ts-pantry shell-init --install"),console.log()}H.stdout.write(_6({shell:$})),H.exit(0)}catch(Q){console.error("Error:",Q instanceof Error?Q.message:Q),H.exit(1)}});I.command("build [context]","Build a Dockerfile into an OCI image (no Docker daemon required)").option("-f, --file <path>","Path to the Dockerfile (default: <context>/Dockerfile)").option("-t, --tag <tag>","Image tag, e.g. myapp:latest (repeatable)").option("--target <stage>","Target stage for a multi-stage build").option("--build-arg <kv>","Set a build arg KEY=VALUE (repeatable)").option("--platform <os/arch>","Target platform (default: linux/<host-arch>)").option("--output <dir>","Where to write the image archive + OCI layout (default: <context>/.pantry/images)").option("--run-mode <mode>","How to run RUN steps: auto|chroot|host|skip (default: auto)").option("--push","Push the built image to the pantry registry after building").option("--quiet","Suppress step output").action(async(z,$)=>{try{let Q=[].concat($.tag??[]),Z={};for(let q of[].concat($.buildArg??[])){let J=q.indexOf("=");if(J!==-1)Z[q.slice(0,J)]=q.slice(J+1)}let Y=await p6({context:z??".",dockerfile:$.file,tags:Q,target:$.target,buildArgs:Z,platform:$.platform,outputDir:$.output,runMode:$.runMode,quiet:$.quiet});if(!$.quiet){if(console.log(`
|
|
115
116
|
✓ Built ${Y.imageId}`),Q.length)console.log(` tags: ${Q.join(", ")}`);console.log(` archive: ${Y.archivePath}`),console.log(` oci layout: ${Y.ociLayoutPath}`)}if($.push){let q=n6(Q[0]||"app:latest");if(!$.quiet)console.log(`
|
|
116
|
-
Pushing ${q.repository}:${q.tag} → ${c6} ...`);let J=await l6({repository:q.repository,tag:q.tag,registry:q.implicitRegistry?void 0:`https://${q.registry}`,configBytes:Buffer.from(Y.configBytes),configDigest:Y.configDigest,layers:Y.layers.map((U)=>({digest:U.digest,path:U.path,size:U.size})),manifestBytes:Buffer.from(Y.manifestBytes),manifestMediaType:Y.manifestMediaType,quiet:$.quiet});console.log(`✓ Pushed ${J.ref} (${J.digest})`)}H.exit(0)}catch(Q){console.error("Build failed:",Q instanceof Error?Q.message:Q),H.exit(1)}});I.command("container:generate [outDir]","Generate a Dockerfile + .freezer (default outDir: storage/framework)").alias("freeze").option("--base <image>","Base image (default: oven/bun:1.3.10)").option("--workdir <dir>","Working directory in the image (default: /app)").option("--install <cmd>","Install command (default: bun install --frozen-lockfile)").option("--build <cmd>","Optional build command run after install").option("--start <cmd>","Start command (default: bun start)").option("--port <port>","Exposed port (default: 3000)").option("--force","Overwrite existing files").action(async(z,$)=>{try{let Q=r6({outDir:z??"storage/framework",baseImage:$.base,workdir:$.workdir,installCommand:$.install,buildCommand:$.build,startCommand:$.start?$.start.split(/\s+/):void 0,port:$.port?Number($.port):void 0,force:$.force});console.log(`${Q.wroteDockerfile?"✓ wrote":"• kept"} ${Q.dockerfilePath}`),console.log(`${Q.wroteFreezer?"✓ wrote":"• kept"} ${Q.freezerPath}`),H.exit(0)}catch(Q){console.error("Generate failed:",Q instanceof Error?Q.message:Q),H.exit(1)}});I.help();I.version(I6);var
|
|
117
|
+
Pushing ${q.repository}:${q.tag} → ${c6} ...`);let J=await l6({repository:q.repository,tag:q.tag,registry:q.implicitRegistry?void 0:`https://${q.registry}`,configBytes:Buffer.from(Y.configBytes),configDigest:Y.configDigest,layers:Y.layers.map((U)=>({digest:U.digest,path:U.path,size:U.size})),manifestBytes:Buffer.from(Y.manifestBytes),manifestMediaType:Y.manifestMediaType,quiet:$.quiet});console.log(`✓ Pushed ${J.ref} (${J.digest})`)}H.exit(0)}catch(Q){console.error("Build failed:",Q instanceof Error?Q.message:Q),H.exit(1)}});I.command("container:generate [outDir]","Generate a Dockerfile + .freezer (default outDir: storage/framework)").alias("freeze").option("--base <image>","Base image (default: oven/bun:1.3.10)").option("--workdir <dir>","Working directory in the image (default: /app)").option("--install <cmd>","Install command (default: bun install --frozen-lockfile)").option("--build <cmd>","Optional build command run after install").option("--start <cmd>","Start command (default: bun start)").option("--port <port>","Exposed port (default: 3000)").option("--force","Overwrite existing files").action(async(z,$)=>{try{let Q=r6({outDir:z??"storage/framework",baseImage:$.base,workdir:$.workdir,installCommand:$.install,buildCommand:$.build,startCommand:$.start?$.start.split(/\s+/):void 0,port:$.port?Number($.port):void 0,force:$.force});console.log(`${Q.wroteDockerfile?"✓ wrote":"• kept"} ${Q.dockerfilePath}`),console.log(`${Q.wroteFreezer?"✓ wrote":"• kept"} ${Q.freezerPath}`),H.exit(0)}catch(Q){console.error("Generate failed:",Q instanceof Error?Q.message:Q),H.exit(1)}});I.help();I.version(I6);var H0=I.parse();if(H.argv.length<=2||H.argv.includes("--help")||H.argv.includes("-h"))H.exit(0);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Pb as a,Qb as b,Rb as c,Sb as d,Tb as e}from"./chunk-py3ymxjf.js";import"./chunk-ghzc37v7.js";export{d as PACKAGE_ALIASES,c as DEFAULT_TIMEOUT_MS,b as DEFAULT_CACHE_EXPIRATION_MINUTES,a as DEFAULT_CACHE_DIR,e as ALL_KNOWN_PACKAGES};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{yb as ZQ,zb as KQ}from"./chunk-jkfbbcs7.js";import{Pb as l,Qb as r,Rb as p}from"./chunk-py3ymxjf.js";import{jc as d,kc as YQ}from"./chunk-dnw4x7bh.js";import{oc as qQ}from"./chunk-ghzc37v7.js";import H from"node:fs";import F from"node:path";import h from"node:process";YQ();var WQ=async(...Q)=>null;function c(Q,K){let G=Q.replace(/^v/,"").split("."),$=K.replace(/^v/,"").split(".");for(let q=0;q<Math.max(G.length,$.length);q++){let Z=Number.parseInt(G[q]||"0",10),X=Number.parseInt($[q]||"0",10);if(!Number.isNaN(Z)&&!Number.isNaN(X)){if(Z!==X)return X-Z}else{let Y=($[q]||"").localeCompare(G[q]||"");if(Y!==0)return Y}}return 0}function QQ(Q){if(Q.includes("/")){let[K,...G]=Q.split("/"),$=G.join("/"),q=K.replace(/\./g,"");if(K.includes("github.com")){let X=$.split("/");return X[X.length-1].replace(/[.-]/g,"").toLowerCase()}let Z=$.replace(/[/.-]/g,"");return`${q}${Z}`.toLowerCase()}return Q.replace(/\./g,"").toLowerCase()}function zQ(Q,K){switch(Q){case"versions":if(Array.isArray(K)&&K.length>0)return` /**
|
|
2
2
|
* Available versions from newest to oldest.
|
|
3
3
|
* @see https://ts-pantry.netlify.app/usage for installation instructions
|
|
4
4
|
*/`;break;case"programs":if(Array.isArray(K)&&K.length>0)return` /**
|
|
@@ -31,8 +31,8 @@ import{Mb as l,Nb as r,Ob as p}from"./chunk-6e7x6std.js";import{gc as d,hc as YQ
|
|
|
31
31
|
export const ${Z} = ${Y}
|
|
32
32
|
|
|
33
33
|
export type ${Z.charAt(0).toUpperCase()+Z.slice(1)} = typeof ${Z}
|
|
34
|
-
`}function s(Q){let K=Q.replace(/\{\{[^}]*\}\}/g,"").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");if(!K||K.length===0)return"package";let G=K.replace(/[^\w.-]/g,"-");if(G.length>200)G=`${G.substring(0,150)}...${G.substring(G.length-45)}`;return G}function f(Q,K,G){if(!H.existsSync(Q))H.mkdirSync(Q,{recursive:!0});let $;if(K.includes("/")){let X=K.split("/");if(X.some((B)=>!B||B===".."||B==="."||B.includes("\x00")||B.includes("\\")))throw Error(`Invalid domain name (contains path-traversal): ${K}`);let Y=X[0],W=X.slice(1),J=F.join(Q,Y,...W.slice(0,-1)),E=F.resolve(Q);if(!F.resolve(J).startsWith(`${E}${F.sep}`)&&F.resolve(J)!==E)throw Error(`Path traversal detected for ${K}`);if(!H.existsSync(J))H.mkdirSync(J,{recursive:!0});let T=s(W[W.length-1]);$=F.join(J,`${T}.ts`)}else{let X=K.replace(/\./g,"");$=F.join(Q,`${X}.ts`)}let q={...G};delete q.fetchedAt;let Z=jQ(q,K);return H.writeFileSync($,Z),$}function SQ(Q,K){if(!H.existsSync(Q))return[];let G=new Set;for(let X of K)if(X.includes("/")){let Y=X.split("/"),W=Y[0],J=Y.slice(1),E=s(J[J.length-1]);G.add(F.resolve(Q,W,...J.slice(0,-1),`${E}.ts`))}else{let Y=X.replace(/\./g,"");G.add(F.resolve(Q,`${Y}.ts`))}let $=new Set(["index.ts","aliases.ts","types.ts"]),q=[];function Z(X){if(!H.existsSync(X))return;for(let Y of H.readdirSync(X,{withFileTypes:!0})){let W=F.join(X,Y.name);if(Y.isDirectory()){if(Z(W),H.existsSync(W)&&H.readdirSync(W).length===0)H.rmdirSync(W)}else if(Y.name.endsWith(".ts")&&!$.has(Y.name)){if(!G.has(F.resolve(W)))H.unlinkSync(W),q.push(W)}}}return Z(Q),q}function HQ(Q,K={}){try{let G=K.cacheDir||l;if(K.cache===!1)return console.log(`Cache disabled for ${Q}, skipping cache check`),null;let q=(d[Q]||Q).replace(/\//g,"-"),Z=F.join(G,`${q}.json`);if(console.log(`Checking for cache file: ${Z}`),!H.existsSync(Z))return null;let X;try{X=JSON.parse(H.readFileSync(Z,"utf-8"))}catch{try{H.unlinkSync(Z)}catch{}return null}if(!X.fetchedAt)return console.log(`Cache for ${Q} missing fetchedAt timestamp, invalidating`),null;if(["Crafters of fine Open Source products","Go home.","Package information for","pkgx package","Loading...","Please wait..."].some((B)=>X.description&&X.description.includes(B)))return console.log(`Cache for ${Q} has generic description "${X.description}", invalidating`),null;if(!X.versions||X.versions.length===0)return console.log(`Cache for ${Q} has no versions, invalidating`),null;let E=(K.cacheExpirationMinutes||r)*60*1000,T=Date.now();if(T-X.fetchedAt>E)return console.log(`Cache for ${Q} has expired (age: ${Math.round((T-X.fetchedAt)/60000)} minutes)`),null;return console.log(`Using cached data for ${Q} (age: ${Math.round((T-X.fetchedAt)/60000)} minutes)`),{packageInfo:X,filePath:Z}}catch(G){return console.error(`Error reading cache for ${Q}:`,G),null}}function LQ(Q,K,G={}){let $={...K,fetchedAt:Date.now()},q=G.cacheDir||l;if(!H.existsSync(q))H.mkdirSync(q,{recursive:!0});let Z=Q.replace(/\//g,"-"),X=F.join(q,`${Z}.json`);H.writeFileSync(X,JSON.stringify($,null,2));let Y=G.outputDir||"packages";if(!H.existsSync(Y))H.mkdirSync(Y,{recursive:!0});let W=f(Y,Q,K);return{cachePath:X,outputPath:W}}function GQ(){return Promise.resolve()}async function yQ(Q={}){let K=Q.apiUrl||"https://api.github.com/repos/pkgxdev/pantry/contents/projects";try{console.log(`Fetching projects from GitHub API: ${K}`);let G=await fetch(K,{headers:{Accept:"application/vnd.github.v3+json"}});if(!G.ok)throw Error(`Failed to fetch from GitHub API: ${G.statusText}`);let q=(await G.json()).filter((Z)=>Z.type==="dir").map((Z)=>({name:Z.name,url:Z.html_url}));return console.log(`Retrieved ${q.length} projects from GitHub API`),q.sort((Z,X)=>Z.name.localeCompare(X.name)),q}catch(G){throw console.error("Error fetching projects from GitHub API:",G),G}}async function t(Q,K={}){let G=Q,$=Q;if(Q.includes("/")){let[q,Z]=Q.split("/");console.log(`Identified nested package: domain=${q}, name=${Z}`)}if(d[Q])console.log(`'${Q}' is an alias for '${d[Q]}', redirecting...`),$=d[Q],Q=d[Q];try{let q=K.timeout||p,Z=await WQ(Q,{timeout:q,useClientSideScraper:!0});if(!Z||typeof Z!=="object")return $Q(Q,G,$);let X={name:Z.displayName||Z.name||Q.split("/").pop()||Q,domain:Z.domain||Q,description:Z.description||Z.brief||"",packageYmlUrl:`https://github.com/pkgxdev/pantry/tree/main/projects/${Q}/package.yml`,homepageUrl:Z.homepage||"",githubUrl:Z.github||"",installCommand:`pantry install ${Q}`,pantryInstallCommand:`pantry install ${Q}`,programs:Z.provides||[],companions:Array.isArray(Z.companions)?Z.companions:[],dependencies:Array.isArray(Z.dependencies)?Z.dependencies:[],buildDependencies:Z.buildDependencies||[],versions:Z.versions||[],aliases:[]};if(!X.versions||X.versions.length===0){let Y=X.domain||Q;if(!["apache.org","breakfastquay.com","catb.org","bloomreach.com","cairographics.org","certifi.io","charm.sh","aws.amazon.com","google.com","microsoft.com","mozilla.org","freedesktop.org","gnome.org","kde.org","sourceforge.net","sf.net"].some((J)=>Y.startsWith(J)))try{let J=X.domain||Q,E=await UQ(J);X.versions=E}catch(J){console.warn(`Failed to fetch versions for ${Q} from GitHub API:`,J),X.versions=[]}}if(X.versions&&X.versions.length>0)try{X.versions.sort((Y,W)=>{try{return-1*Bun.semver.order(Y,W)}catch{return c(Y,W)}})}catch(Y){console.warn(`Warning: Failed to sort versions for ${Q} using semver:`,Y)}return X.name=X.name||G,X.domain=X.domain||$,X.programs=X.programs||[],X.companions=X.companions||[],X.dependencies=X.dependencies||[],X.versions=X.versions||[],{packageInfo:X,originalName:G,fullDomainName:$}}catch(q){return console.error(`Error in fetchPantryPackage for ${Q}:`,q),$Q(Q,G,$)}}async function UQ(Q){try{let{shouldProceedWithGitHubRequest:K,saveRateLimitInfo:G}=await import("./chunk-
|
|
35
|
-
Received ${K} signal. Cleaning up resources...`),N)clearInterval(N);await GQ(),console.log("Resources cleaned up. Exiting."),setTimeout(()=>{console.log("Forcing process exit..."),h.exit(0)},5000)};h.on("SIGINT",()=>Q("SIGINT")),h.on("SIGTERM",()=>Q("SIGTERM")),h.on("uncaughtException",(K)=>{console.error("Uncaught exception:",K),Q("uncaughtException")})}if(typeof Bun<"u"&&Bun.main===import.meta.path)EQ(),h.on("uncaughtException",(Q)=>{let K=String(Q);if(console.error("Uncaught exception caught:",Q.message),Q.message.includes("No target found for targetId")||Q.message.includes("Assertion error")||Q.message.includes("Target page, context or browser has been closed")||Q.message.includes("Failed to connect")||Q.message.includes("Connection closed")||Q.message.includes("Protocol error")||K.includes("WebSocket connection closed")||Q.message.includes("Browser has been closed")){console.error("Browser/network connection error detected, continuing execution...");return}console.error("Non-browser error, exiting..."),h.exit(1)}),h.on("unhandledRejection",(Q,K)=>{let G=String(Q);if(console.error("Unhandled rejection caught:",G),G.includes("No target found for targetId")||G.includes("Assertion error")||G.includes("Target page, context or browser has been closed")||G.includes("Failed to connect")||G.includes("Connection closed")||G.includes("Protocol error")||G.includes("WebSocket connection closed")||G.includes("Browser has been closed")){console.error("Browser/network connection error in promise, continuing execution...");return}console.error("Non-browser promise rejection, exiting..."),h.exit(1)});function vQ(){if(N)clearInterval(N);N=setInterval(()=>{console.log("Running periodic browser resource cleanup..."),GQ().then(()=>console.log("Periodic cleanup completed")).catch((Q)=>console.error("Error during periodic cleanup:",Q))},RQ)}async function bQ(Q={}){let K=Q.timeout||p,G=Q.outputDir||"packages",$=Q.cacheDir||l,q=Q.cache!==!1,Z=Q.cacheExpirationMinutes||r,X=Math.min(Q.concurrency||6,8),Y=Q.pantryDir||"src/pantry";if(!Q.outputJson)console.log(`Starting bulk fetch with concurrency: ${X}, timeout: ${K}ms`);let W=Date.now(),J=[];try{if(!Q.outputJson)console.log("Scanning local pantry for packages...");try{if(J=await OQ(Y),!Q.outputJson)console.log(`Found ${J.length} packages in local pantry`)}catch(j){if(!Q.outputJson)console.warn("Failed to scan local pantry, falling back to consts:",j);try{let{ALL_KNOWN_PACKAGES:_}=await import("./chunk-
|
|
34
|
+
`}function s(Q){let K=Q.replace(/\{\{[^}]*\}\}/g,"").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");if(!K||K.length===0)return"package";let G=K.replace(/[^\w.-]/g,"-");if(G.length>200)G=`${G.substring(0,150)}...${G.substring(G.length-45)}`;return G}function f(Q,K,G){if(!H.existsSync(Q))H.mkdirSync(Q,{recursive:!0});let $;if(K.includes("/")){let X=K.split("/");if(X.some((B)=>!B||B===".."||B==="."||B.includes("\x00")||B.includes("\\")))throw Error(`Invalid domain name (contains path-traversal): ${K}`);let Y=X[0],W=X.slice(1),J=F.join(Q,Y,...W.slice(0,-1)),E=F.resolve(Q);if(!F.resolve(J).startsWith(`${E}${F.sep}`)&&F.resolve(J)!==E)throw Error(`Path traversal detected for ${K}`);if(!H.existsSync(J))H.mkdirSync(J,{recursive:!0});let T=s(W[W.length-1]);$=F.join(J,`${T}.ts`)}else{let X=K.replace(/\./g,"");$=F.join(Q,`${X}.ts`)}let q={...G};delete q.fetchedAt;let Z=jQ(q,K);return H.writeFileSync($,Z),$}function SQ(Q,K){if(!H.existsSync(Q))return[];let G=new Set;for(let X of K)if(X.includes("/")){let Y=X.split("/"),W=Y[0],J=Y.slice(1),E=s(J[J.length-1]);G.add(F.resolve(Q,W,...J.slice(0,-1),`${E}.ts`))}else{let Y=X.replace(/\./g,"");G.add(F.resolve(Q,`${Y}.ts`))}let $=new Set(["index.ts","aliases.ts","types.ts"]),q=[];function Z(X){if(!H.existsSync(X))return;for(let Y of H.readdirSync(X,{withFileTypes:!0})){let W=F.join(X,Y.name);if(Y.isDirectory()){if(Z(W),H.existsSync(W)&&H.readdirSync(W).length===0)H.rmdirSync(W)}else if(Y.name.endsWith(".ts")&&!$.has(Y.name)){if(!G.has(F.resolve(W)))H.unlinkSync(W),q.push(W)}}}return Z(Q),q}function HQ(Q,K={}){try{let G=K.cacheDir||l;if(K.cache===!1)return console.log(`Cache disabled for ${Q}, skipping cache check`),null;let q=(d[Q]||Q).replace(/\//g,"-"),Z=F.join(G,`${q}.json`);if(console.log(`Checking for cache file: ${Z}`),!H.existsSync(Z))return null;let X;try{X=JSON.parse(H.readFileSync(Z,"utf-8"))}catch{try{H.unlinkSync(Z)}catch{}return null}if(!X.fetchedAt)return console.log(`Cache for ${Q} missing fetchedAt timestamp, invalidating`),null;if(["Crafters of fine Open Source products","Go home.","Package information for","pkgx package","Loading...","Please wait..."].some((B)=>X.description&&X.description.includes(B)))return console.log(`Cache for ${Q} has generic description "${X.description}", invalidating`),null;if(!X.versions||X.versions.length===0)return console.log(`Cache for ${Q} has no versions, invalidating`),null;let E=(K.cacheExpirationMinutes||r)*60*1000,T=Date.now();if(T-X.fetchedAt>E)return console.log(`Cache for ${Q} has expired (age: ${Math.round((T-X.fetchedAt)/60000)} minutes)`),null;return console.log(`Using cached data for ${Q} (age: ${Math.round((T-X.fetchedAt)/60000)} minutes)`),{packageInfo:X,filePath:Z}}catch(G){return console.error(`Error reading cache for ${Q}:`,G),null}}function LQ(Q,K,G={}){let $={...K,fetchedAt:Date.now()},q=G.cacheDir||l;if(!H.existsSync(q))H.mkdirSync(q,{recursive:!0});let Z=Q.replace(/\//g,"-"),X=F.join(q,`${Z}.json`);H.writeFileSync(X,JSON.stringify($,null,2));let Y=G.outputDir||"packages";if(!H.existsSync(Y))H.mkdirSync(Y,{recursive:!0});let W=f(Y,Q,K);return{cachePath:X,outputPath:W}}function GQ(){return Promise.resolve()}async function yQ(Q={}){let K=Q.apiUrl||"https://api.github.com/repos/pkgxdev/pantry/contents/projects";try{console.log(`Fetching projects from GitHub API: ${K}`);let G=await fetch(K,{headers:{Accept:"application/vnd.github.v3+json"}});if(!G.ok)throw Error(`Failed to fetch from GitHub API: ${G.statusText}`);let q=(await G.json()).filter((Z)=>Z.type==="dir").map((Z)=>({name:Z.name,url:Z.html_url}));return console.log(`Retrieved ${q.length} projects from GitHub API`),q.sort((Z,X)=>Z.name.localeCompare(X.name)),q}catch(G){throw console.error("Error fetching projects from GitHub API:",G),G}}async function t(Q,K={}){let G=Q,$=Q;if(Q.includes("/")){let[q,Z]=Q.split("/");console.log(`Identified nested package: domain=${q}, name=${Z}`)}if(d[Q])console.log(`'${Q}' is an alias for '${d[Q]}', redirecting...`),$=d[Q],Q=d[Q];try{let q=K.timeout||p,Z=await WQ(Q,{timeout:q,useClientSideScraper:!0});if(!Z||typeof Z!=="object")return $Q(Q,G,$);let X={name:Z.displayName||Z.name||Q.split("/").pop()||Q,domain:Z.domain||Q,description:Z.description||Z.brief||"",packageYmlUrl:`https://github.com/pkgxdev/pantry/tree/main/projects/${Q}/package.yml`,homepageUrl:Z.homepage||"",githubUrl:Z.github||"",installCommand:`pantry install ${Q}`,pantryInstallCommand:`pantry install ${Q}`,programs:Z.provides||[],companions:Array.isArray(Z.companions)?Z.companions:[],dependencies:Array.isArray(Z.dependencies)?Z.dependencies:[],buildDependencies:Z.buildDependencies||[],versions:Z.versions||[],aliases:[]};if(!X.versions||X.versions.length===0){let Y=X.domain||Q;if(!["apache.org","breakfastquay.com","catb.org","bloomreach.com","cairographics.org","certifi.io","charm.sh","aws.amazon.com","google.com","microsoft.com","mozilla.org","freedesktop.org","gnome.org","kde.org","sourceforge.net","sf.net"].some((J)=>Y.startsWith(J)))try{let J=X.domain||Q,E=await UQ(J);X.versions=E}catch(J){console.warn(`Failed to fetch versions for ${Q} from GitHub API:`,J),X.versions=[]}}if(X.versions&&X.versions.length>0)try{X.versions.sort((Y,W)=>{try{return-1*Bun.semver.order(Y,W)}catch{return c(Y,W)}})}catch(Y){console.warn(`Warning: Failed to sort versions for ${Q} using semver:`,Y)}return X.name=X.name||G,X.domain=X.domain||$,X.programs=X.programs||[],X.companions=X.companions||[],X.dependencies=X.dependencies||[],X.versions=X.versions||[],{packageInfo:X,originalName:G,fullDomainName:$}}catch(q){return console.error(`Error in fetchPantryPackage for ${Q}:`,q),$Q(Q,G,$)}}async function UQ(Q){try{let{shouldProceedWithGitHubRequest:K,saveRateLimitInfo:G}=await import("./chunk-wcn78wgj.js");if(!K())return console.warn("Skipping GitHub API request for versions due to rate limiting"),[];let $=await fetch(`https://api.github.com/repos/pkgxdev/pantry/contents/projects/${Q}`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"ts-pantry"},signal:AbortSignal.timeout(15000)});if(G($.headers),$.status===403){let Z=$.headers.get("X-RateLimit-Remaining"),X=$.headers.get("X-RateLimit-Reset"),Y=X?new Date(Number(X)*1000).toLocaleString():"unknown";return console.warn(`GitHub API rate limit exceeded. Remaining: ${Z||0}, Reset: ${Y}`),[]}if(!$.ok)throw Error(`GitHub API responded with ${$.status}: ${$.statusText}`);return(await $.json()).filter((Z)=>Z.name.match(/^v\d+/)).map((Z)=>Z.name)}catch(K){return console.error("Error fetching versions from GitHub:",K),[]}}var RQ=300000,N=null;function EQ(){let Q=async(K)=>{if(console.log(`
|
|
35
|
+
Received ${K} signal. Cleaning up resources...`),N)clearInterval(N);await GQ(),console.log("Resources cleaned up. Exiting."),setTimeout(()=>{console.log("Forcing process exit..."),h.exit(0)},5000)};h.on("SIGINT",()=>Q("SIGINT")),h.on("SIGTERM",()=>Q("SIGTERM")),h.on("uncaughtException",(K)=>{console.error("Uncaught exception:",K),Q("uncaughtException")})}if(typeof Bun<"u"&&Bun.main===import.meta.path)EQ(),h.on("uncaughtException",(Q)=>{let K=String(Q);if(console.error("Uncaught exception caught:",Q.message),Q.message.includes("No target found for targetId")||Q.message.includes("Assertion error")||Q.message.includes("Target page, context or browser has been closed")||Q.message.includes("Failed to connect")||Q.message.includes("Connection closed")||Q.message.includes("Protocol error")||K.includes("WebSocket connection closed")||Q.message.includes("Browser has been closed")){console.error("Browser/network connection error detected, continuing execution...");return}console.error("Non-browser error, exiting..."),h.exit(1)}),h.on("unhandledRejection",(Q,K)=>{let G=String(Q);if(console.error("Unhandled rejection caught:",G),G.includes("No target found for targetId")||G.includes("Assertion error")||G.includes("Target page, context or browser has been closed")||G.includes("Failed to connect")||G.includes("Connection closed")||G.includes("Protocol error")||G.includes("WebSocket connection closed")||G.includes("Browser has been closed")){console.error("Browser/network connection error in promise, continuing execution...");return}console.error("Non-browser promise rejection, exiting..."),h.exit(1)});function vQ(){if(N)clearInterval(N);N=setInterval(()=>{console.log("Running periodic browser resource cleanup..."),GQ().then(()=>console.log("Periodic cleanup completed")).catch((Q)=>console.error("Error during periodic cleanup:",Q))},RQ)}async function bQ(Q={}){let K=Q.timeout||p,G=Q.outputDir||"packages",$=Q.cacheDir||l,q=Q.cache!==!1,Z=Q.cacheExpirationMinutes||r,X=Math.min(Q.concurrency||6,8),Y=Q.pantryDir||"src/pantry";if(!Q.outputJson)console.log(`Starting bulk fetch with concurrency: ${X}, timeout: ${K}ms`);let W=Date.now(),J=[];try{if(!Q.outputJson)console.log("Scanning local pantry for packages...");try{if(J=await OQ(Y),!Q.outputJson)console.log(`Found ${J.length} packages in local pantry`)}catch(j){if(!Q.outputJson)console.warn("Failed to scan local pantry, falling back to consts:",j);try{let{ALL_KNOWN_PACKAGES:_}=await import("./chunk-0xfx7txg.js");if(J=[..._].filter((L)=>L&&L!=="undefined"&&L!=="aliases"&&L!=="index"),!Q.outputJson)console.log(`Using comprehensive package list: ${J.length} packages`)}catch(_){if(!Q.outputJson)console.warn("Failed to load consts, falling back to GitHub API:",_);try{let L=await fetch("https://api.github.com/repos/pkgxdev/pantry/contents/projects",{headers:{"User-Agent":"ts-pantry-fetcher",Accept:"application/vnd.github.v3+json"}});if(L.ok){let x=(await L.json()).filter((U)=>U.type==="dir").map((U)=>U.name).sort();if(!Q.outputJson)console.log(`Retrieved ${x.length} projects from GitHub API`);J=x}else throw Error(`GitHub API returned ${L.status}`)}catch(L){if(!Q.outputJson)console.warn("Failed to fetch from GitHub API, falling back to local discovery:",L);if(H.existsSync(G))J=H.readdirSync(G).filter((x)=>x.endsWith(".ts")).map((x)=>F.basename(x,".ts")),console.log(`Found ${J.length} existing packages`)}}}if(J.length===0)return console.error("No packages found to process"),[];let E=["android.com","apache.org","akuity.io","alsa-project.org","anchore.com","aomedia.googlesource.com","apollographql.com","facebook.com","google.com","microsoft.com","mozilla.org","sourceforge.net","x.org","xiph.org","yui.github.io","crates.io","gitlab.com","github.com"],T=new Set,B=J.filter((j)=>j.startsWith("github.com/"));for(let j of B){let _=j.split("/");if(_.length>2){let L=_.slice(0,2).join("/");T.add(L)}}if(J=J.filter((j)=>{if(j.endsWith("/.pkgroot"))return console.log(`Filtering out .pkgroot marker: ${j}`),!1;if(j.endsWith("/README.rst"))return console.log(`Filtering out README.rst documentation: ${j}`),!1;if(j==="agwa.name")return console.log("Filtering out standalone agwa.name - only agwa.name/git-crypt is valid"),!1;if(E.includes(j))return console.log(`Filtering out parent domain ${j} - only has nested packages`),!1;if(T.has(j))return console.log(`Filtering out GitHub parent path ${j} - only has nested packages`),!1;if(j==="undefined"||j==="aliases"||j==="index")return!1;return!0}),console.log(`Found ${J.length} packages to process`),Q.limit&&Q.limit>0)J=J.slice(0,Q.limit),console.log(`Limited to ${J.length} packages`);let O=[],M=[],C=0,w=Math.min(X,6),z=[];for(let j=0;j<J.length;j+=w)z.push(J.slice(j,j+w));if(!Q.outputJson)console.log(`Processing ${J.length} packages in ${z.length} batches...`);for(let j=0;j<z.length;j++){let _=z[j];if(!Q.outputJson)console.log(`Processing batch ${j+1}/${z.length} (${_.length} packages)`);let L=_.map(async(R)=>{try{let P=F.join($,`${R.replace(/\//g,"-")}.json`);if(q&&H.existsSync(P)){let v=H.statSync(P),k=(Date.now()-v.mtime.getTime())/60000;if(k<Z){if(!Q.outputJson)console.log(`Using cached data for ${R} (age: ${Math.round(k)} minutes)`);try{let u=JSON.parse(H.readFileSync(P,"utf-8"));delete u.fetchedAt;let g=f(G,R,u);if(!Q.outputJson)console.log(`Using cached data for ${R} (saved to ${g})`);return{success:!0,packageName:R}}catch{console.warn(`Cache file corrupted for ${R}, will refetch`)}}}let S=await FQ(R,{...Q,pantryDir:Y,timeout:K,cache:q,cacheDir:$,cacheExpirationMinutes:Z});if(S){let{outputPath:v}=LQ(R,S.packageInfo,{cacheDir:$,outputDir:G,cache:q});if(!Q.outputJson)console.log(`Successfully processed ${R} (saved to ${v})`);return{success:!0,packageName:R}}else return console.warn(`Failed to fetch ${R}`),{success:!1,packageName:R}}catch(P){return console.error(`Error processing ${R}:`,P),{success:!1,packageName:R}}}),V=await Promise.allSettled(L);for(let R of V)if(C++,R.status==="fulfilled")if(R.value.success)O.push(R.value.packageName);else M.push(R.value.packageName);else console.error("Batch promise rejected:",R.reason),M.push("unknown");let x=Math.round((Date.now()-W)/1000),U=Math.round(C/x*10)/10,y=Math.round((J.length-C)/U);if(!Q.outputJson)console.log(`Batch ${j+1}/${z.length} complete. Progress: ${C}/${J.length} (${Math.round(C/J.length*100)}%) | Success: ${O.length} | Failed: ${M.length} | Rate: ${U}/s | ETA: ${y}s`);if(j<z.length-1)await new Promise((R)=>setTimeout(R,1000))}let A=Math.round((Date.now()-W)/1000);if(!Q.outputJson){if(console.log(`
|
|
36
36
|
Completed in ${A}s. Successfully processed: ${O.length}, Failed: ${M.length}`),M.length>0)console.log(`Failed packages: ${M.slice(0,10).join(", ")}${M.length>10?` ... and ${M.length-10} more`:""}`)}return O}catch(E){return console.error("Error in fetchAndSaveAllPackages:",E),[]}}function $Q(Q,K,G){let $=Q.split("/"),q=$[0];return{packageInfo:{name:($.length>1?$.slice(1).join("/"):null)||Q,domain:q,description:`Package information for ${Q}`,packageYmlUrl:"",homepageUrl:"",githubUrl:"",installCommand:`pantry install ${Q}`,pantryInstallCommand:`pantry install ${Q}`,programs:[],companions:[],dependencies:[],versions:[]},originalName:K,fullDomainName:G}}async function BQ(Q,K,G,$=!1,q=1,Z=3,X=!1,Y={}){try{let W=Y.cache!==!1,J=Y.cacheDir||l;if(!W)console.log(`Cache disabled for ${Q}, will fetch directly`);else{let C=HQ(Q,{cacheDir:J,cacheExpirationMinutes:Y.cacheExpirationMinutes,cache:Y.cache});if(C){let{packageInfo:w}=C,z=w.domain||Q,A=w.aliases||[],j=f(K,Q,w);return console.log(`Using cached data for ${Q} (saved to ${j})`),{success:!0,fullDomainName:z,aliases:A,filePath:j}}}let T=G+(q-1)*1e4;console.log(`Using timeout for ${Q} (attempt ${q}): ${T}ms`);let B=T,O,M=new Promise((C,w)=>{O=setTimeout(()=>{console.error(`Operation timeout for ${Q} after ${B}ms`),w(Error(`Operation timeout after ${B}ms`))},B)});if(Q.includes("/")){let C=Q.split("/"),w=C[0],z=C.slice(1).join("/");console.log(`Processing nested package: domain=${w}, subPath=${z}`);try{let A=t(`${w}/${z}`,{timeout:T,browser:Y.browser}),j=await Promise.race([A,M]);clearTimeout(O);let{packageInfo:_,originalName:L,fullDomainName:V}=j;if(_.versions&&_.versions.length>0)try{_.versions.sort((S,v)=>{try{return-1*Bun.semver.order(S,v)}catch{return c(S,v)}})}catch(S){console.warn(`Warning: Failed to sort versions for ${Q} using semver:`,S)}let x=V.replace(/\//g,"-"),U=[];if(_.aliases&&_.aliases.length>0)U.push(..._.aliases);for(let[S,v]of Object.entries(d))if(v===V&&!U.includes(S))U.push(S);if(L!==V&&!U.includes(L))U.push(L);let y=["cli","app","tool","server","client","api","lib","core"];if(!U.includes(z)&&!y.includes(z.toLowerCase()))U.push(z);let R={..._,fullPath:Q,aliases:U.length>0?U:[]};if(W){let S=F.join(J,`${x}.json`),v={...R,fetchedAt:Date.now()};if(!H.existsSync(J))H.mkdirSync(J,{recursive:!0});H.writeFileSync(S,JSON.stringify(v,null,2)),console.log(`Saved package data to cache: ${S}`)}let P=f(K,V,R);return console.log(`Successfully saved nested package ${Q} to ${P} with aliases: ${U.join(", ")||"none"}`),{success:!0,fullDomainName:V,aliases:U,filePath:P}}catch(A){if(clearTimeout(O),A.toString().includes("404")||A.toString().includes("Not Found"))return console.error(`Package ${Q} returned 404 Not Found.`),console.error(`Skipping ${Q} to avoid overwriting existing files.`),{success:!1,fullDomainName:Q};throw A}}else try{let C=t(Q,{timeout:T,browser:Y.browser}),w=await Promise.race([C,M]);clearTimeout(O);let{packageInfo:z,originalName:A,fullDomainName:j}=w,_=z.description&&z.description.trim()!=="",L=z.versions&&z.versions.length>0,V=z.programs&&z.programs.length>0,x=z.packageYmlUrl&&z.packageYmlUrl.length>0,U=z.dependencies&&z.dependencies.length>0,y=z.companions&&z.companions.length>0,R=_&&(z.description.toLowerCase().trim()==="go home."||z.description.toLowerCase().trim()==="page not found"||z.description.toLowerCase().trim()==="not found"||z.description.toLowerCase().trim()==="404"||z.description.toLowerCase().trim()==="error"),P=_&&!R,S=L||V||x||U||y,v=z.domain&&z.domain.includes(".");if(!(P||S||v))return console.error(`Package ${Q} appears to have no meaningful data. Skipping to avoid creating empty files.`),{success:!1,fullDomainName:Q};let u=z.name&&z.name!==j&&z.name!==j.split("/")[0]&&z.name.length>1&&!z.name.includes("/")?s(z.name):null,g=j.replace(/\//g,"-"),m=u?F.join(K,`${u}.ts`):F.join(K,`${g}.ts`);if(H.existsSync(m)){let b=H.readFileSync(m,"utf-8"),I=b.includes("dependencies: [")&&!b.includes("dependencies: [] as const"),n=z.dependencies.length===0,e=!b.includes("description: 'Package information for")&&!b.includes("description: '' as const"),a=z.description.includes("Package information for")||z.description.trim()==="";if(I&&n||e&&a)return console.warn(`⚠️ Existing file ${m} has better data than new fetch. Skipping to prevent data loss.`),console.warn(` Existing deps: ${I}, New deps: ${!n}`),console.warn(` Existing desc: ${e}, New desc: ${!a}`),{success:!1,fullDomainName:Q}}if(z.versions&&z.versions.length>0)try{z.versions.sort((b,I)=>{try{return-1*Bun.semver.order(b,I)}catch{return c(b,I)}})}catch(b){console.warn(`Warning: Failed to sort versions for ${Q} using semver:`,b)}let JQ=j.replace(/\//g,"-"),D=[];if(z.aliases&&z.aliases.length>0)D.push(...z.aliases);for(let[b,I]of Object.entries(d))if(I===j&&!D.includes(b))D.push(b);if(A!==j&&!D.includes(A))D.push(A);let o={...z,fullPath:Q,aliases:D.length>0?D:[]};if(W){let b=F.join(J,`${JQ}.json`),I={...o,fetchedAt:Date.now()};if(!H.existsSync(J))H.mkdirSync(J,{recursive:!0});H.writeFileSync(b,JSON.stringify(I,null,2)),console.log(`Saved package data to cache: ${b}`)}let i=f(K,j,o);return console.log(`Successfully saved ${Q} to ${i} with aliases: ${D.join(", ")||"none"}`),{success:!0,fullDomainName:j,aliases:D,filePath:i}}catch(C){if(clearTimeout(O),C.toString().includes("404")||C.toString().includes("Not Found"))return console.error(`Package ${Q} returned 404 Not Found. Skipping to avoid overwriting existing files.`),{success:!1,fullDomainName:Q};throw C}}catch(W){let J=String(W),E=J.includes("Operation timed out after")||J.includes("Operation timeout after")||J.includes("timeout")||J.includes("Timeout")||J.includes("Navigation timeout"),T=J.includes("No target found")||J.includes("targetId")||J.includes("Target page, context or browser has been closed")||J.includes("Protocol error")||J.includes("Connection closed")||J.includes("Assertion error")||J.includes("Browser has been closed")||J.includes("Target closed")||J.includes("Session closed")||J.includes("WebSocket connection closed");if(E)console.error(`Timeout error for ${Q}:`,J.substring(0,200)),await new Promise((O)=>setTimeout(O,1000*q));else if(T){if(console.error(`Browser connection error for ${Q}:`,J.substring(0,200)),Y.browser)try{await Y.browser.close().catch(()=>{})}catch{}await new Promise((O)=>setTimeout(O,3000*q))}if(q>=Z){if(console.error(`Failed to fetch package ${Q} after ${q} attempts:`,W),X){let O=F.join(h.cwd(),`${Q.replace(/\//g,"-")}-error.txt`);H.writeFileSync(O,`Error fetching ${Q}:
|
|
37
37
|
${W.toString()}
|
|
38
38
|
|