@gjsify/cli 0.64.44 → 0.64.45

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/cli.gjs.mjs CHANGED
@@ -146,7 +146,7 @@ fi
146
146
  `)}`:``;n.fail(N(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(C).length,Object.keys(C).join(`, `)+S))}},F.unknownArguments=function unknownArguments(S,C,I,H,W=!0){let q=t.getInternalMethods().getCommandInstance().getCommands(),Y=[],X=t.getInternalMethods().getContext();if(Object.keys(S).forEach(n=>{!zp.includes(n)&&!Object.prototype.hasOwnProperty.call(I,n)&&!Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),n)&&!F.isValidAndSomeAliasIsNotNew(n,C)&&Y.push(n)}),W&&(X.commands.length>0||q.length>0||H)&&S._.slice(X.commands.length).forEach(t=>{q.includes(``+t)||Y.push(``+t)}),W){let n=t.getDemandedCommands()._?.max||0,C=X.commands.length+n;C<S._.length&&S._.slice(C).forEach(t=>{t=String(t),!X.commands.includes(t)&&!Y.includes(t)&&Y.push(t)})}Y.length&&n.fail(N(`Unknown argument: %s`,`Unknown arguments: %s`,Y.length,Y.map(t=>t.trim()?t:`"${t}"`).join(`, `)))},F.unknownCommands=function unknownCommands(S){let C=t.getInternalMethods().getCommandInstance().getCommands(),F=[],I=t.getInternalMethods().getContext();return(I.commands.length>0||C.length>0)&&S._.slice(I.commands.length).forEach(t=>{C.includes(``+t)||F.push(``+t)}),F.length>0?(n.fail(N(`Unknown command: %s`,`Unknown commands: %s`,F.length,F.join(`, `))),!0):!1},F.isValidAndSomeAliasIsNotNew=function isValidAndSomeAliasIsNotNew(n,S){if(!Object.prototype.hasOwnProperty.call(S,n))return!1;let C=t.parsed.newAliases;return[n,...S[n]].some(t=>!Object.prototype.hasOwnProperty.call(C,t)||!C[n])},F.limitedChoices=function limitedChoices(S){let N=t.getOptions(),F={};if(!Object.keys(N.choices).length)return;Object.keys(S).forEach(t=>{zp.indexOf(t)===-1&&Object.prototype.hasOwnProperty.call(N.choices,t)&&[].concat(S[t]).forEach(n=>{N.choices[t].indexOf(n)===-1&&n!==void 0&&(F[t]=(F[t]||[]).concat(n))})});let I=Object.keys(F);if(!I.length)return;let H=C(`Invalid values:`);I.forEach(t=>{H+=`\n ${C(`Argument: %s, Given: %s, Choices: %s`,t,n.stringifiedValues(F[t]),n.stringifiedValues(N.choices[t]))}`}),n.fail(H)};let I={};F.implies=function implies(n,C){argsert(`<string|object> [array|number|string]`,[n,C],arguments.length),typeof n==`object`?Object.keys(n).forEach(t=>{F.implies(t,n[t])}):(t.global(n),I[n]||(I[n]=[]),Array.isArray(C)?C.forEach(t=>F.implies(n,t)):(assertNotStrictEqual(C,void 0,S),I[n].push(C)))},F.getImplied=function getImplied(){return I};function keyExists(t,n){let S=Number(n);return n=isNaN(S)?n:S,typeof n==`number`?n=t._.length>=n:n.match(/^--no-.+/)?(n=n.match(/^--no-(.+)/)[1],n=!Object.prototype.hasOwnProperty.call(t,n)):n=Object.prototype.hasOwnProperty.call(t,n),n}F.implications=function implications(t){let S=[];if(Object.keys(I).forEach(n=>{let C=n;(I[n]||[]).forEach(n=>{let N=C,F=n;N=keyExists(t,N),n=keyExists(t,n),N&&!n&&S.push(` ${C} -> ${F}`)})}),S.length){let t=`${C(`Implications failed:`)}\n`;S.forEach(n=>{t+=n}),n.fail(t)}};let H={};F.conflicts=function conflicts(n,S){argsert(`<string|object> [array|string]`,[n,S],arguments.length),typeof n==`object`?Object.keys(n).forEach(t=>{F.conflicts(t,n[t])}):(t.global(n),H[n]||(H[n]=[]),Array.isArray(S)?S.forEach(t=>F.conflicts(n,t)):H[n].push(S))},F.getConflicting=()=>H,F.conflicting=function conflictingFn(N){Object.keys(N).forEach(t=>{H[t]&&H[t].forEach(S=>{S&&N[t]!==void 0&&N[S]!==void 0&&n.fail(C(`Arguments %s and %s are mutually exclusive`,t,S))})}),t.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(H).forEach(t=>{H[t].forEach(F=>{F&&N[S.Parser.camelCase(t)]!==void 0&&N[S.Parser.camelCase(F)]!==void 0&&n.fail(C(`Arguments %s and %s are mutually exclusive`,t,F))})})},F.recommendCommands=function recommendCommands(t,S){S=S.sort((t,n)=>n.length-t.length);let N=null,F=1/0;for(let n=0,C;(C=S[n])!==void 0;n++){let n=levenshtein(t,C);n<=3&&n<F&&(F=n,N=C)}N&&n.fail(C(`Did you mean %s?`,N))},F.reset=function reset(t){return I=objFilter(I,n=>!t[n]),H=objFilter(H,n=>!t[n]),F};let W=[];return F.freeze=function freeze(){W.push({implied:I,conflicting:H})},F.unfreeze=function unfreeze(){let t=W.pop();assertNotStrictEqual(t,void 0,S),{implied:I,conflicting:H}=t},F}var zp,Bp=__esmMin(()=>{Ep(),Sp(),Rp(),jp(),zp=[`$0`,`--`,`_`]});function YargsFactory(t){return(n=[],S=t.process.cwd(),C)=>{let N=new YargsInstance(n,S,C,t);return Object.defineProperty(N,"argv",{get:()=>N.parse(),enumerable:!0}),N.help(),N.version(),N}}function isYargsInstance(t){return!!t&&typeof t.getInternalMethods==`function`}var __classPrivateFieldSet,__classPrivateFieldGet,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,YargsInstance,oh=__esmMin(()=>{_e(),Ap(),Sp(),Bl(),Np(),Ep(),Lp(),Bp(),jp(),Ul(),Dp(),Cp(),Op(),Mp(),__classPrivateFieldSet=function(t,n,S,C,N){if(C===`m`)throw TypeError(`Private method is not writable`);if(C===`a`&&!N)throw TypeError(`Private accessor was defined without a setter`);if(typeof n==`function`?t!==n||!N:!n.has(t))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return C===`a`?N.call(t,S):N?N.value=S:n.set(t,S),S},__classPrivateFieldGet=function(t,n,S,C){if(S===`a`&&!C)throw TypeError(`Private accessor was defined without a getter`);if(typeof n==`function`?t!==n||!C:!n.has(t))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return S===`m`?C:S===`a`?C.call(t):C?C.value:n.get(t)},Cm=Symbol(`copyDoubleDash`),wm=Symbol(`copyDoubleDash`),Tm=Symbol(`deleteFromParserHintObject`),Em=Symbol(`emitWarning`),Dm=Symbol(`freeze`),Om=Symbol(`getDollarZero`),km=Symbol(`getParserConfiguration`),Am=Symbol(`getUsageConfiguration`),jm=Symbol(`guessLocale`),Mm=Symbol(`guessVersion`),Nm=Symbol(`parsePositionalNumbers`),Pm=Symbol(`pkgUp`),Fm=Symbol(`populateParserHintArray`),Im=Symbol(`populateParserHintSingleValueDictionary`),Lm=Symbol(`populateParserHintArrayDictionary`),Rm=Symbol(`populateParserHintDictionary`),zm=Symbol(`sanitizeKey`),Bm=Symbol(`setKey`),Vm=Symbol(`unfreeze`),Hm=Symbol(`validateAsync`),Um=Symbol(`getCommandInstance`),Wm=Symbol(`getContext`),Gm=Symbol(`getHasOutput`),Km=Symbol(`getLoggerInstance`),qm=Symbol(`getParseContext`),Jm=Symbol(`getUsageInstance`),Ym=Symbol(`getValidationInstance`),Xm=Symbol(`hasParseCallback`),Zm=Symbol(`isGlobalContext`),Qm=Symbol(`postProcess`),$m=Symbol(`rebase`),eh=Symbol(`reset`),th=Symbol(`runYargsParserAndExecuteCommands`),nh=Symbol(`runValidation`),rh=Symbol(`setHasOutput`),ih=Symbol(`kTrackManuallySetKeys`),ah=`en_US`,YargsInstance=class{constructor(t=[],n,S,C){this.customScriptName=!1,this.parsed=!1,Vp.set(this,void 0),Hp.set(this,void 0),Up.set(this,{commands:[],fullCommands:[]}),Wp.set(this,null),Gp.set(this,null),Kp.set(this,`show-hidden`),qp.set(this,null),Jp.set(this,!0),Yp.set(this,{}),Xp.set(this,!0),Zp.set(this,[]),Qp.set(this,void 0),$p.set(this,{}),em.set(this,!1),tm.set(this,null),nm.set(this,!0),im.set(this,void 0),am.set(this,``),om.set(this,void 0),sm.set(this,void 0),cm.set(this,{}),lm.set(this,null),um.set(this,null),dm.set(this,{}),fm.set(this,{}),pm.set(this,void 0),mm.set(this,!1),hm.set(this,void 0),gm.set(this,!1),_m.set(this,!1),vm.set(this,!1),ym.set(this,void 0),bm.set(this,{}),xm.set(this,null),Sm.set(this,void 0),__classPrivateFieldSet(this,hm,C,`f`),__classPrivateFieldSet(this,pm,t,`f`),__classPrivateFieldSet(this,Hp,n,`f`),__classPrivateFieldSet(this,sm,S,`f`),__classPrivateFieldSet(this,Qp,new GlobalMiddleware(this),`f`),this.$0=this[Om](),this[eh](),__classPrivateFieldSet(this,Vp,__classPrivateFieldGet(this,Vp,`f`),`f`),__classPrivateFieldSet(this,ym,__classPrivateFieldGet(this,ym,`f`),`f`),__classPrivateFieldSet(this,Sm,__classPrivateFieldGet(this,Sm,`f`),`f`),__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`),`f`),__classPrivateFieldGet(this,om,`f`).showHiddenOpt=__classPrivateFieldGet(this,Kp,`f`),__classPrivateFieldSet(this,im,this[wm](),`f`),__classPrivateFieldGet(this,hm,`f`).y18n.setLocale(ah)}addHelpOpt(t,n){return argsert(`[string|boolean] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,tm,`f`)&&(this[Tm](__classPrivateFieldGet(this,tm,`f`)),__classPrivateFieldSet(this,tm,null,`f`)),t===!1&&n===void 0?this:(__classPrivateFieldSet(this,tm,typeof t==`string`?t:`help`,`f`),this.boolean(__classPrivateFieldGet(this,tm,`f`)),this.describe(__classPrivateFieldGet(this,tm,`f`),n||__classPrivateFieldGet(this,ym,`f`).deferY18nLookup(`Show help`)),this)}help(t,n){return this.addHelpOpt(t,n)}addShowHiddenOpt(t,n){if(argsert(`[string|boolean] [string]`,[t,n],arguments.length),t===!1&&n===void 0)return this;let S=typeof t==`string`?t:__classPrivateFieldGet(this,Kp,`f`);return this.boolean(S),this.describe(S,n||__classPrivateFieldGet(this,ym,`f`).deferY18nLookup(`Show hidden options`)),__classPrivateFieldGet(this,om,`f`).showHiddenOpt=S,this}showHidden(t,n){return this.addShowHiddenOpt(t,n)}alias(t,n){return argsert(`<object|string|array> [string|array]`,[t,n],arguments.length),this[Lm](this.alias.bind(this),`alias`,t,n),this}array(t){return argsert(`<array|string>`,[t],arguments.length),this[Fm](`array`,t),this[ih](t),this}boolean(t){return argsert(`<array|string>`,[t],arguments.length),this[Fm](`boolean`,t),this[ih](t),this}check(t,n){return argsert(`<function> [boolean]`,[t,n],arguments.length),this.middleware((n,S)=>maybeAsyncResult(()=>t(n,S.getOptions()),S=>(S?(typeof S==`string`||S instanceof Error)&&__classPrivateFieldGet(this,ym,`f`).fail(S.toString(),S):__classPrivateFieldGet(this,ym,`f`).fail(__classPrivateFieldGet(this,hm,`f`).y18n.__(`Argument check failed: %s`,t.toString())),n),t=>(__classPrivateFieldGet(this,ym,`f`).fail(t.message?t.message:t.toString(),t),n)),!1,n),this}choices(t,n){return argsert(`<object|string|array> [string|array]`,[t,n],arguments.length),this[Lm](this.choices.bind(this),`choices`,t,n),this}coerce(t,n){if(argsert(`<object|string|array> [function]`,[t,n],arguments.length),Array.isArray(t)){if(!n)throw new zl(`coerce callback must be provided`);for(let S of t)this.coerce(S,n);return this}else if(typeof t==`object`){for(let n of Object.keys(t))this.coerce(n,t[n]);return this}if(!n)throw new zl(`coerce callback must be provided`);let S=t;return __classPrivateFieldGet(this,om,`f`).key[S]=!0,__classPrivateFieldGet(this,Qp,`f`).addCoerceMiddleware((t,C)=>{let N=C.getAliases()[S]??[],F=[S,...N].filter(n=>Object.prototype.hasOwnProperty.call(t,n));return F.length===0?t:maybeAsyncResult(()=>n(t[F[0]]),n=>(F.forEach(S=>{t[S]=n}),t),t=>{throw new zl(t.message)})},S),this}conflicts(t,n){return argsert(`<string|object> [string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Sm,`f`).conflicts(t,n),this}config(t=`config`,n,S){return argsert(`[object|string] [string|function] [function]`,[t,n,S],arguments.length),typeof t==`object`&&!Array.isArray(t)?(t=applyExtends(t,__classPrivateFieldGet(this,Hp,`f`),this[km]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,hm,`f`)),__classPrivateFieldGet(this,om,`f`).configObjects=(__classPrivateFieldGet(this,om,`f`).configObjects||[]).concat(t),this):(typeof n==`function`&&(S=n,n=void 0),this.describe(t,n||__classPrivateFieldGet(this,ym,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(t)?t:[t]).forEach(t=>{__classPrivateFieldGet(this,om,`f`).config[t]=S||!0}),this)}completion(t,n,S){return argsert(`[string] [string|boolean|function] [function]`,[t,n,S],arguments.length),typeof n==`function`&&(S=n,n=void 0),__classPrivateFieldSet(this,Gp,t||__classPrivateFieldGet(this,Gp,`f`)||`completion`,`f`),!n&&n!==!1&&(n=`generate completion script`),this.command(__classPrivateFieldGet(this,Gp,`f`),n),S&&__classPrivateFieldGet(this,Wp,`f`).registerFunction(S),this}command(t,n,S,C,N,F){return argsert(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[t,n,S,C,N,F],arguments.length),__classPrivateFieldGet(this,Vp,`f`).addHandler(t,n,S,C,N,F),this}commands(t,n,S,C,N,F){return this.command(t,n,S,C,N,F)}commandDir(t,n){argsert(`<string> [object]`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,sm,`f`)||__classPrivateFieldGet(this,hm,`f`).require;return __classPrivateFieldGet(this,Vp,`f`).addDirectory(t,S,__classPrivateFieldGet(this,hm,`f`).getCallerFile(),n),this}count(t){return argsert(`<array|string>`,[t],arguments.length),this[Fm](`count`,t),this[ih](t),this}default(t,n,S){return argsert(`<object|string|array> [*] [string]`,[t,n,S],arguments.length),S&&(assertSingleKey(t,__classPrivateFieldGet(this,hm,`f`)),__classPrivateFieldGet(this,om,`f`).defaultDescription[t]=S),typeof n==`function`&&(assertSingleKey(t,__classPrivateFieldGet(this,hm,`f`)),__classPrivateFieldGet(this,om,`f`).defaultDescription[t]||(__classPrivateFieldGet(this,om,`f`).defaultDescription[t]=__classPrivateFieldGet(this,ym,`f`).functionDescription(n)),n=n.call()),this[Im](this.default.bind(this),`default`,t,n),this}defaults(t,n,S){return this.default(t,n,S)}demandCommand(t=1,n,S,C){return argsert(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[t,n,S,C],arguments.length),typeof n!=`number`&&(S=n,n=1/0),this.global(`_`,!1),__classPrivateFieldGet(this,om,`f`).demandedCommands._={min:t,max:n,minMsg:S,maxMsg:C},this}demand(t,n,S){return Array.isArray(n)?(n.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,hm,`f`)),this.demandOption(t,S)}),n=1/0):typeof n!=`number`&&(S=n,n=1/0),typeof t==`number`?(assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,hm,`f`)),this.demandCommand(t,n,S,S)):Array.isArray(t)?t.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,hm,`f`)),this.demandOption(t,S)}):typeof S==`string`?this.demandOption(t,S):(S===!0||S===void 0)&&this.demandOption(t),this}demandOption(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[Im](this.demandOption.bind(this),`demandedOptions`,t,n),this}deprecateOption(t,n){return argsert(`<string> [string|boolean]`,[t,n],arguments.length),__classPrivateFieldGet(this,om,`f`).deprecatedOptions[t]=n,this}describe(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[Bm](t,!0),__classPrivateFieldGet(this,ym,`f`).describe(t,n),this}detectLocale(t){return argsert(`<boolean>`,[t],arguments.length),__classPrivateFieldSet(this,Jp,t,`f`),this}env(t){return argsert(`[string|boolean]`,[t],arguments.length),t===!1?delete __classPrivateFieldGet(this,om,`f`).envPrefix:__classPrivateFieldGet(this,om,`f`).envPrefix=t||``,this}epilogue(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,ym,`f`).epilog(t),this}epilog(t){return this.epilogue(t)}example(t,n){return argsert(`<string|array> [string]`,[t,n],arguments.length),Array.isArray(t)?t.forEach(t=>this.example(...t)):__classPrivateFieldGet(this,ym,`f`).example(t,n),this}exit(t,n){__classPrivateFieldSet(this,em,!0,`f`),__classPrivateFieldSet(this,qp,n,`f`),__classPrivateFieldGet(this,Xp,`f`)&&__classPrivateFieldGet(this,hm,`f`).process.exit(t)}exitProcess(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Xp,t,`f`),this}fail(t){if(argsert(`<function|boolean>`,[t],arguments.length),typeof t==`boolean`&&t!==!1)throw new zl(`Invalid first argument. Expected function or boolean 'false'`);return __classPrivateFieldGet(this,ym,`f`).failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,n){return argsert(`<array> [function]`,[t,n],arguments.length),n?__classPrivateFieldGet(this,Wp,`f`).getCompletion(t,n):new Promise((n,S)=>{__classPrivateFieldGet(this,Wp,`f`).getCompletion(t,(t,C)=>{t?S(t):n(C)})})}getDemandedOptions(){return argsert([],0),__classPrivateFieldGet(this,om,`f`).demandedOptions}getDemandedCommands(){return argsert([],0),__classPrivateFieldGet(this,om,`f`).demandedCommands}getDeprecatedOptions(){return argsert([],0),__classPrivateFieldGet(this,om,`f`).deprecatedOptions}getDetectLocale(){return __classPrivateFieldGet(this,Jp,`f`)}getExitProcess(){return __classPrivateFieldGet(this,Xp,`f`)}getGroups(){return Object.assign({},__classPrivateFieldGet(this,$p,`f`),__classPrivateFieldGet(this,fm,`f`))}getHelp(){if(__classPrivateFieldSet(this,em,!0,`f`),!__classPrivateFieldGet(this,ym,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[th](__classPrivateFieldGet(this,pm,`f`),void 0,void 0,0,!0);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,ym,`f`).help())}let t=__classPrivateFieldGet(this,Vp,`f`).runDefaultBuilderOn(this);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,ym,`f`).help())}return Promise.resolve(__classPrivateFieldGet(this,ym,`f`).help())}getOptions(){return __classPrivateFieldGet(this,om,`f`)}getStrict(){return __classPrivateFieldGet(this,gm,`f`)}getStrictCommands(){return __classPrivateFieldGet(this,_m,`f`)}getStrictOptions(){return __classPrivateFieldGet(this,vm,`f`)}global(t,n){return argsert(`<string|array> [boolean]`,[t,n],arguments.length),t=[].concat(t),n===!1?t.forEach(t=>{__classPrivateFieldGet(this,om,`f`).local.includes(t)||__classPrivateFieldGet(this,om,`f`).local.push(t)}):__classPrivateFieldGet(this,om,`f`).local=__classPrivateFieldGet(this,om,`f`).local.filter(n=>t.indexOf(n)===-1),this}group(t,n){argsert(`<string|array> <string>`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,fm,`f`)[n]||__classPrivateFieldGet(this,$p,`f`)[n];__classPrivateFieldGet(this,fm,`f`)[n]&&delete __classPrivateFieldGet(this,fm,`f`)[n];let C={};return __classPrivateFieldGet(this,$p,`f`)[n]=(S||[]).concat(t).filter(t=>C[t]?!1:C[t]=!0),this}hide(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,om,`f`).hiddenOptions.push(t),this}implies(t,n){return argsert(`<string|object> [number|string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Sm,`f`).implies(t,n),this}locale(t){return argsert(`[string]`,[t],arguments.length),t===void 0?(this[jm](),__classPrivateFieldGet(this,hm,`f`).y18n.getLocale()):(__classPrivateFieldSet(this,Jp,!1,`f`),__classPrivateFieldGet(this,hm,`f`).y18n.setLocale(t),this)}middleware(t,n,S){return __classPrivateFieldGet(this,Qp,`f`).addMiddleware(t,!!n,S)}nargs(t,n){return argsert(`<string|object|array> [number]`,[t,n],arguments.length),this[Im](this.nargs.bind(this),`narg`,t,n),this}normalize(t){return argsert(`<array|string>`,[t],arguments.length),this[Fm](`normalize`,t),this}number(t){return argsert(`<array|string>`,[t],arguments.length),this[Fm](`number`,t),this[ih](t),this}option(t,n){if(argsert(`<string|object> [object]`,[t,n],arguments.length),typeof t==`object`)Object.keys(t).forEach(n=>{this.options(n,t[n])});else{typeof n!=`object`&&(n={}),this[ih](t),__classPrivateFieldGet(this,xm,`f`)&&(t===`version`||n?.alias===`version`)&&this[Em]([`"version" is a reserved word.`,`Please do one of the following:`,'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)",`- Use a different option key`,`https://yargs.js.org/docs/#api-reference-version`].join(`
147
147
  `),void 0,`versionWarning`),__classPrivateFieldGet(this,om,`f`).key[t]=!0,n.alias&&this.alias(t,n.alias);let S=n.deprecate||n.deprecated;S&&this.deprecateOption(t,S);let C=n.demand||n.required||n.require;C&&this.demand(t,C),n.demandOption&&this.demandOption(t,typeof n.demandOption==`string`?n.demandOption:void 0),n.conflicts&&this.conflicts(t,n.conflicts),`default`in n&&this.default(t,n.default),n.implies!==void 0&&this.implies(t,n.implies),n.nargs!==void 0&&this.nargs(t,n.nargs),n.config&&this.config(t,n.configParser),n.normalize&&this.normalize(t),n.choices&&this.choices(t,n.choices),n.coerce&&this.coerce(t,n.coerce),n.group&&this.group(t,n.group),(n.boolean||n.type===`boolean`)&&(this.boolean(t),n.alias&&this.boolean(n.alias)),(n.array||n.type===`array`)&&(this.array(t),n.alias&&this.array(n.alias)),(n.number||n.type===`number`)&&(this.number(t),n.alias&&this.number(n.alias)),(n.string||n.type===`string`)&&(this.string(t),n.alias&&this.string(n.alias)),(n.count||n.type===`count`)&&this.count(t),typeof n.global==`boolean`&&this.global(t,n.global),n.defaultDescription&&(__classPrivateFieldGet(this,om,`f`).defaultDescription[t]=n.defaultDescription),n.skipValidation&&this.skipValidation(t);let N=n.describe||n.description||n.desc,F=__classPrivateFieldGet(this,ym,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(F,t)||typeof N==`string`)&&this.describe(t,N),n.hidden&&this.hide(t),n.requiresArg&&this.requiresArg(t)}return this}options(t,n){return this.option(t,n)}parse(t,n,S){argsert(`[string|array] [function|boolean|object] [function]`,[t,n,S],arguments.length),this[Dm](),t===void 0&&(t=__classPrivateFieldGet(this,pm,`f`)),typeof n==`object`&&(__classPrivateFieldSet(this,um,n,`f`),n=S),typeof n==`function`&&(__classPrivateFieldSet(this,lm,n,`f`),n=!1),n||__classPrivateFieldSet(this,pm,t,`f`),__classPrivateFieldGet(this,lm,`f`)&&__classPrivateFieldSet(this,Xp,!1,`f`);let C=this[th](t,!!n),N=this.parsed;return __classPrivateFieldGet(this,Wp,`f`).setParsed(this.parsed),isPromise(C)?C.then(t=>(__classPrivateFieldGet(this,lm,`f`)&&__classPrivateFieldGet(this,lm,`f`).call(this,__classPrivateFieldGet(this,qp,`f`),t,__classPrivateFieldGet(this,am,`f`)),t)).catch(t=>{throw __classPrivateFieldGet(this,lm,`f`)&&__classPrivateFieldGet(this,lm,`f`)(t,this.parsed.argv,__classPrivateFieldGet(this,am,`f`)),t}).finally(()=>{this[Vm](),this.parsed=N}):(__classPrivateFieldGet(this,lm,`f`)&&__classPrivateFieldGet(this,lm,`f`).call(this,__classPrivateFieldGet(this,qp,`f`),C,__classPrivateFieldGet(this,am,`f`)),this[Vm](),this.parsed=N,C)}parseAsync(t,n,S){let C=this.parse(t,n,S);return isPromise(C)?C:Promise.resolve(C)}parseSync(t,n,S){let C=this.parse(t,n,S);if(isPromise(C))throw new zl(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return C}parserConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,cm,t,`f`),this}pkgConf(t,n){argsert(`<string> [string]`,[t,n],arguments.length);let S=null,C=this[Pm](n||__classPrivateFieldGet(this,Hp,`f`));return C[t]&&typeof C[t]==`object`&&(S=applyExtends(C[t],n||__classPrivateFieldGet(this,Hp,`f`),this[km]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,hm,`f`)),__classPrivateFieldGet(this,om,`f`).configObjects=(__classPrivateFieldGet(this,om,`f`).configObjects||[]).concat(S)),this}positional(t,n){argsert(`<string> <object>`,[t,n],arguments.length);let S=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];n=objFilter(n,(t,n)=>t===`type`&&![`string`,`number`,`boolean`].includes(n)?!1:S.includes(t));let C=__classPrivateFieldGet(this,Up,`f`).fullCommands[__classPrivateFieldGet(this,Up,`f`).fullCommands.length-1],N=C?__classPrivateFieldGet(this,Vp,`f`).cmdToParseOptions(C):{array:[],alias:{},default:{},demand:{}};return objectKeys(N).forEach(S=>{let C=N[S];Array.isArray(C)?C.indexOf(t)!==-1&&(n[S]=!0):C[t]&&!(S in n)&&(n[S]=C[t])}),this.group(t,__classPrivateFieldGet(this,ym,`f`).getPositionalGroupName()),this.option(t,n)}recommendCommands(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,mm,t,`f`),this}required(t,n,S){return this.demand(t,n,S)}require(t,n,S){return this.demand(t,n,S)}requiresArg(t){return argsert(`<array|string|object> [number]`,[t],arguments.length),typeof t==`string`&&__classPrivateFieldGet(this,om,`f`).narg[t]||this[Im](this.requiresArg.bind(this),`narg`,t,NaN),this}showCompletionScript(t,n){return argsert(`[string] [string]`,[t,n],arguments.length),t||=this.$0,__classPrivateFieldGet(this,im,`f`).log(__classPrivateFieldGet(this,Wp,`f`).generateCompletionScript(t,n||__classPrivateFieldGet(this,Gp,`f`)||`completion`)),this}showHelp(t){if(argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldSet(this,em,!0,`f`),!__classPrivateFieldGet(this,ym,`f`).hasCachedHelpMessage()){if(!this.parsed){let n=this[th](__classPrivateFieldGet(this,pm,`f`),void 0,void 0,0,!0);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,ym,`f`).showHelp(t)}),this}let n=__classPrivateFieldGet(this,Vp,`f`).runDefaultBuilderOn(this);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,ym,`f`).showHelp(t)}),this}return __classPrivateFieldGet(this,ym,`f`).showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,n){return argsert(`[boolean|string] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,ym,`f`).showHelpOnFail(t,n),this}showVersion(t){return argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldGet(this,ym,`f`).showVersion(t),this}skipValidation(t){return argsert(`<array|string>`,[t],arguments.length),this[Fm](`skipValidation`,t),this}strict(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,gm,t!==!1,`f`),this}strictCommands(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,_m,t!==!1,`f`),this}strictOptions(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,vm,t!==!1,`f`),this}string(t){return argsert(`<array|string>`,[t],arguments.length),this[Fm](`string`,t),this[ih](t),this}terminalWidth(){return argsert([],0),__classPrivateFieldGet(this,hm,`f`).process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Jp,!1,`f`),__classPrivateFieldGet(this,hm,`f`).y18n.updateLocale(t),this}usage(t,n,S,C){if(argsert(`<string|null|undefined> [string|boolean] [function|object] [function]`,[t,n,S,C],arguments.length),n!==void 0){if(assertNotStrictEqual(t,null,__classPrivateFieldGet(this,hm,`f`)),(t||``).match(/^\$0( |$)/))return this.command(t,n,S,C);throw new zl(`.usage() description must start with $0 if being used as alias for .command()`)}else return __classPrivateFieldGet(this,ym,`f`).usage(t),this}usageConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,bm,t,`f`),this}version(t,n,S){let C=`version`;if(argsert(`[boolean|string] [string] [string]`,[t,n,S],arguments.length),__classPrivateFieldGet(this,xm,`f`)&&(this[Tm](__classPrivateFieldGet(this,xm,`f`)),__classPrivateFieldGet(this,ym,`f`).version(void 0),__classPrivateFieldSet(this,xm,null,`f`)),arguments.length===0)S=this[Mm](),t=C;else if(arguments.length===1){if(t===!1)return this;S=t,t=C}else arguments.length===2&&(S=n,n=void 0);return __classPrivateFieldSet(this,xm,typeof t==`string`?t:C,`f`),n||=__classPrivateFieldGet(this,ym,`f`).deferY18nLookup(`Show version number`),__classPrivateFieldGet(this,ym,`f`).version(S||void 0),this.boolean(__classPrivateFieldGet(this,xm,`f`)),this.describe(__classPrivateFieldGet(this,xm,`f`),n),this}wrap(t){return argsert(`<number|null|undefined>`,[t],arguments.length),__classPrivateFieldGet(this,ym,`f`).wrap(t),this}[(Vp=new WeakMap,Hp=new WeakMap,Up=new WeakMap,Wp=new WeakMap,Gp=new WeakMap,Kp=new WeakMap,qp=new WeakMap,Jp=new WeakMap,Yp=new WeakMap,Xp=new WeakMap,Zp=new WeakMap,Qp=new WeakMap,$p=new WeakMap,em=new WeakMap,tm=new WeakMap,nm=new WeakMap,im=new WeakMap,am=new WeakMap,om=new WeakMap,sm=new WeakMap,cm=new WeakMap,lm=new WeakMap,um=new WeakMap,dm=new WeakMap,fm=new WeakMap,pm=new WeakMap,mm=new WeakMap,hm=new WeakMap,gm=new WeakMap,_m=new WeakMap,vm=new WeakMap,ym=new WeakMap,bm=new WeakMap,xm=new WeakMap,Sm=new WeakMap,Cm)](t){if(!t._||!t[`--`])return t;t._.push.apply(t._,t[`--`]);try{delete t[`--`]}catch{}return t}[wm](){return{log:(...t)=>{this[Xm]()||ge.log(...t),__classPrivateFieldSet(this,em,!0,`f`),__classPrivateFieldGet(this,am,`f`).length&&__classPrivateFieldSet(this,am,__classPrivateFieldGet(this,am,`f`)+`
148
148
  `,`f`),__classPrivateFieldSet(this,am,__classPrivateFieldGet(this,am,`f`)+t.join(` `),`f`)},error:(...t)=>{this[Xm]()||ge.error(...t),__classPrivateFieldSet(this,em,!0,`f`),__classPrivateFieldGet(this,am,`f`).length&&__classPrivateFieldSet(this,am,__classPrivateFieldGet(this,am,`f`)+`
149
- `,`f`),__classPrivateFieldSet(this,am,__classPrivateFieldGet(this,am,`f`)+t.join(` `),`f`)}}}[Tm](t){objectKeys(__classPrivateFieldGet(this,om,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,om,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,ym,`f`).getDescriptions()[t]}[Em](t,n,S){__classPrivateFieldGet(this,Yp,`f`)[S]||(__classPrivateFieldGet(this,hm,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Yp,`f`)[S]=!0)}[Dm](){__classPrivateFieldGet(this,Zp,`f`).push({options:__classPrivateFieldGet(this,om,`f`),configObjects:__classPrivateFieldGet(this,om,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Xp,`f`),groups:__classPrivateFieldGet(this,$p,`f`),strict:__classPrivateFieldGet(this,gm,`f`),strictCommands:__classPrivateFieldGet(this,_m,`f`),strictOptions:__classPrivateFieldGet(this,vm,`f`),completionCommand:__classPrivateFieldGet(this,Gp,`f`),output:__classPrivateFieldGet(this,am,`f`),exitError:__classPrivateFieldGet(this,qp,`f`),hasOutput:__classPrivateFieldGet(this,em,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,lm,`f`),parseContext:__classPrivateFieldGet(this,um,`f`)}),__classPrivateFieldGet(this,ym,`f`).freeze(),__classPrivateFieldGet(this,Sm,`f`).freeze(),__classPrivateFieldGet(this,Vp,`f`).freeze(),__classPrivateFieldGet(this,Qp,`f`).freeze()}[Om](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,hm,`f`).process.argv()[0])?__classPrivateFieldGet(this,hm,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,hm,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[$m](__classPrivateFieldGet(this,Hp,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,hm,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,hm,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,hm,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,hm,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,hm,`f`).path.dirname(__classPrivateFieldGet(this,hm,`f`).process.execPath())}/`,``)),t}[km](){return __classPrivateFieldGet(this,cm,`f`)}[Am](){return __classPrivateFieldGet(this,bm,`f`)}[jm](){if(!__classPrivateFieldGet(this,Jp,`f`))return;let t=__classPrivateFieldGet(this,hm,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,hm,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,hm,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,hm,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[Mm](){return this[Pm]().version||`unknown`}[Nm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,hm,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[Pm](t){let n=t||`*`;if(__classPrivateFieldGet(this,dm,`f`)[n])return __classPrivateFieldGet(this,dm,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,hm,`f`).mainFilename;__classPrivateFieldGet(this,hm,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,hm,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,hm,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,hm,`f`)),S=JSON.parse(__classPrivateFieldGet(this,hm,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,dm,`f`)[n]=S||{},__classPrivateFieldGet(this,dm,`f`)[n]}[Fm](t,n){n=[].concat(n),n.forEach(n=>{n=this[zm](n),__classPrivateFieldGet(this,om,`f`)[t].push(n)})}[Im](t,n,S,C){this[Rm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,om,`f`)[t][n]=S})}[Lm](t,n,S,C){this[Rm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,om,`f`)[t][n]=(__classPrivateFieldGet(this,om,`f`)[t][n]||[]).concat(S)})}[Rm](t,n,S,C,N){if(Array.isArray(S))S.forEach(n=>{t(n,C)});else if((t=>typeof t==`object`)(S))for(let n of objectKeys(S))t(n,S[n]);else N(n,this[zm](S),C)}[zm](t){return t===`__proto__`?`___proto___`:t}[Bm](t,n){return this[Im](this[Bm].bind(this),`key`,t,n),this}[Vm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Zp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,hm,`f`));let te;t=this,n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,{options:{set value(n){__classPrivateFieldSet(t,om,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Xp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,$p,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,am,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,qp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,em,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,gm,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,_m,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,vm,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Gp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,lm,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,um,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,om,`f`).configObjects=te,__classPrivateFieldGet(this,ym,`f`).unfreeze(),__classPrivateFieldGet(this,Sm,`f`).unfreeze(),__classPrivateFieldGet(this,Vp,`f`).unfreeze(),__classPrivateFieldGet(this,Qp,`f`).unfreeze()}[Hm](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[Um].bind(this),getContext:this[Wm].bind(this),getHasOutput:this[Gm].bind(this),getLoggerInstance:this[Km].bind(this),getParseContext:this[qm].bind(this),getParserConfiguration:this[km].bind(this),getUsageConfiguration:this[Am].bind(this),getUsageInstance:this[Jm].bind(this),getValidationInstance:this[Ym].bind(this),hasParseCallback:this[Xm].bind(this),isGlobalContext:this[Zm].bind(this),postProcess:this[Qm].bind(this),reset:this[eh].bind(this),runValidation:this[nh].bind(this),runYargsParserAndExecuteCommands:this[th].bind(this),setHasOutput:this[rh].bind(this)}}[Um](){return __classPrivateFieldGet(this,Vp,`f`)}[Wm](){return __classPrivateFieldGet(this,Up,`f`)}[Gm](){return __classPrivateFieldGet(this,em,`f`)}[Km](){return __classPrivateFieldGet(this,im,`f`)}[qm](){return __classPrivateFieldGet(this,um,`f`)||{}}[Jm](){return __classPrivateFieldGet(this,ym,`f`)}[Ym](){return __classPrivateFieldGet(this,Sm,`f`)}[Xm](){return!!__classPrivateFieldGet(this,lm,`f`)}[Zm](){return __classPrivateFieldGet(this,nm,`f`)}[Qm](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[Cm](t)),(this[km]()[`parse-positional-numbers`]||this[km]()[`parse-positional-numbers`]===void 0)&&(t=this[Nm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,Qp,`f`).getMiddleware(),!1)),t)}[eh](t={}){__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,om,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,om,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,fm,`f`),Object.keys(__classPrivateFieldGet(this,$p,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,$p,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,$p,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,om,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,om,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,om,`f`).envPrefix,__classPrivateFieldSet(this,om,n,`f`),__classPrivateFieldSet(this,ym,__classPrivateFieldGet(this,ym,`f`)?__classPrivateFieldGet(this,ym,`f`).reset(S):usage(this,__classPrivateFieldGet(this,hm,`f`)),`f`),__classPrivateFieldSet(this,Sm,__classPrivateFieldGet(this,Sm,`f`)?__classPrivateFieldGet(this,Sm,`f`).reset(S):validation(this,__classPrivateFieldGet(this,ym,`f`),__classPrivateFieldGet(this,hm,`f`)),`f`),__classPrivateFieldSet(this,Vp,__classPrivateFieldGet(this,Vp,`f`)?__classPrivateFieldGet(this,Vp,`f`).reset():command(__classPrivateFieldGet(this,ym,`f`),__classPrivateFieldGet(this,Sm,`f`),__classPrivateFieldGet(this,Qp,`f`),__classPrivateFieldGet(this,hm,`f`)),`f`),__classPrivateFieldGet(this,Wp,`f`)||__classPrivateFieldSet(this,Wp,completion(this,__classPrivateFieldGet(this,ym,`f`),__classPrivateFieldGet(this,Vp,`f`),__classPrivateFieldGet(this,hm,`f`)),`f`),__classPrivateFieldGet(this,Qp,`f`).reset(),__classPrivateFieldSet(this,Gp,null,`f`),__classPrivateFieldSet(this,am,``,`f`),__classPrivateFieldSet(this,qp,null,`f`),__classPrivateFieldSet(this,em,!1,`f`),this.parsed=!1,this}[$m](t,n){return __classPrivateFieldGet(this,hm,`f`).path.relative(t,n)}[th](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,pm,`f`),__classPrivateFieldGet(this,om,`f`).__=__classPrivateFieldGet(this,hm,`f`).y18n.__,__classPrivateFieldGet(this,om,`f`).configuration=this[km]();let I=!!__classPrivateFieldGet(this,om,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,om,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,hm,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,om,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,um,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,tm,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,xm,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,ym,`f`).clearCachedHelpMessage();try{if(this[jm](),n)return this[Qm](q,I,!!S,!1);__classPrivateFieldGet(this,tm,`f`)&&[__classPrivateFieldGet(this,tm,`f`)].concat(X[__classPrivateFieldGet(this,tm,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,nm,!1,`f`);let H=__classPrivateFieldGet(this,Vp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Wp,`f`)?.completionKey?[__classPrivateFieldGet(this,Wp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Wp,`f`)?.completionKey]??[]].some(t=>Object.prototype.hasOwnProperty.call(q,t)):!1,re=Z||ne||N;if(q._.length){if(H.length){let t;for(let n=C||0,F;q._[n]!==void 0;n++)if(F=String(q._[n]),H.includes(F)&&F!==__classPrivateFieldGet(this,Gp,`f`)){let t=__classPrivateFieldGet(this,Vp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[Qm](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Gp,`f`)){t=F;break}!__classPrivateFieldGet(this,Vp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,mm,`f`)&&t&&!re&&__classPrivateFieldGet(this,Sm,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Gp,`f`)&&q._.includes(__classPrivateFieldGet(this,Gp,`f`))&&!ne&&(__classPrivateFieldGet(this,Xp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Vp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,Vp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[Qm](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Xp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Wp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Wp,`f`).getCompletion(n,(t,n)=>{if(t)throw new zl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,im,`f`).log(t)}),this.exit(0)}),this[Qm](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,em,`f`)||(Z?(__classPrivateFieldGet(this,Xp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,im,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Xp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,ym,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,om,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,om,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new zl(W.error.message);if(!ne){let t=this[nh](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,Qp,`f`).getMiddleware(),!0)),Y=this[Hm](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,Qp,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof zl)__classPrivateFieldGet(this,ym,`f`).fail(t.message,t);else throw t}return this[Qm](Y??q,I,!!S,!0)}[nh](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new zl(S.message);__classPrivateFieldGet(this,Sm,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Sm,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,_m,`f`)&&(I=__classPrivateFieldGet(this,Sm,`f`).unknownCommands(F)),__classPrivateFieldGet(this,gm,`f`)&&!I?__classPrivateFieldGet(this,Sm,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,vm,`f`)&&__classPrivateFieldGet(this,Sm,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Sm,`f`).limitedChoices(F),__classPrivateFieldGet(this,Sm,`f`).implications(F),__classPrivateFieldGet(this,Sm,`f`).conflicting(F)}}[rh](){__classPrivateFieldSet(this,em,!0,`f`)}[ih](t){if(typeof t==`string`)__classPrivateFieldGet(this,om,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,om,`f`).key[n]=!0}}}),sh,ch=__esmMin(()=>{xp(),oh(),sh=YargsFactory(bp)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var lh=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.64.44`,"accept-encoding":n.acceptEncoding??`identity`};if(n.npmrc){let C=resolveAuthForUrl(t,n.npmrc);C&&(S.authorization=C)}if(n.headers)for(let[t,C]of Object.entries(n.headers))S[t.toLowerCase()]=C;return S}function resolveAuthForUrl(t,n){let S=pathPrefixes(new URL(t));for(let t of S){let S=n.authTokens[t];if(S)return`Bearer ${S}`;let C=n.basicAuth[t];if(C)return`Basic ${btoa(`${C.username}:${C.password}`)}`}return null}function pathPrefixes(t){let n=t.pathname.split(`/`).filter(Boolean),S=[];for(let C=n.length;C>=0;C--){let N=n.slice(0,C).join(`/`);S.push(N?`//${t.host}/${N}`:`//${t.host}`)}return S}var uh=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,dh=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(t,n){super(`Package not found in registry: ${t} (${n})`),this.name=t,this.url=n,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(t,n){super(`Tarball integrity mismatch for ${t} (expected ${n})`),this.url=t,this.integrity=n,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(t,n,S){let C=Math.round(n/100)/10,N=Math.round(n*S/100)/10;super(`@gjsify/npm-registry: GET ${t} timed out after ${C}s × ${S} attempt(s) (total ~${N}s). This usually means the registry CDN is slow or unreachable.`),this.url=t,this.timeoutMs=n,this.attempts=S,this.name=`RegistryTimeoutError`}},RegistryUnreachableError=class extends Error{url;attempts;elapsedMs;constructor(t,n,S,C){let N=Math.round(S/100)/10,F=C instanceof Error?C.message:String(C);super(`@gjsify/npm-registry: GET ${t} failed after ${n} attempt(s) over ~${N}s: ${F}. This usually means the registry or the network dropped out.`),this.url=t,this.attempts=n,this.elapsedMs=S,this.name=`RegistryUnreachableError`,this.cause=C}}});function registryFor(t,n){if(n&&t.startsWith(`@`)){let S=t.slice(0,t.indexOf(`/`)),C=n.scopes[S];if(C)return ensureTrailingSlash$1(C)}return n?.registry?ensureTrailingSlash$1(n.registry):fh}function parseNpmrc(t){let n={registry:fh,scopes:{},authTokens:{},basicAuth:{}},S=t.split(/\r?\n/),C={};for(let t of S){let S=t.replace(/^\s+|\s+$/g,``);if(!S||S.startsWith(`#`)||S.startsWith(`;`))continue;let N=S.indexOf(`=`);if(N<0)continue;let F=S.slice(0,N).trim(),I=expandEnv(stripQuotes(S.slice(N+1).trim()));if(F===`registry`){n.registry=ensureTrailingSlash$1(I);continue}let H=F.match(/^(@[^:]+):registry$/);if(H){n.scopes[H[1]]=ensureTrailingSlash$1(I);continue}let W=F.match(/^\/\/(.+):_authToken$/);if(W){n.authTokens[normalizeAuthHost(W[1])]=I;continue}let q=F.match(/^\/\/(.+):username$/);if(q){(C[normalizeAuthHost(q[1])]??={}).user=I;continue}let Y=F.match(/^\/\/(.+):_password$/);if(Y){let t=base64Decode$1(I);(C[normalizeAuthHost(Y[1])]??={}).pass=t;continue}}for(let[t,S]of Object.entries(C))S.user&&S.pass!==void 0&&(n.basicAuth[t]={username:S.user,password:S.pass});return n}function normalizeAuthHost(t){return`//${t.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(t){return t.endsWith(`/`)?t:t+`/`}function stripQuotes(t){return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function expandEnv(t){return t.replace(/\$\{([A-Z0-9_]+)\}/gi,(t,n)=>globalThis.process?.env?.[n]??``)}function base64Decode$1(t){return atob(t)}var fh,ph=__esmMin(()=>{fh=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`),__name$1(base64Decode$1,`base64Decode`)});async function fetchWithRetry(t,n,S){let C=S.fetch??globalThis.fetch;if(!C)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let N=Math.max(0,S.retries??5),F=Math.max(0,S.retryDelayMs??1e3),I=Math.max(0,S.timeoutMs??3e4),H=S.retryNotFound??!1,W=Date.now(),q=0,Y,X=0;for(;;){if(n.signal?.aborted)throw signalAbortError(n.signal);let Z=I>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${I}ms`)),I),ne=composeSignals(n.signal,Z?.signal);try{let F=await C(t,{...n,signal:ne}),I=isRetryableStatus(F.status)||H&&F.status===404;if(F.ok||!I||q>=N)return S.read?await S.read(F):F;try{await F.arrayBuffer()}catch{}Y=Error(`HTTP ${F.status} ${F.statusText}`)}catch(S){let C=Z!==null&&Z.signal.aborted,F=n.signal?.aborted===!0;if(C&&!F){if(X++,q>=N)throw new RegistryTimeoutError(t,I,X);Y=S}else if(F)throw signalAbortError(n.signal);else{if(!isRetryableError(S))throw S;if(q>=N)throw new RegistryUnreachableError(t,q+1,Date.now()-W,S);Y=S}}finally{te!==null&&clearTimeout(te)}let re=Math.min(F*2**q,8e3);S.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,n.signal),q++}}function composeSignals(t,n){return t?n?AbortSignal.any([t,n]):t:n}function isRetryableStatus(t){return t===408||t===425||t===429||t===500||t===502||t===503||t===504||t===521||t===522||t===524||t===525}function isRetryableError(t){if(t&&typeof t==`object`&&`name`in t&&t.name===`AbortError`)return!1;if(t instanceof TypeError)return!0;if(t&&typeof t==`object`&&`name`in t){let n=t.name;if(n===`FetchError`)return!0;if(n===`AbortError`)return!1}let n=t?.cause;if(n&&typeof n==`object`&&`code`in n){let t=n.code;if(typeof t==`string`)return t===`ECONNRESET`||t===`ECONNREFUSED`||t===`ENETUNREACH`||t===`ENOTFOUND`||t===`ETIMEDOUT`||t===`EAI_AGAIN`||t===`UND_ERR_SOCKET`||t===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t),onAbort=()=>{clearTimeout(N),C(signalAbortError(n))};if(n?.aborted){clearTimeout(N),C(signalAbortError(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}var mh=__esmMin(()=>{dh(),__name$1(delay$1,`delay`)});async function verifyIntegrity(t,n){let S=n.trim().split(/\s+/);for(let n of S){let S=n.indexOf(`-`);if(S<0)continue;let C=n.slice(0,S).toLowerCase(),N=n.slice(S+1),F=globalThis.crypto?.subtle;if(!F)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let I=subriToWebCryptoAlgo(C);if(!I)continue;let H=await F.digest(I,dataAsArrayBuffer(t));if(bytesToBase64(new Uint8Array(H))===N)return!0}return!1}function subriToWebCryptoAlgo(t){switch(t){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(t){if(t.byteOffset===0&&t.byteLength===t.buffer.byteLength)return t.buffer;let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function bytesToBase64(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return btoa(n)}var hh=__esmMin(()=>{});function assertPackument(t,n){if(!n||typeof n!=`object`)throw TypeError(`registry: ${t} packument is not an object`);let S=n;if(typeof S.name!=`string`)throw TypeError(`registry: ${t} packument missing string name`);if(!S.versions||typeof S.versions!=`object`)throw TypeError(`registry: ${t} packument missing versions map`)}function packumentUrl(t,n){let S=ensureTrailingSlash$1(n);if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw TypeError(`Invalid scoped package name: ${t}`);let C=t.slice(0,n),N=t.slice(n+1);return`${S}${encodeURIComponent(C)}/${encodeURIComponent(N)}`}return`${S}${encodeURIComponent(t)}`}async function fetchPackumentConditional(t,n={}){let S=packumentUrl(t,n.registry??registryFor(t,n.npmrc)),C=buildHeaders(S,{...n,acceptEncoding:`gzip`});C.accept??=n.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,n.ifNoneMatch&&(C[`if-none-match`]=n.ifNoneMatch);let N=await fetchWithRetry(S,{headers:C,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,read:async n=>{if(n.status===304){try{await n.arrayBuffer()}catch{}return{status:`not-modified`}}if(!n.ok)throw n.status===404||n.status===406?new PackageNotFoundError(t,S):Error(`registry GET ${S} -> ${n.status} ${n.statusText}`);return{status:`fresh`,body:await decodeJsonBody(n),etag:n.headers.get(`etag`)??void 0}}});if(N.status===`not-modified`)return{status:`not-modified`,etag:n.ifNoneMatch};let F=N.body;return assertPackument(t,F),{status:`fresh`,packument:F,etag:N.etag}}async function decodeJsonBody(t){return t.json()}async function fetchPackument(t,n={}){let S=await fetchPackumentConditional(t,n);if(!S.packument)throw Error(`registry: ${t} returned 304 Not Modified to an unconditional request`);return S.packument}var gh=__esmMin(()=>{uh(),dh(),ph(),mh()});async function fetchTarball(t,n={}){let S=buildHeaders(t,{...n,acceptEncoding:`identity`});S.accept??=`application/octet-stream`;let C=await fetchWithRetry(t,{headers:S,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,retryNotFound:n.retryNotFound??!0,read:async n=>{if(!n.ok)throw Error(`tarball GET ${t} -> ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});if(n.integrity&&!await verifyIntegrity(C,n.integrity))throw new IntegrityError(t,n.integrity);return C}var vh=__esmMin(()=>{uh(),dh(),mh(),hh()});async function whoami(t,n){let S=`${ensureTrailingSlash$1(t)}-/whoami`,C=buildHeaders(S,{npmrc:n});C.accept=`application/json`;let N=globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=await N(S,{method:`GET`,headers:C});if(!F.ok)throw Error(`whoami GET ${S} -> ${F.status} ${F.statusText}`);let I=await F.json();if(I&&typeof I==`object`&&`username`in I){let t=I.username;if(typeof t==`string`&&t.length>0)return{username:t}}return{}}var yh=__esmMin(()=>{uh(),ph()}),bh=__esmMin(()=>{uh(),dh(),ph(),hh(),gh(),vh(),yh()});function escapePackageName(t){return t.replace(`/`,`%2f`)}function buildPublishHeaders(t,n){let S=buildHeaders(t,{npmrc:n.npmrc});return S[`content-type`]=`application/json`,S[`npm-command`]=`publish`,S[`npm-auth-type`]=n.otp?`legacy`:`web`,S[`user-agent`]=n.userAgent??defaultUserAgent(),n.otp&&(S[`npm-otp`]=n.otp),n.authorization&&(S.authorization=n.authorization),S}function cliVersion(){return xh===void 0&&(xh=`0.64.44`),xh}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=Hn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=Hn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var xh,Sh=__esmMin(()=>{rf(),Xn(),cr(),bh()}),Ch,wh=__esmMin(()=>{Ch=`gjsify`});function parseDeclaredChannel(t,n){if(!(t===void 0||t===``)){if(Th.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a distribution channel. Known: ${Th.join(`, `)}.`)}}function channelAllowsDonations(t){return t!==void 0&&Eh[t]===`external-link`}var Th,Eh,Dh,Oh=__esmMin(()=>{Th=[`flathub`,`web`,`microsoft-store`,`apple-app-store`],Eh={flathub:`external-link`,web:`external-link`,"microsoft-store":`none`,"apple-app-store":`store-purchase`},Dh=`GJSIFY_CHANNEL`});function parseDeclaredPricing(t,n){if(!(t===void 0||t===``)){if(kh.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a pricing tier. Known: ${kh.join(`, `)}.`)}}var kh,Ah,jh=__esmMin(()=>{kh=[`free`,`paid`],Ah=`GJSIFY_PRICING`}),Mh=__commonJSMin(((t,n)=>{let S=(Xn(),__toCommonJS(Pn)),C=($l(),__toCommonJS(Yl)),N=(rf(),__toCommonJS(tf)),resolveFrom=(t,n,F)=>{if(typeof t!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof t}\``);if(typeof n!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof n}\``);try{t=N.realpathSync(t)}catch(n){if(n.code===`ENOENT`)t=S.resolve(t);else if(F)return null;else throw n}let I=S.join(t,`noop.js`),resolveFileName=()=>C._resolveFilename(n,{id:I,filename:I,paths:C._nodeModulePaths(t)});if(F)try{return resolveFileName()}catch{return null}return resolveFileName()};n.exports=(t,n)=>resolveFrom(t,n),n.exports.silent=(t,n)=>resolveFrom(t,n,!0)})),Nh=__commonJSMin(((t,n)=>{let callsites=()=>{let t=Error.prepareStackTrace;Error.prepareStackTrace=(t,n)=>n;let n=Error().stack.slice(1);return Error.prepareStackTrace=t,n};n.exports=callsites,n.exports.default=callsites})),Ph=__commonJSMin(((t,n)=>{let S=Nh();n.exports=t=>{let n=S();if(!t)return n[2].getFileName();let C=!1;n.shift();for(let S of n){let n=S.getFileName();if(typeof n==`string`){if(n===t){C=!0;continue}if(n!==`module.js`&&C&&n!==t)return n}}}})),Fh=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(ru(),__toCommonJS(eu)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(Xn(),__toCommonJS(Pn)),H=Mh(),W=Ph();n.exports=t=>{if(typeof t!=`string`)throw TypeError(`Expected a string`);let n=W(F),S=n?I.dirname(n):N,C=H(S,t),q=Y.cache[C];if(q&&q.parent){let t=q.parent.children.length;for(;t--;)q.parent.children[t].id===C&&q.parent.children.splice(t,1)}delete Y.cache[C];let X=Y.cache[n];return X===void 0||X.require===void 0?Y(C):X.require(C)}})),Ih=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),Lh=__commonJSMin(((t,n)=>{var S=(Hu(),__toCommonJS(Ru)),C=Ih(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
149
+ `,`f`),__classPrivateFieldSet(this,am,__classPrivateFieldGet(this,am,`f`)+t.join(` `),`f`)}}}[Tm](t){objectKeys(__classPrivateFieldGet(this,om,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,om,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,ym,`f`).getDescriptions()[t]}[Em](t,n,S){__classPrivateFieldGet(this,Yp,`f`)[S]||(__classPrivateFieldGet(this,hm,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Yp,`f`)[S]=!0)}[Dm](){__classPrivateFieldGet(this,Zp,`f`).push({options:__classPrivateFieldGet(this,om,`f`),configObjects:__classPrivateFieldGet(this,om,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Xp,`f`),groups:__classPrivateFieldGet(this,$p,`f`),strict:__classPrivateFieldGet(this,gm,`f`),strictCommands:__classPrivateFieldGet(this,_m,`f`),strictOptions:__classPrivateFieldGet(this,vm,`f`),completionCommand:__classPrivateFieldGet(this,Gp,`f`),output:__classPrivateFieldGet(this,am,`f`),exitError:__classPrivateFieldGet(this,qp,`f`),hasOutput:__classPrivateFieldGet(this,em,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,lm,`f`),parseContext:__classPrivateFieldGet(this,um,`f`)}),__classPrivateFieldGet(this,ym,`f`).freeze(),__classPrivateFieldGet(this,Sm,`f`).freeze(),__classPrivateFieldGet(this,Vp,`f`).freeze(),__classPrivateFieldGet(this,Qp,`f`).freeze()}[Om](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,hm,`f`).process.argv()[0])?__classPrivateFieldGet(this,hm,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,hm,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[$m](__classPrivateFieldGet(this,Hp,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,hm,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,hm,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,hm,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,hm,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,hm,`f`).path.dirname(__classPrivateFieldGet(this,hm,`f`).process.execPath())}/`,``)),t}[km](){return __classPrivateFieldGet(this,cm,`f`)}[Am](){return __classPrivateFieldGet(this,bm,`f`)}[jm](){if(!__classPrivateFieldGet(this,Jp,`f`))return;let t=__classPrivateFieldGet(this,hm,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,hm,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,hm,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,hm,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[Mm](){return this[Pm]().version||`unknown`}[Nm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,hm,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[Pm](t){let n=t||`*`;if(__classPrivateFieldGet(this,dm,`f`)[n])return __classPrivateFieldGet(this,dm,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,hm,`f`).mainFilename;__classPrivateFieldGet(this,hm,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,hm,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,hm,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,hm,`f`)),S=JSON.parse(__classPrivateFieldGet(this,hm,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,dm,`f`)[n]=S||{},__classPrivateFieldGet(this,dm,`f`)[n]}[Fm](t,n){n=[].concat(n),n.forEach(n=>{n=this[zm](n),__classPrivateFieldGet(this,om,`f`)[t].push(n)})}[Im](t,n,S,C){this[Rm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,om,`f`)[t][n]=S})}[Lm](t,n,S,C){this[Rm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,om,`f`)[t][n]=(__classPrivateFieldGet(this,om,`f`)[t][n]||[]).concat(S)})}[Rm](t,n,S,C,N){if(Array.isArray(S))S.forEach(n=>{t(n,C)});else if((t=>typeof t==`object`)(S))for(let n of objectKeys(S))t(n,S[n]);else N(n,this[zm](S),C)}[zm](t){return t===`__proto__`?`___proto___`:t}[Bm](t,n){return this[Im](this[Bm].bind(this),`key`,t,n),this}[Vm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Zp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,hm,`f`));let te;t=this,n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,{options:{set value(n){__classPrivateFieldSet(t,om,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Xp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,$p,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,am,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,qp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,em,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,gm,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,_m,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,vm,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Gp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,lm,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,um,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,om,`f`).configObjects=te,__classPrivateFieldGet(this,ym,`f`).unfreeze(),__classPrivateFieldGet(this,Sm,`f`).unfreeze(),__classPrivateFieldGet(this,Vp,`f`).unfreeze(),__classPrivateFieldGet(this,Qp,`f`).unfreeze()}[Hm](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[Um].bind(this),getContext:this[Wm].bind(this),getHasOutput:this[Gm].bind(this),getLoggerInstance:this[Km].bind(this),getParseContext:this[qm].bind(this),getParserConfiguration:this[km].bind(this),getUsageConfiguration:this[Am].bind(this),getUsageInstance:this[Jm].bind(this),getValidationInstance:this[Ym].bind(this),hasParseCallback:this[Xm].bind(this),isGlobalContext:this[Zm].bind(this),postProcess:this[Qm].bind(this),reset:this[eh].bind(this),runValidation:this[nh].bind(this),runYargsParserAndExecuteCommands:this[th].bind(this),setHasOutput:this[rh].bind(this)}}[Um](){return __classPrivateFieldGet(this,Vp,`f`)}[Wm](){return __classPrivateFieldGet(this,Up,`f`)}[Gm](){return __classPrivateFieldGet(this,em,`f`)}[Km](){return __classPrivateFieldGet(this,im,`f`)}[qm](){return __classPrivateFieldGet(this,um,`f`)||{}}[Jm](){return __classPrivateFieldGet(this,ym,`f`)}[Ym](){return __classPrivateFieldGet(this,Sm,`f`)}[Xm](){return!!__classPrivateFieldGet(this,lm,`f`)}[Zm](){return __classPrivateFieldGet(this,nm,`f`)}[Qm](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[Cm](t)),(this[km]()[`parse-positional-numbers`]||this[km]()[`parse-positional-numbers`]===void 0)&&(t=this[Nm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,Qp,`f`).getMiddleware(),!1)),t)}[eh](t={}){__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,om,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,om,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,fm,`f`),Object.keys(__classPrivateFieldGet(this,$p,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,$p,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,$p,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,om,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,om,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,om,`f`).envPrefix,__classPrivateFieldSet(this,om,n,`f`),__classPrivateFieldSet(this,ym,__classPrivateFieldGet(this,ym,`f`)?__classPrivateFieldGet(this,ym,`f`).reset(S):usage(this,__classPrivateFieldGet(this,hm,`f`)),`f`),__classPrivateFieldSet(this,Sm,__classPrivateFieldGet(this,Sm,`f`)?__classPrivateFieldGet(this,Sm,`f`).reset(S):validation(this,__classPrivateFieldGet(this,ym,`f`),__classPrivateFieldGet(this,hm,`f`)),`f`),__classPrivateFieldSet(this,Vp,__classPrivateFieldGet(this,Vp,`f`)?__classPrivateFieldGet(this,Vp,`f`).reset():command(__classPrivateFieldGet(this,ym,`f`),__classPrivateFieldGet(this,Sm,`f`),__classPrivateFieldGet(this,Qp,`f`),__classPrivateFieldGet(this,hm,`f`)),`f`),__classPrivateFieldGet(this,Wp,`f`)||__classPrivateFieldSet(this,Wp,completion(this,__classPrivateFieldGet(this,ym,`f`),__classPrivateFieldGet(this,Vp,`f`),__classPrivateFieldGet(this,hm,`f`)),`f`),__classPrivateFieldGet(this,Qp,`f`).reset(),__classPrivateFieldSet(this,Gp,null,`f`),__classPrivateFieldSet(this,am,``,`f`),__classPrivateFieldSet(this,qp,null,`f`),__classPrivateFieldSet(this,em,!1,`f`),this.parsed=!1,this}[$m](t,n){return __classPrivateFieldGet(this,hm,`f`).path.relative(t,n)}[th](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,pm,`f`),__classPrivateFieldGet(this,om,`f`).__=__classPrivateFieldGet(this,hm,`f`).y18n.__,__classPrivateFieldGet(this,om,`f`).configuration=this[km]();let I=!!__classPrivateFieldGet(this,om,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,om,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,hm,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,om,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,um,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,tm,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,xm,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,ym,`f`).clearCachedHelpMessage();try{if(this[jm](),n)return this[Qm](q,I,!!S,!1);__classPrivateFieldGet(this,tm,`f`)&&[__classPrivateFieldGet(this,tm,`f`)].concat(X[__classPrivateFieldGet(this,tm,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,nm,!1,`f`);let H=__classPrivateFieldGet(this,Vp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Wp,`f`)?.completionKey?[__classPrivateFieldGet(this,Wp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Wp,`f`)?.completionKey]??[]].some(t=>Object.prototype.hasOwnProperty.call(q,t)):!1,re=Z||ne||N;if(q._.length){if(H.length){let t;for(let n=C||0,F;q._[n]!==void 0;n++)if(F=String(q._[n]),H.includes(F)&&F!==__classPrivateFieldGet(this,Gp,`f`)){let t=__classPrivateFieldGet(this,Vp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[Qm](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Gp,`f`)){t=F;break}!__classPrivateFieldGet(this,Vp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,mm,`f`)&&t&&!re&&__classPrivateFieldGet(this,Sm,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Gp,`f`)&&q._.includes(__classPrivateFieldGet(this,Gp,`f`))&&!ne&&(__classPrivateFieldGet(this,Xp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Vp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,Vp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[Qm](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Xp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Wp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Wp,`f`).getCompletion(n,(t,n)=>{if(t)throw new zl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,im,`f`).log(t)}),this.exit(0)}),this[Qm](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,em,`f`)||(Z?(__classPrivateFieldGet(this,Xp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,im,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Xp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,ym,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,om,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,om,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new zl(W.error.message);if(!ne){let t=this[nh](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,Qp,`f`).getMiddleware(),!0)),Y=this[Hm](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,Qp,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof zl)__classPrivateFieldGet(this,ym,`f`).fail(t.message,t);else throw t}return this[Qm](Y??q,I,!!S,!0)}[nh](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new zl(S.message);__classPrivateFieldGet(this,Sm,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Sm,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,_m,`f`)&&(I=__classPrivateFieldGet(this,Sm,`f`).unknownCommands(F)),__classPrivateFieldGet(this,gm,`f`)&&!I?__classPrivateFieldGet(this,Sm,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,vm,`f`)&&__classPrivateFieldGet(this,Sm,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Sm,`f`).limitedChoices(F),__classPrivateFieldGet(this,Sm,`f`).implications(F),__classPrivateFieldGet(this,Sm,`f`).conflicting(F)}}[rh](){__classPrivateFieldSet(this,em,!0,`f`)}[ih](t){if(typeof t==`string`)__classPrivateFieldGet(this,om,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,om,`f`).key[n]=!0}}}),sh,ch=__esmMin(()=>{xp(),oh(),sh=YargsFactory(bp)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var lh=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.64.45`,"accept-encoding":n.acceptEncoding??`identity`};if(n.npmrc){let C=resolveAuthForUrl(t,n.npmrc);C&&(S.authorization=C)}if(n.headers)for(let[t,C]of Object.entries(n.headers))S[t.toLowerCase()]=C;return S}function resolveAuthForUrl(t,n){let S=pathPrefixes(new URL(t));for(let t of S){let S=n.authTokens[t];if(S)return`Bearer ${S}`;let C=n.basicAuth[t];if(C)return`Basic ${btoa(`${C.username}:${C.password}`)}`}return null}function pathPrefixes(t){let n=t.pathname.split(`/`).filter(Boolean),S=[];for(let C=n.length;C>=0;C--){let N=n.slice(0,C).join(`/`);S.push(N?`//${t.host}/${N}`:`//${t.host}`)}return S}var uh=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,dh=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(t,n){super(`Package not found in registry: ${t} (${n})`),this.name=t,this.url=n,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(t,n){super(`Tarball integrity mismatch for ${t} (expected ${n})`),this.url=t,this.integrity=n,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(t,n,S){let C=Math.round(n/100)/10,N=Math.round(n*S/100)/10;super(`@gjsify/npm-registry: GET ${t} timed out after ${C}s × ${S} attempt(s) (total ~${N}s). This usually means the registry CDN is slow or unreachable.`),this.url=t,this.timeoutMs=n,this.attempts=S,this.name=`RegistryTimeoutError`}},RegistryUnreachableError=class extends Error{url;attempts;elapsedMs;constructor(t,n,S,C){let N=Math.round(S/100)/10,F=C instanceof Error?C.message:String(C);super(`@gjsify/npm-registry: GET ${t} failed after ${n} attempt(s) over ~${N}s: ${F}. This usually means the registry or the network dropped out.`),this.url=t,this.attempts=n,this.elapsedMs=S,this.name=`RegistryUnreachableError`,this.cause=C}}});function registryFor(t,n){if(n&&t.startsWith(`@`)){let S=t.slice(0,t.indexOf(`/`)),C=n.scopes[S];if(C)return ensureTrailingSlash$1(C)}return n?.registry?ensureTrailingSlash$1(n.registry):fh}function parseNpmrc(t){let n={registry:fh,scopes:{},authTokens:{},basicAuth:{}},S=t.split(/\r?\n/),C={};for(let t of S){let S=t.replace(/^\s+|\s+$/g,``);if(!S||S.startsWith(`#`)||S.startsWith(`;`))continue;let N=S.indexOf(`=`);if(N<0)continue;let F=S.slice(0,N).trim(),I=expandEnv(stripQuotes(S.slice(N+1).trim()));if(F===`registry`){n.registry=ensureTrailingSlash$1(I);continue}let H=F.match(/^(@[^:]+):registry$/);if(H){n.scopes[H[1]]=ensureTrailingSlash$1(I);continue}let W=F.match(/^\/\/(.+):_authToken$/);if(W){n.authTokens[normalizeAuthHost(W[1])]=I;continue}let q=F.match(/^\/\/(.+):username$/);if(q){(C[normalizeAuthHost(q[1])]??={}).user=I;continue}let Y=F.match(/^\/\/(.+):_password$/);if(Y){let t=base64Decode$1(I);(C[normalizeAuthHost(Y[1])]??={}).pass=t;continue}}for(let[t,S]of Object.entries(C))S.user&&S.pass!==void 0&&(n.basicAuth[t]={username:S.user,password:S.pass});return n}function normalizeAuthHost(t){return`//${t.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(t){return t.endsWith(`/`)?t:t+`/`}function stripQuotes(t){return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function expandEnv(t){return t.replace(/\$\{([A-Z0-9_]+)\}/gi,(t,n)=>globalThis.process?.env?.[n]??``)}function base64Decode$1(t){return atob(t)}var fh,ph=__esmMin(()=>{fh=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`),__name$1(base64Decode$1,`base64Decode`)});async function fetchWithRetry(t,n,S){let C=S.fetch??globalThis.fetch;if(!C)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let N=Math.max(0,S.retries??5),F=Math.max(0,S.retryDelayMs??1e3),I=Math.max(0,S.timeoutMs??3e4),H=S.retryNotFound??!1,W=Date.now(),q=0,Y,X=0;for(;;){if(n.signal?.aborted)throw signalAbortError(n.signal);let Z=I>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${I}ms`)),I),ne=composeSignals(n.signal,Z?.signal);try{let F=await C(t,{...n,signal:ne}),I=isRetryableStatus(F.status)||H&&F.status===404;if(F.ok||!I||q>=N)return S.read?await S.read(F):F;try{await F.arrayBuffer()}catch{}Y=Error(`HTTP ${F.status} ${F.statusText}`)}catch(S){let C=Z!==null&&Z.signal.aborted,F=n.signal?.aborted===!0;if(C&&!F){if(X++,q>=N)throw new RegistryTimeoutError(t,I,X);Y=S}else if(F)throw signalAbortError(n.signal);else{if(!isRetryableError(S))throw S;if(q>=N)throw new RegistryUnreachableError(t,q+1,Date.now()-W,S);Y=S}}finally{te!==null&&clearTimeout(te)}let re=Math.min(F*2**q,8e3);S.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,n.signal),q++}}function composeSignals(t,n){return t?n?AbortSignal.any([t,n]):t:n}function isRetryableStatus(t){return t===408||t===425||t===429||t===500||t===502||t===503||t===504||t===521||t===522||t===524||t===525}function isRetryableError(t){if(t&&typeof t==`object`&&`name`in t&&t.name===`AbortError`)return!1;if(t instanceof TypeError)return!0;if(t&&typeof t==`object`&&`name`in t){let n=t.name;if(n===`FetchError`)return!0;if(n===`AbortError`)return!1}let n=t?.cause;if(n&&typeof n==`object`&&`code`in n){let t=n.code;if(typeof t==`string`)return t===`ECONNRESET`||t===`ECONNREFUSED`||t===`ENETUNREACH`||t===`ENOTFOUND`||t===`ETIMEDOUT`||t===`EAI_AGAIN`||t===`UND_ERR_SOCKET`||t===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(t,n){return t<=0?Promise.resolve():new Promise((S,C)=>{let N=setTimeout(()=>{n?.removeEventListener?.(`abort`,onAbort),S()},t),onAbort=()=>{clearTimeout(N),C(signalAbortError(n))};if(n?.aborted){clearTimeout(N),C(signalAbortError(n));return}n?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(t){let n=t&&`reason`in t?t.reason:void 0;if(n instanceof Error)return n;let S=Error(`Aborted`);return S.name=`AbortError`,S}var mh=__esmMin(()=>{dh(),__name$1(delay$1,`delay`)});async function verifyIntegrity(t,n){let S=n.trim().split(/\s+/);for(let n of S){let S=n.indexOf(`-`);if(S<0)continue;let C=n.slice(0,S).toLowerCase(),N=n.slice(S+1),F=globalThis.crypto?.subtle;if(!F)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let I=subriToWebCryptoAlgo(C);if(!I)continue;let H=await F.digest(I,dataAsArrayBuffer(t));if(bytesToBase64(new Uint8Array(H))===N)return!0}return!1}function subriToWebCryptoAlgo(t){switch(t){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(t){if(t.byteOffset===0&&t.byteLength===t.buffer.byteLength)return t.buffer;let n=new Uint8Array(t.byteLength);return n.set(t),n.buffer}function bytesToBase64(t){let n=``;for(let S=0;S<t.length;S++)n+=String.fromCharCode(t[S]);return btoa(n)}var hh=__esmMin(()=>{});function assertPackument(t,n){if(!n||typeof n!=`object`)throw TypeError(`registry: ${t} packument is not an object`);let S=n;if(typeof S.name!=`string`)throw TypeError(`registry: ${t} packument missing string name`);if(!S.versions||typeof S.versions!=`object`)throw TypeError(`registry: ${t} packument missing versions map`)}function packumentUrl(t,n){let S=ensureTrailingSlash$1(n);if(t.startsWith(`@`)){let n=t.indexOf(`/`);if(n<0)throw TypeError(`Invalid scoped package name: ${t}`);let C=t.slice(0,n),N=t.slice(n+1);return`${S}${encodeURIComponent(C)}/${encodeURIComponent(N)}`}return`${S}${encodeURIComponent(t)}`}async function fetchPackumentConditional(t,n={}){let S=packumentUrl(t,n.registry??registryFor(t,n.npmrc)),C=buildHeaders(S,{...n,acceptEncoding:`gzip`});C.accept??=n.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,n.ifNoneMatch&&(C[`if-none-match`]=n.ifNoneMatch);let N=await fetchWithRetry(S,{headers:C,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,read:async n=>{if(n.status===304){try{await n.arrayBuffer()}catch{}return{status:`not-modified`}}if(!n.ok)throw n.status===404||n.status===406?new PackageNotFoundError(t,S):Error(`registry GET ${S} -> ${n.status} ${n.statusText}`);return{status:`fresh`,body:await decodeJsonBody(n),etag:n.headers.get(`etag`)??void 0}}});if(N.status===`not-modified`)return{status:`not-modified`,etag:n.ifNoneMatch};let F=N.body;return assertPackument(t,F),{status:`fresh`,packument:F,etag:N.etag}}async function decodeJsonBody(t){return t.json()}async function fetchPackument(t,n={}){let S=await fetchPackumentConditional(t,n);if(!S.packument)throw Error(`registry: ${t} returned 304 Not Modified to an unconditional request`);return S.packument}var gh=__esmMin(()=>{uh(),dh(),ph(),mh()});async function fetchTarball(t,n={}){let S=buildHeaders(t,{...n,acceptEncoding:`identity`});S.accept??=`application/octet-stream`;let C=await fetchWithRetry(t,{headers:S,signal:n.signal},{fetch:n.fetch,retries:n.retries,retryDelayMs:n.retryDelayMs,timeoutMs:n.timeoutMs,onRetry:n.onRetry,retryNotFound:n.retryNotFound??!0,read:async n=>{if(!n.ok)throw Error(`tarball GET ${t} -> ${n.status} ${n.statusText}`);return new Uint8Array(await n.arrayBuffer())}});if(n.integrity&&!await verifyIntegrity(C,n.integrity))throw new IntegrityError(t,n.integrity);return C}var vh=__esmMin(()=>{uh(),dh(),mh(),hh()});async function whoami(t,n){let S=`${ensureTrailingSlash$1(t)}-/whoami`,C=buildHeaders(S,{npmrc:n});C.accept=`application/json`;let N=globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=await N(S,{method:`GET`,headers:C});if(!F.ok)throw Error(`whoami GET ${S} -> ${F.status} ${F.statusText}`);let I=await F.json();if(I&&typeof I==`object`&&`username`in I){let t=I.username;if(typeof t==`string`&&t.length>0)return{username:t}}return{}}var yh=__esmMin(()=>{uh(),ph()}),bh=__esmMin(()=>{uh(),dh(),ph(),hh(),gh(),vh(),yh()});function escapePackageName(t){return t.replace(`/`,`%2f`)}function buildPublishHeaders(t,n){let S=buildHeaders(t,{npmrc:n.npmrc});return S[`content-type`]=`application/json`,S[`npm-command`]=`publish`,S[`npm-auth-type`]=n.otp?`legacy`:`web`,S[`user-agent`]=n.userAgent??defaultUserAgent(),n.otp&&(S[`npm-otp`]=n.otp),n.authorization&&(S.authorization=n.authorization),S}function cliVersion(){return xh===void 0&&(xh=`0.64.45`),xh}function cliPackageDir(){let t=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,n;try{n=Hn(t||fileURLToPath(import.meta.url))}catch{return null}for(let t=0;t<12;t++){try{if(JSON.parse(readFileSync(`${n}/package.json`,`utf8`)).name===`@gjsify/cli`)return n}catch{}let t=Hn(n);if(t===n)break;n=t}return null}function defaultUserAgent(){let t=globalThis.process,n=t?.arch??`x64`,S=t?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${S} ${n})`}var xh,Sh=__esmMin(()=>{rf(),Xn(),cr(),bh()}),Ch,wh=__esmMin(()=>{Ch=`gjsify`});function parseDeclaredChannel(t,n){if(!(t===void 0||t===``)){if(Th.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a distribution channel. Known: ${Th.join(`, `)}.`)}}function channelAllowsDonations(t){return t!==void 0&&Eh[t]===`external-link`}var Th,Eh,Dh,Oh=__esmMin(()=>{Th=[`flathub`,`web`,`microsoft-store`,`apple-app-store`],Eh={flathub:`external-link`,web:`external-link`,"microsoft-store":`none`,"apple-app-store":`store-purchase`},Dh=`GJSIFY_CHANNEL`});function parseDeclaredPricing(t,n){if(!(t===void 0||t===``)){if(kh.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a pricing tier. Known: ${kh.join(`, `)}.`)}}var kh,Ah,jh=__esmMin(()=>{kh=[`free`,`paid`],Ah=`GJSIFY_PRICING`}),Mh=__commonJSMin(((t,n)=>{let S=(Xn(),__toCommonJS(Pn)),C=($l(),__toCommonJS(Yl)),N=(rf(),__toCommonJS(tf)),resolveFrom=(t,n,F)=>{if(typeof t!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof t}\``);if(typeof n!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof n}\``);try{t=N.realpathSync(t)}catch(n){if(n.code===`ENOENT`)t=S.resolve(t);else if(F)return null;else throw n}let I=S.join(t,`noop.js`),resolveFileName=()=>C._resolveFilename(n,{id:I,filename:I,paths:C._nodeModulePaths(t)});if(F)try{return resolveFileName()}catch{return null}return resolveFileName()};n.exports=(t,n)=>resolveFrom(t,n),n.exports.silent=(t,n)=>resolveFrom(t,n,!0)})),Nh=__commonJSMin(((t,n)=>{let callsites=()=>{let t=Error.prepareStackTrace;Error.prepareStackTrace=(t,n)=>n;let n=Error().stack.slice(1);return Error.prepareStackTrace=t,n};n.exports=callsites,n.exports.default=callsites})),Ph=__commonJSMin(((t,n)=>{let S=Nh();n.exports=t=>{let n=S();if(!t)return n[2].getFileName();let C=!1;n.shift();for(let S of n){let n=S.getFileName();if(typeof n==`string`){if(n===t){C=!0;continue}if(n!==`module.js`&&C&&n!==t)return n}}}})),Fh=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(ru(),__toCommonJS(eu)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(Xn(),__toCommonJS(Pn)),H=Mh(),W=Ph();n.exports=t=>{if(typeof t!=`string`)throw TypeError(`Expected a string`);let n=W(F),S=n?I.dirname(n):N,C=H(S,t),q=Y.cache[C];if(q&&q.parent){let t=q.parent.children.length;for(;t--;)q.parent.children[t].id===C&&q.parent.children.splice(t,1)}delete Y.cache[C];let X=Y.cache[n];return X===void 0||X.require===void 0?Y(C):X.require(C)}})),Ih=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),Lh=__commonJSMin(((t,n)=>{var S=(Hu(),__toCommonJS(Ru)),C=Ih(),N=function errorEx(t,n){(!t||t.constructor!==String)&&(n=t||{},t=Error.name);var N=function ErrorEXError(S){if(!this)return new ErrorEXError(S);S=S instanceof Error?S.message:S||this.message,Error.call(this,S),Error.captureStackTrace(this,N),this.name=t,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var t=S.split(/\r?\n/g);for(var N in n)if(n.hasOwnProperty(N)){var F=n[N];`message`in F&&(t=F.message(this[N],t)||t,C(t)||(t=[t]))}return t.join(`
150
150
  `)},set:function(t){S=t}});var F=null,I=Object.getOwnPropertyDescriptor(this,`stack`),H=I.get,W=I.value;delete I.value,delete I.writable,I.set=function(t){F=t},I.get=function(){var t=(F||(H?H.call(this):W)).split(/\r?\n+/g);F||(t[0]=this.name+`: `+this.message);var S=1;for(var C in n)if(n.hasOwnProperty(C)){var N=n[C];if(`line`in N){var I=N.line(this[C]);I&&t.splice(S++,0,` `+I)}`stack`in N&&N.stack(this[C],t)}return t.join(`
151
151
  `)},Object.defineProperty(this,"stack",I)};return Object.setPrototypeOf?(Object.setPrototypeOf(N.prototype,Error.prototype),Object.setPrototypeOf(N,Error)):S.inherits(N,Error),N};N.append=function(t,n){return{message:function(S,C){return S||=n,S&&(C[0]+=` `+t.replace(`%s`,S.toString())),C}}},N.line=function(t,n){return{line:function(S){return S||=n,S?t.replace(`%s`,S.toString()):null}}},n.exports=N})),Rh=__commonJSMin(((t,n)=>{let hexify=t=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return`0x`+(n.length%2?`0`:``)+n},parseError=(t,n,S)=>{if(!n)return{message:t.message+` while parsing empty string`,position:0};let C=t.message.match(/^Unexpected token (.) .*position\s+(\d+)/i),N=C?+C[2]:t.message.match(/^Unexpected end of JSON.*/i)?n.length-1:null,F=C?t.message.replace(/^Unexpected token ./,`Unexpected token ${JSON.stringify(C[1])} (${hexify(C[1])})`):t.message;if(N!=null){let t=N<=S?0:N-S,C=N+S>=n.length?n.length:N+S,I=(t===0?``:`...`)+n.slice(t,C)+(C===n.length?``:`...`);return{message:F+` while parsing ${n===I?``:`near `}${JSON.stringify(I)}`,position:N}}else return{message:F+` while parsing '${n.slice(0,S*2)}'`,position:0}};var JSONParseError=class extends SyntaxError{constructor(t,n,S,C){S||=20;let N=parseError(t,n,S);super(N.message),Object.assign(this,N),this.code=`EJSONPARSE`,this.systemError=t,Error.captureStackTrace(this,C||this.constructor)}get name(){return this.constructor.name}set name(t){}get[Symbol.toStringTag](){return this.constructor.name}};let S=Symbol.for(`indent`),C=Symbol.for(`newline`),N=/^\s*[{\[]((?:\r?\n)+)([\s\t]*)/,F=/^(?:\{\}|\[\])((?:\r?\n)+)?$/,parseJson=(t,n,I)=>{let H=stripBOM(t);I||=20;try{let[,t=`
152
152
  `,I=` `]=H.match(F)||H.match(N)||[,``,``],W=JSON.parse(H,n);return W&&typeof W==`object`&&(W[C]=t,W[S]=I),W}catch(n){if(typeof t!=`string`&&!Buffer.isBuffer(t)){let S=Array.isArray(t)&&t.length===0;throw Object.assign(TypeError(`Cannot parse ${S?`an empty array`:String(t)}`),{code:`EJSONPARSE`,systemError:n})}throw new JSONParseError(n,H,I,parseJson)}},stripBOM=t=>String(t).replace(/^\uFEFF/,``);n.exports=parseJson,parseJson.JSONParseError=JSONParseError,parseJson.noExceptions=(t,n)=>{try{return JSON.parse(stripBOM(t),n)}catch{}}})),zh=__commonJSMin((t=>{t.__esModule=!0,t.LinesAndColumns=void 0;var n=`
@@ -951,7 +951,7 @@ Add @gjsify/node-gi as a dependency to run it on Node, e.g.:
951
951
  echo "gjsify: got: node $*" >&2
952
952
  exit 127 ;;
953
953
  esac
954
- `+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var Kz,qz,Jz,Yz=__esmMin(()=>{hl(),rf(),a_(),Xn(),cr(),N_(),kR(),fL(),qR(),Gz(),HI(),Kz=!1,qz=!1,Jz=`node-shim`});function markDaemonCommand(){Xz=!0}function isDaemonCommand(){return Xz}var Xz,Zz=__esmMin(()=>{Xz=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(zn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=In(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Un(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=zn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[zn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(zn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(AY(),kY));await t(Z)}catch(n){ge.error(n.message),t=!0}if(!t&&isDaemonCommand())return;let n=t?1:process.exitCode==null?0:Number(process.exitCode);return process.exit(n)}let te=n.length>0?`${I} ${n.map(shellEscape).join(` `)}`:I,ne;try{ne=await spawnToCompletion(te,[],{completion:`exit`,cwd:S,env:X,shell:!0})}catch(t){return ge.error(t.message),process.exit(1)}return ne.code===0?process.exit(0):(ge.error(`script "${t}" exited with ${describeExit(ne)}`),process.exit(1))}function shellEscape(t){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(t)?t:`'${t.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(t,n){let S=gjsifyCommandArgv(t);return S?[...S,...n]:null}var Qz,$z=__esmMin(()=>{_e(),rf(),Xn(),xR(),mv(),LR(),zR(),GR(),KR(),Yz(),HI(),rR(),Zz(),BI(),N_(),_v(),Qz={command:`run <target> [args..]`,description:"Run a script from package.json (yarn-run-style) or a GJS bundle file. If <target> resolves to a file on disk (or has a path-like prefix), it is launched via gjs with LD_LIBRARY_PATH + GI_TYPELIB_PATH set for native packages. Otherwise it is looked up in the current package.json `scripts`.",builder:t=>t.positional(`target`,{description:"Either a script name (looked up in package.json `scripts`) or a path to a GJS bundle (e.g. dist/gjs.js).",type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments passed through to the script / gjs.`,type:`string`,array:!0,default:[]}).option(`workspace`,{alias:`w`,type:`string`,description:"Run <target> as a script in the named workspace (by name or path), like `npm run <script> -w <name>`."}).option(`node-script`,{type:`boolean`,default:!1,description:"Treat <target> as an unbundled Node-style script (imports `node:` builtins) and run it on the host runtime. Under GJS the file is bundled `--app gjs` on the fly first, which is what makes a repo script runnable on a host that has no Node."}).option(`runtime`,{type:`string`,choices:hv,description:"Runtime to launch a bundle FILE on: gjs (default, `--app gjs` bundle) | node | bun | deno (the `--app node` bundle). Forces file mode."}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=t.target,S=[...t.args??[],...doubleDashArgs(t)];if(t.nodeScript===!0){let isSet=t=>typeof t==`string`&&t.length>0,C=isSet(t.runtime)?`--runtime`:isSet(t.workspace)?`--workspace`:null;if(C)return ge.error(`gjsify run: --node-script cannot be combined with ${C}.`),process.exit(1);await runNodeScript(n,S,{completion:`exit`,exitOnSuccess:!0});return}let C=t.runtime;if(typeof C==`string`&&C.length>0){if(typeof t.workspace==`string`&&t.workspace.length>0)return ge.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(C))return ge.error(`gjsify run: unknown --runtime "${C}" (expected: ${hv.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(C,n,S);return}if(typeof t.workspace==`string`&&t.workspace.length>0){await runScriptInWorkspace(t.workspace,n,S);return}let N=readPackageJson$1(zn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=In(n),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(t)?`gjs`:C;N===`gjs`?await runGjsBundle(t,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,t,S,{completion:`exit`,exitOnSuccess:!0});return}await runScript(n,S)}}}),eB,tB=__esmMin(()=>{_e(),Xn(),fL(),eB={command:`info [file]`,description:`Show native gjsify packages detected in node_modules and the env vars needed to run a GJS bundle directly with gjs.`,builder:t=>t.positional(`file`,{description:`Optional: the GJS bundle path to include in the example command (e.g. dist/gjs.js)`,type:`string`,normalize:!0}).option(`export`,{description:`Output only shell export statements suitable for eval (eval $(gjsify info --export))`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.file?In(t.file):null,C=detectNativePackages(n),N=buildNativeEnv(C),F=Object.entries(N).filter(([,t])=>t!==void 0);if(t.export){for(let[t,n]of F)ge.log(`export ${t}="${n}"`);return}if(C.length===0){ge.log(`No native gjsify packages detected in node_modules.`),ge.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ge.log(`Native packages detected:`);for(let t of C)ge.log(` ${t.name} → ${t.prebuildsDir}`);ge.log(``),ge.log(`To run your app directly with gjs, set:`);for(let[t,n]of F)ge.log(` export ${t}="${n}"`);S?ge.log(` gjs -m ${S}`):ge.log(` gjs -m <your-bundle.js>`),ge.log(``),ge.log(`Or use gjsify run to handle this automatically:`),S?ge.log(` gjsify run ${t.file}`):ge.log(` gjsify run <your-bundle.js>`)}}}),nB,rB=__esmMin(()=>{_e(),sL(),nB={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:t=>t.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async t=>{let n=runAllChecks(process.cwd()),S=detectPackageManager$1(),C=checkTypeSkew(process.cwd()),N=n.filter(t=>!t.found&&t.severity===`required`),F=n.filter(t=>!t.found&&t.severity===`optional`),I=[...N,...F];if(t.json)return ge.log(JSON.stringify({packageManager:S,deps:n,typeSkew:C},null,2)),process.exit(+(N.length>0));ge.log(`System dependency check
954
+ `+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var Kz,qz,Jz,Yz=__esmMin(()=>{hl(),rf(),a_(),Xn(),cr(),N_(),kR(),fL(),qR(),Gz(),HI(),Kz=!1,qz=!1,Jz=`node-shim`});function markDaemonCommand(){Xz=!0}function isDaemonCommand(){return Xz}var Xz,Zz=__esmMin(()=>{Xz=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(zn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=In(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Un(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=zn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[zn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(zn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(aX(),iX));await t(Z)}catch(n){ge.error(n.message),t=!0}if(!t&&isDaemonCommand())return;let n=t?1:process.exitCode==null?0:Number(process.exitCode);return process.exit(n)}let te=n.length>0?`${I} ${n.map(shellEscape).join(` `)}`:I,ne;try{ne=await spawnToCompletion(te,[],{completion:`exit`,cwd:S,env:X,shell:!0})}catch(t){return ge.error(t.message),process.exit(1)}return ne.code===0?process.exit(0):(ge.error(`script "${t}" exited with ${describeExit(ne)}`),process.exit(1))}function shellEscape(t){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(t)?t:`'${t.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(t,n){let S=gjsifyCommandArgv(t);return S?[...S,...n]:null}var Qz,$z=__esmMin(()=>{_e(),rf(),Xn(),xR(),mv(),LR(),zR(),GR(),KR(),Yz(),HI(),rR(),Zz(),BI(),N_(),_v(),Qz={command:`run <target> [args..]`,description:"Run a script from package.json (yarn-run-style) or a GJS bundle file. If <target> resolves to a file on disk (or has a path-like prefix), it is launched via gjs with LD_LIBRARY_PATH + GI_TYPELIB_PATH set for native packages. Otherwise it is looked up in the current package.json `scripts`.",builder:t=>t.positional(`target`,{description:"Either a script name (looked up in package.json `scripts`) or a path to a GJS bundle (e.g. dist/gjs.js).",type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments passed through to the script / gjs.`,type:`string`,array:!0,default:[]}).option(`workspace`,{alias:`w`,type:`string`,description:"Run <target> as a script in the named workspace (by name or path), like `npm run <script> -w <name>`."}).option(`node-script`,{type:`boolean`,default:!1,description:"Treat <target> as an unbundled Node-style script (imports `node:` builtins) and run it on the host runtime. Under GJS the file is bundled `--app gjs` on the fly first, which is what makes a repo script runnable on a host that has no Node."}).option(`runtime`,{type:`string`,choices:hv,description:"Runtime to launch a bundle FILE on: gjs (default, `--app gjs` bundle) | node | bun | deno (the `--app node` bundle). Forces file mode."}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=t.target,S=[...t.args??[],...doubleDashArgs(t)];if(t.nodeScript===!0){let isSet=t=>typeof t==`string`&&t.length>0,C=isSet(t.runtime)?`--runtime`:isSet(t.workspace)?`--workspace`:null;if(C)return ge.error(`gjsify run: --node-script cannot be combined with ${C}.`),process.exit(1);await runNodeScript(n,S,{completion:`exit`,exitOnSuccess:!0});return}let C=t.runtime;if(typeof C==`string`&&C.length>0){if(typeof t.workspace==`string`&&t.workspace.length>0)return ge.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(C))return ge.error(`gjsify run: unknown --runtime "${C}" (expected: ${hv.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(C,n,S);return}if(typeof t.workspace==`string`&&t.workspace.length>0){await runScriptInWorkspace(t.workspace,n,S);return}let N=readPackageJson$1(zn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=In(n),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(t)?`gjs`:C;N===`gjs`?await runGjsBundle(t,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,t,S,{completion:`exit`,exitOnSuccess:!0});return}await runScript(n,S)}}}),eB,tB=__esmMin(()=>{_e(),Xn(),fL(),eB={command:`info [file]`,description:`Show native gjsify packages detected in node_modules and the env vars needed to run a GJS bundle directly with gjs.`,builder:t=>t.positional(`file`,{description:`Optional: the GJS bundle path to include in the example command (e.g. dist/gjs.js)`,type:`string`,normalize:!0}).option(`export`,{description:`Output only shell export statements suitable for eval (eval $(gjsify info --export))`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.file?In(t.file):null,C=detectNativePackages(n),N=buildNativeEnv(C),F=Object.entries(N).filter(([,t])=>t!==void 0);if(t.export){for(let[t,n]of F)ge.log(`export ${t}="${n}"`);return}if(C.length===0){ge.log(`No native gjsify packages detected in node_modules.`),ge.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ge.log(`Native packages detected:`);for(let t of C)ge.log(` ${t.name} → ${t.prebuildsDir}`);ge.log(``),ge.log(`To run your app directly with gjs, set:`);for(let[t,n]of F)ge.log(` export ${t}="${n}"`);S?ge.log(` gjs -m ${S}`):ge.log(` gjs -m <your-bundle.js>`),ge.log(``),ge.log(`Or use gjsify run to handle this automatically:`),S?ge.log(` gjsify run ${t.file}`):ge.log(` gjsify run <your-bundle.js>`)}}}),nB,rB=__esmMin(()=>{_e(),sL(),nB={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:t=>t.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async t=>{let n=runAllChecks(process.cwd()),S=detectPackageManager$1(),C=checkTypeSkew(process.cwd()),N=n.filter(t=>!t.found&&t.severity===`required`),F=n.filter(t=>!t.found&&t.severity===`optional`),I=[...N,...F];if(t.json)return ge.log(JSON.stringify({packageManager:S,deps:n,typeSkew:C},null,2)),process.exit(+(N.length>0));ge.log(`System dependency check
955
955
  `);let H=n.filter(t=>t.severity===`required`),W=n.filter(t=>t.severity===`optional`);if(H.length>0){ge.log(`Required:`);for(let t of H){let n=t.found?`✓`:`✗`,S=t.version?` (${t.version})`:``;ge.log(` ${n} ${t.name}${S}`)}}if(W.length>0){ge.log(`
956
956
  Optional:`);for(let t of W){let n=t.found?`✓`:`⚠`,S=t.version?` (${t.version})`:``,C=t.requiredBy&&t.requiredBy.length>0?` — needed by ${t.requiredBy.join(`, `)}`:``;ge.log(` ${n} ${t.name}${S}${C}`)}}if(C.length>0){ge.log(`
957
957
  Type/runtime version skew:`);for(let t of C){let n=t.relation===`ahead`?`⚠`:`ℹ`;ge.log(` ${n} ${t.typePackage} describes ${t.declared}, installed ${t.pkgConfig} is ${t.installed}`)}C.some(t=>t.relation===`ahead`)&&ge.log(`
@@ -972,7 +972,7 @@ No install command available for your package manager. Install manually.`),proce
972
972
  bunx @gjsify/cli@latest showcase <name>
973
973
  deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,TB={command:`showcase [name]`,description:`List or run curated gjsify showcase applications.`,builder:t=>t.positional(`name`,{description:`Showcase name to run (omit to list all)`,type:`string`}).option(`json`,{description:`Output as JSON`,type:`boolean`,default:!1}).option(`list`,{description:`List available showcases`,type:`boolean`,default:!1}).option(`runtime`,{type:`string`,choices:hv,defaultDescription:`gjs when gjs is installed, else the host runtime`,description:"Runtime to run the showcase on: gjs | node | bun | deno (default: gjs when installed, else the host runtime). node/bun/deno run its `--app node` bundle."}),handler:async t=>{if(!t.name||t.list){let n=discoverShowcases();if(t.json){ge.log(JSON.stringify(n,null,2));return}if(n.length===0){ge.log("No showcases found. The CLI ships a curated list in `showcases.json`; if it is missing the CLI install is incomplete.");return}let S=new Map;for(let t of n){let n=S.get(t.category)??[];n.push(t),S.set(t.category,n)}ge.log(`Available gjsify showcases:
974
974
  `);for(let[t,n]of S){ge.log(` ${t.toUpperCase()}:`);let S=Math.max(...n.map(t=>t.name.length));for(let t of n){let n=` `.repeat(S-t.name.length+2),C=t.description?`${n}${t.description}`:``;ge.log(` ${t.name}${C}`)}ge.log(``)}ge.log(`Run a showcase: gjsify showcase <name>`);return}let n=findShowcase(t.name);if(!n)return ge.error(`Unknown showcase: "${t.name}"`),ge.error(`Run "gjsify showcase" to list available showcases.`),process.exit(1);let S=t.runtime??defaultExampleRuntime();if(!isExampleRuntime(S))return ge.error(`Unknown --runtime "${S}" (expected: ${hv.join(`, `)}).`),process.exit(1);if(requiresGjsSystemDeps(S)){let t=runMinimalChecks().filter(t=>!t.found&&t.severity===`required`);if(t.length>0){ge.error(`Missing system dependencies:
975
- `);for(let n of t)ge.error(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),t);return n&&ge.error(`\nInstall with:\n ${n}`),process.exit(1)}}let C=readCliVersion();if(S!==`gjs`){await runShowcaseOnRuntime(n,S,C);return}let N=C?`${n.packageName}@${C}`:n.packageName;ge.log(`Running showcase: ${n.name} ${runningAs(C)}(via gjsify dlx ${N})\n`);try{let{runCli:t}=await Promise.resolve().then(()=>(AY(),kY));await t([`dlx`,N])}catch(t){ge.error(t.message),process.exit(1)}}}});function resolveTemplatesRoot(){let t=Hn(fileURLToPath(import.meta.url)),n=[zn(t,`..`,`dist-templates`),zn(t,`dist-templates`)];try{let t=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);n.splice(1,0,zn(Hn(t),`dist-templates`))}catch{}return n.find(t=>existsSync(t))}function discoverTemplates(){let t=resolveTemplatesRoot();if(!t)return[];let n=[];for(let S of readdirSync(t)){let C=zn(t,S),N=zn(C,`package.json`);if(!statSync(C).isDirectory()||!existsSync(N))continue;let F=DB[S]??``;try{let t=JSON.parse(readFileSync(N,`utf-8`));typeof t.description==`string`&&t.description.trim()&&(F=t.description)}catch{}n.push({name:S,description:F,path:C})}return n.sort((t,n)=>t.name.localeCompare(n.name)),n}function findTemplate(t){return discoverTemplates().find(n=>n.name===t)}var DB,OB=__esmMin(()=>{rf(),$l(),Xn(),cr(),DB={"gtk-minimal":`Minimal GTK4 app — Gtk.ApplicationWindow + Gtk.Label, no Adwaita (Blueprint UI).`,cli:`Command-line tool using yargs (Node.js + GJS).`,"adw-canvas2d":`Adwaita app with HTML Canvas 2D rendering (Blueprint UI).`,"adw-webgl":`Adwaita app with WebGL + three.js (Blueprint UI).`,"adw-game":`Adwaita game shell using Excalibur.js, WebGL → Canvas2D fallback.`,"web-server-hono":`HTTP server using Hono (Web-standard fetch-style API).`,"web-server-express":`HTTP server using Express (familiar Node.js stack).`}});function installCommandLine(t){return[t,...AB[t]].join(` `)}function runScriptCommand(t){return jB[t]}function packageManagersForRuntime(t){return MB[t]}function hostRuntime(){let t=globalThis;return t.Bun===void 0?t.Deno===void 0?t.imports?.gi===void 0?`node`:`gjs`:`deno`:`bun`}function defaultRuntimeFor(t,n){if(n)return t.find(t=>packageManagersForRuntime(t)?.includes(n));let S=hostRuntime();return t.includes(S)?S:t[0]}function startScriptFor(t){return t===`gjs`?`start`:`start:${t}`}var kB,AB,jB,MB,NB,PB=__esmMin(()=>{kB=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],AB={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},jB={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},MB={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},NB={gjs:`GNOME JavaScript — no Node.js needed at runtime.`,node:`Node.js — gi:// via the @gjsify/node-gi bridge.`,bun:`Bun — runs the same --app node bundle.`,deno:`Deno — runs the same --app node bundle.`}});function selectRuntime(t){let{flag:n,offered:S,manager:C,interactive:N}=t;if(n!==void 0)return S.length>0&&!S.includes(n)?{kind:`error`,message:`this template does not run on "${n}". Declared runtimes: ${S.join(`, `)}.`}:{kind:`value`,value:n};if(S.length===1)return{kind:`value`,value:S[0]};if(S.length===0)return{kind:`error`,message:`this template declares no runtime this scaffolder can install for.`};let F=defaultRuntimeFor(S,C);return F===void 0?{kind:`error`,message:`no runtime this template declares installs with "${C}". Declared runtimes: ${S.join(`, `)}.`}:C===void 0?N?{kind:`prompt`,choices:S,initial:F}:{kind:`auto`,value:F,notice:`--runtime not given, using "${F}". Runs on: ${S.join(`, `)}.`}:{kind:`auto`,value:F,notice:`Setting up for ${F} — the runtime ${C} installs for.`}}function selectPackageManager(t){let{flag:n,runtime:S,install:C,interactive:N}=t,F=packageManagersForRuntime(S);return F===void 0||F.length===0?{kind:`error`,message:`no package manager known for runtime "${S}".`}:n===void 0?F.length===1?{kind:`auto`,value:F[0],notice:`Using ${F[0]} — the only package manager that installs for ${S}.`}:N?{kind:`prompt`,choices:F,initial:F[0]}:C?{kind:`error`,message:`--package-manager is required with --install in non-interactive mode. Package managers for ${S}: ${F.join(`, `)}.`}:{kind:`auto`,value:F[0],notice:`--package-manager not given, using "${F[0]}" for ${S}.`}:F.includes(n)?{kind:`value`,value:n}:{kind:`error`,message:`"${n}" cannot install a project you intend to run on ${S}. Package managers for ${S}: ${F.join(`, `)}.`}}var FB=__esmMin(()=>{PB()});function applicationIdFor(t){let n=t.replace(/[^A-Za-z0-9_-]/g,`-`);return`org.gjsify.${/^[0-9]/.test(n)?`app-${n}`:n}`}function sanitizeProjectName(t){let n=t.trim();if(!n)throw Error(`Project name cannot be empty.`);let S=n.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[._-]+/,``).replace(/[._-]+$/,``);if(!S)throw Error(`"${t}" is not a valid npm package name.`);return S}function isDirEmpty(t){return existsSync(t)?readdirSync(t).length===0:!0}async function createProject(t){let n=sanitizeProjectName(t.projectName),{template:S,force:C=!1,install:N=!1}=t,F=findTemplate(S);if(!F){let t=discoverTemplates().map(t=>t.name).join(`, `);throw Error(`Unknown template "${S}". Available templates: ${t||`(none — run "yarn build" first)`}`)}let I=supportedRuntimes(F),H=t.runtime??defaultRuntimeFor(I,t.packageManager)??hostRuntime(),W=packageManagersForRuntime(H);if(!W)throw Error(`Template "${F.name}" was asked for runtime "${H}", which this version of @gjsify/create-app has no installer mapping for. Upgrade it, or pick one of: ${I.join(`, `)||`(none)`}.`);let q=t.packageManager??W[0];if(!W.includes(q))throw Error(`"${q}" cannot install a project you intend to run on ${H}. Package managers for ${H}: ${W.join(`, `)}.`);let Y=In(process.cwd(),n);if(existsSync(Y)&&!isDirEmpty(Y)&&!C)return ge.error(`Error: Directory "${n}" exists and is not empty. Use --force to scaffold into it anyway.`),process.exit(1);if(ge.log(`Creating new Gjsify project in ${Y} (template: ${F.name})...`),mkdirSync(Y,{recursive:!0}),cpSync(F.path,Y,{recursive:!0}),substituteTemplateSentinels(Y,n),N){let t=installCommandLine(q);ge.log(`Running ${t}...`);let n=spawnSync(t,{cwd:Y,stdio:`inherit`,shell:!0});n.error?ge.warn(`${q} install could not start (${n.error.message}); re-run it manually.`):n.status!==0&&ge.warn(`${q} install failed; re-run it manually in the project directory.`)}printNextSteps(n,F,N,q,H)}function substituteTemplateSentinels(t,n){let S=[[IB,n],[LB,applicationIdFor(n)]];renameSentinelPaths(t,S),substituteSentinelContents(t,S)}function renameSentinelPaths(t,n){for(let S of readdirSync(t,{withFileTypes:!0})){let C=S.name;for(let[t,S]of n)C=C.replaceAll(t,S);let N=zn(t,S.name),F=zn(t,C);F!==N&&renameSync(N,F),S.isDirectory()&&renameSentinelPaths(F,n)}}function substituteSentinelContents(t,n){let S=new Set([`node_modules`,`dist`,`lib`]),C=[t];for(;C.length>0;){let t=C.pop();for(let N of readdirSync(t,{withFileTypes:!0})){let F=zn(t,N.name);if(N.isDirectory()){S.has(N.name)||C.push(F);continue}if(!N.isFile())continue;let I=N.name.lastIndexOf(`.`),H=I>=0?N.name.slice(I):``;if(!RB.has(H)&&!zB.has(N.name))continue;let W=readFileSync(F,`utf-8`),q=W;for(let[t,S]of n)q=q.replaceAll(t,S);q!==W&&writeFileSync(F,q)}}}function printNextSteps(t,n,S,C,N){let F=runScriptCommand(C),I=templateScripts(n),H=startScriptFor(N);ge.log(``),ge.log(`Project created from template "${n.name}", set up for ${N}.`),ge.log(``),ge.log(`Next steps:`),ge.log(` cd ${t}`),S||ge.log(` ${C} install`),N===`gjs`&&I.dev?ge.log(` ${F} dev`):(ge.log(` ${F} build`),ge.log(` ${F} ${H}`)),ge.log(``);let W=supportedRuntimes(n).filter(t=>t!==N&&I[startScriptFor(t)]);if(W.length>0){ge.log(`Also runs on ${W.join(`, `)}:`);for(let t of W)ge.log(` ${F} ${startScriptFor(t)}`);ge.log(``)}I.ship&&(ge.log(`Package it for a machine without gjsify:`),ge.log(` ${F} ship -- darwin`),ge.log(``))}function templateManifest(t){try{return JSON.parse(readFileSync(zn(t.path,`package.json`),`utf-8`))}catch{return{}}}function templateScripts(t){let n=templateManifest(t).scripts;return n?Object.fromEntries(Object.entries(n).filter(t=>typeof t[1]==`string`)):{}}function supportedRuntimes(t){let n=templateManifest(t).gjsify?.example?.runtimes;return Array.isArray(n)?n.filter(t=>typeof t==`string`&&packageManagersForRuntime(t)!==void 0):[]}var IB,LB,RB,zB,BB=__esmMin(()=>{_e(),sv(),rf(),Xn(),OB(),PB(),FB(),IB=`new-gjsify-app`,LB=`org.gjsify.example`,RB=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`,`.svg`]),zB=new Set([`LICENSE`,`LICENCE`,`COPYING`,`NOTICE`])});function isCancelled(t){return t instanceof Error&&t.message===HB}function render(t,n,S){S||xn.write(`\x1b[${t.length}A`);for(let S=0;S<t.length;S++){let C=t[S],N=S===n?`${VB.cyan}❯${VB.reset}`:` `,F=S===n?`${VB.bold}${VB.green}${C.label}${VB.reset}`:C.label,I=C.description?` ${VB.dim}${C.description}${VB.reset}`:``;xn.write(`\x1b[2K\r ${N} ${F}${I}\n`)}}function promptChoice(t,n,S=0){return n.length===0?Promise.reject(Error(`Nothing to choose for "${t}".`)):new Promise((C,N)=>{let F=S>=0&&S<n.length?S:0;xn.write(`${VB.bold}${t}${VB.reset} ${VB.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${VB.reset}\n`),render(n,F,!0),emitKeypressEvents(Sn),Sn.isTTY&&Sn.setRawMode(!0),Sn.resume();let cleanup=()=>{Sn.removeListener(`keypress`,onKeypress),Sn.isTTY&&Sn.setRawMode(!1),Sn.pause()},onKeypress=(t,S)=>{if(S){if(S.ctrl&&S.name===`c`){cleanup(),xn.write(`
975
+ `);for(let n of t)ge.error(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),t);return n&&ge.error(`\nInstall with:\n ${n}`),process.exit(1)}}let C=readCliVersion();if(S!==`gjs`){await runShowcaseOnRuntime(n,S,C);return}let N=C?`${n.packageName}@${C}`:n.packageName;ge.log(`Running showcase: ${n.name} ${runningAs(C)}(via gjsify dlx ${N})\n`);try{let{runCli:t}=await Promise.resolve().then(()=>(aX(),iX));await t([`dlx`,N])}catch(t){ge.error(t.message),process.exit(1)}}}});function resolveTemplatesRoot(){let t=Hn(fileURLToPath(import.meta.url)),n=[zn(t,`..`,`dist-templates`),zn(t,`dist-templates`)];try{let t=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);n.splice(1,0,zn(Hn(t),`dist-templates`))}catch{}return n.find(t=>existsSync(t))}function discoverTemplates(){let t=resolveTemplatesRoot();if(!t)return[];let n=[];for(let S of readdirSync(t)){let C=zn(t,S),N=zn(C,`package.json`);if(!statSync(C).isDirectory()||!existsSync(N))continue;let F=DB[S]??``;try{let t=JSON.parse(readFileSync(N,`utf-8`));typeof t.description==`string`&&t.description.trim()&&(F=t.description)}catch{}n.push({name:S,description:F,path:C})}return n.sort((t,n)=>t.name.localeCompare(n.name)),n}function findTemplate(t){return discoverTemplates().find(n=>n.name===t)}var DB,OB=__esmMin(()=>{rf(),$l(),Xn(),cr(),DB={"gtk-minimal":`Minimal GTK4 app — Gtk.ApplicationWindow + Gtk.Label, no Adwaita (Blueprint UI).`,cli:`Command-line tool using yargs (Node.js + GJS).`,"adw-canvas2d":`Adwaita app with HTML Canvas 2D rendering (Blueprint UI).`,"adw-webgl":`Adwaita app with WebGL + three.js (Blueprint UI).`,"adw-game":`Adwaita game shell using Excalibur.js, WebGL → Canvas2D fallback.`,"web-server-hono":`HTTP server using Hono (Web-standard fetch-style API).`,"web-server-express":`HTTP server using Express (familiar Node.js stack).`}});function installCommandLine(t){return[t,...AB[t]].join(` `)}function runScriptCommand(t){return jB[t]}function packageManagersForRuntime(t){return MB[t]}function hostRuntime(){let t=globalThis;return t.Bun===void 0?t.Deno===void 0?t.imports?.gi===void 0?`node`:`gjs`:`deno`:`bun`}function defaultRuntimeFor(t,n){if(n)return t.find(t=>packageManagersForRuntime(t)?.includes(n));let S=hostRuntime();return t.includes(S)?S:t[0]}function startScriptFor(t){return t===`gjs`?`start`:`start:${t}`}var kB,AB,jB,MB,NB,PB=__esmMin(()=>{kB=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],AB={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},jB={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},MB={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},NB={gjs:`GNOME JavaScript — no Node.js needed at runtime.`,node:`Node.js — gi:// via the @gjsify/node-gi bridge.`,bun:`Bun — runs the same --app node bundle.`,deno:`Deno — runs the same --app node bundle.`}});function selectRuntime(t){let{flag:n,offered:S,manager:C,interactive:N}=t;if(n!==void 0)return S.length>0&&!S.includes(n)?{kind:`error`,message:`this template does not run on "${n}". Declared runtimes: ${S.join(`, `)}.`}:{kind:`value`,value:n};if(S.length===1)return{kind:`value`,value:S[0]};if(S.length===0)return{kind:`error`,message:`this template declares no runtime this scaffolder can install for.`};let F=defaultRuntimeFor(S,C);return F===void 0?{kind:`error`,message:`no runtime this template declares installs with "${C}". Declared runtimes: ${S.join(`, `)}.`}:C===void 0?N?{kind:`prompt`,choices:S,initial:F}:{kind:`auto`,value:F,notice:`--runtime not given, using "${F}". Runs on: ${S.join(`, `)}.`}:{kind:`auto`,value:F,notice:`Setting up for ${F} — the runtime ${C} installs for.`}}function selectPackageManager(t){let{flag:n,runtime:S,install:C,interactive:N}=t,F=packageManagersForRuntime(S);return F===void 0||F.length===0?{kind:`error`,message:`no package manager known for runtime "${S}".`}:n===void 0?F.length===1?{kind:`auto`,value:F[0],notice:`Using ${F[0]} — the only package manager that installs for ${S}.`}:N?{kind:`prompt`,choices:F,initial:F[0]}:C?{kind:`error`,message:`--package-manager is required with --install in non-interactive mode. Package managers for ${S}: ${F.join(`, `)}.`}:{kind:`auto`,value:F[0],notice:`--package-manager not given, using "${F[0]}" for ${S}.`}:F.includes(n)?{kind:`value`,value:n}:{kind:`error`,message:`"${n}" cannot install a project you intend to run on ${S}. Package managers for ${S}: ${F.join(`, `)}.`}}var FB=__esmMin(()=>{PB()});function applicationIdFor(t){let n=t.replace(/[^A-Za-z0-9_-]/g,`-`);return`org.gjsify.${/^[0-9]/.test(n)?`app-${n}`:n}`}function sanitizeProjectName(t){let n=t.trim();if(!n)throw Error(`Project name cannot be empty.`);let S=n.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[._-]+/,``).replace(/[._-]+$/,``);if(!S)throw Error(`"${t}" is not a valid npm package name.`);return S}function isDirEmpty(t){return existsSync(t)?readdirSync(t).length===0:!0}async function createProject(t){let n=sanitizeProjectName(t.projectName),{template:S,force:C=!1,install:N=!1}=t,F=findTemplate(S);if(!F){let t=discoverTemplates().map(t=>t.name).join(`, `);throw Error(`Unknown template "${S}". Available templates: ${t||`(none — run "yarn build" first)`}`)}let I=supportedRuntimes(F),H=t.runtime??defaultRuntimeFor(I,t.packageManager)??hostRuntime(),W=packageManagersForRuntime(H);if(!W)throw Error(`Template "${F.name}" was asked for runtime "${H}", which this version of @gjsify/create-app has no installer mapping for. Upgrade it, or pick one of: ${I.join(`, `)||`(none)`}.`);let q=t.packageManager??W[0];if(!W.includes(q))throw Error(`"${q}" cannot install a project you intend to run on ${H}. Package managers for ${H}: ${W.join(`, `)}.`);let Y=In(process.cwd(),n);if(existsSync(Y)&&!isDirEmpty(Y)&&!C)return ge.error(`Error: Directory "${n}" exists and is not empty. Use --force to scaffold into it anyway.`),process.exit(1);if(ge.log(`Creating new Gjsify project in ${Y} (template: ${F.name})...`),mkdirSync(Y,{recursive:!0}),cpSync(F.path,Y,{recursive:!0}),substituteTemplateSentinels(Y,n),N){let t=installCommandLine(q);ge.log(`Running ${t}...`);let n=spawnSync(t,{cwd:Y,stdio:`inherit`,shell:!0});n.error?ge.warn(`${q} install could not start (${n.error.message}); re-run it manually.`):n.status!==0&&ge.warn(`${q} install failed; re-run it manually in the project directory.`)}printNextSteps(n,F,N,q,H)}function substituteTemplateSentinels(t,n){let S=[[IB,n],[LB,applicationIdFor(n)]];renameSentinelPaths(t,S),substituteSentinelContents(t,S)}function renameSentinelPaths(t,n){for(let S of readdirSync(t,{withFileTypes:!0})){let C=S.name;for(let[t,S]of n)C=C.replaceAll(t,S);let N=zn(t,S.name),F=zn(t,C);F!==N&&renameSync(N,F),S.isDirectory()&&renameSentinelPaths(F,n)}}function substituteSentinelContents(t,n){let S=new Set([`node_modules`,`dist`,`lib`]),C=[t];for(;C.length>0;){let t=C.pop();for(let N of readdirSync(t,{withFileTypes:!0})){let F=zn(t,N.name);if(N.isDirectory()){S.has(N.name)||C.push(F);continue}if(!N.isFile())continue;let I=N.name.lastIndexOf(`.`),H=I>=0?N.name.slice(I):``;if(!RB.has(H)&&!zB.has(N.name))continue;let W=readFileSync(F,`utf-8`),q=W;for(let[t,S]of n)q=q.replaceAll(t,S);q!==W&&writeFileSync(F,q)}}}function printNextSteps(t,n,S,C,N){let F=runScriptCommand(C),I=templateScripts(n),H=startScriptFor(N);ge.log(``),ge.log(`Project created from template "${n.name}", set up for ${N}.`),ge.log(``),ge.log(`Next steps:`),ge.log(` cd ${t}`),S||ge.log(` ${C} install`),N===`gjs`&&I.dev?ge.log(` ${F} dev`):(ge.log(` ${F} build`),ge.log(` ${F} ${H}`)),ge.log(``);let W=supportedRuntimes(n).filter(t=>t!==N&&I[startScriptFor(t)]);if(W.length>0){ge.log(`Also runs on ${W.join(`, `)}:`);for(let t of W)ge.log(` ${F} ${startScriptFor(t)}`);ge.log(``)}I.ship&&(ge.log(`Package it for a machine without gjsify:`),ge.log(` ${F} ship -- darwin`),ge.log(``))}function templateManifest(t){try{return JSON.parse(readFileSync(zn(t.path,`package.json`),`utf-8`))}catch{return{}}}function templateScripts(t){let n=templateManifest(t).scripts;return n?Object.fromEntries(Object.entries(n).filter(t=>typeof t[1]==`string`)):{}}function supportedRuntimes(t){let n=templateManifest(t).gjsify?.example?.runtimes;return Array.isArray(n)?n.filter(t=>typeof t==`string`&&packageManagersForRuntime(t)!==void 0):[]}var IB,LB,RB,zB,BB=__esmMin(()=>{_e(),sv(),rf(),Xn(),OB(),PB(),FB(),IB=`new-gjsify-app`,LB=`org.gjsify.example`,RB=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`,`.svg`]),zB=new Set([`LICENSE`,`LICENCE`,`COPYING`,`NOTICE`])});function isCancelled(t){return t instanceof Error&&t.message===HB}function render(t,n,S){S||xn.write(`\x1b[${t.length}A`);for(let S=0;S<t.length;S++){let C=t[S],N=S===n?`${VB.cyan}❯${VB.reset}`:` `,F=S===n?`${VB.bold}${VB.green}${C.label}${VB.reset}`:C.label,I=C.description?` ${VB.dim}${C.description}${VB.reset}`:``;xn.write(`\x1b[2K\r ${N} ${F}${I}\n`)}}function promptChoice(t,n,S=0){return n.length===0?Promise.reject(Error(`Nothing to choose for "${t}".`)):new Promise((C,N)=>{let F=S>=0&&S<n.length?S:0;xn.write(`${VB.bold}${t}${VB.reset} ${VB.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${VB.reset}\n`),render(n,F,!0),emitKeypressEvents(Sn),Sn.isTTY&&Sn.setRawMode(!0),Sn.resume();let cleanup=()=>{Sn.removeListener(`keypress`,onKeypress),Sn.isTTY&&Sn.setRawMode(!1),Sn.pause()},onKeypress=(t,S)=>{if(S){if(S.ctrl&&S.name===`c`){cleanup(),xn.write(`
976
976
  `),N(Error(HB));return}S.name===`up`||S.name===`k`?(F=(F-1+n.length)%n.length,render(n,F,!1)):S.name===`down`||S.name===`j`?(F=(F+1)%n.length,render(n,F,!1)):(S.name===`return`||S.name===`enter`)&&(cleanup(),C(n[F].value))}};Sn.on(`keypress`,onKeypress)})}function promptTemplate(t){return t.length===0?Promise.reject(Error(`No templates available.`)):promptChoice(`Select a template`,t.map(t=>({value:t,label:t.name,description:t.description})))}function promptRuntime(t,n){return promptChoice(`Select a runtime`,t.map(t=>({value:t,label:t,description:NB[t]??``})),t.indexOf(n))}function promptPackageManager(t,n){return promptChoice(`Select a package manager`,t.map(t=>({value:t,label:t,description:``})),t.indexOf(n))}async function settle(t,n){switch(t.kind){case`value`:return t.value;case`auto`:return ge.error(t.notice),t.value;case`prompt`:try{return await n(t.choices,t.initial)}catch(t){if(!isCancelled(t))throw t;ge.error(`Cancelled.`);return}case`error`:ge.error(`Error: ${t.message}`);return}}async function promptSetup(t){let{offered:n,install:S,interactive:C}=t,N=await settle(selectRuntime({flag:t.runtime,offered:n,manager:t.packageManager,interactive:C}),(t,n)=>promptRuntime(t,n));if(N===void 0)return;let F=await settle(selectPackageManager({flag:t.packageManager,runtime:N,install:S,interactive:C}),(t,n)=>promptPackageManager(t,n));if(F!==void 0)return{runtime:N,packageManager:F}}var VB,HB,UB=__esmMin(()=>{_e(),Cn(),Yd(),PB(),FB(),VB={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},HB=`Cancelled by user`}),WB,GB=__esmMin(()=>{_e(),BB(),UB(),WB={command:`create [project-name]`,description:`Scaffold a new Gjsify project in a new directory.`,builder:t=>{let n=discoverTemplates(),S=n.map(t=>t.name),C=[...new Set(n.flatMap(t=>supportedRuntimes(t)))];return t.positional(`project-name`,{describe:`Name of the project directory to create`,type:`string`,default:`my-gjs-app`}).option(`template`,{alias:`t`,describe:`Template to scaffold from`,type:`string`,choices:S.length>0?S:void 0}).option(`runtime`,{alias:`r`,describe:`Runtime to set the project up for. Decides which package managers are offered and which start script the next steps name.`,type:`string`,choices:C.length>0?C:void 0}).option(`force`,{alias:`f`,describe:`Scaffold into a non-empty directory`,type:`boolean`,default:!1}).option(`install`,{describe:`Install dependencies after scaffolding`,type:`boolean`,default:!1}).option(`package-manager`,{alias:`p`,describe:"Package manager to install with, and to name in the printed next steps. Must be one the chosen runtime can install for. `gjsify` is the only one that works on a host with no Node.js.",type:`string`,choices:kB})},handler:async t=>{let n=!!process.stdin.isTTY,S=discoverTemplates(),C=t.template;if(!C){if(!n){let t=S.map(t=>t.name).join(`, `);return ge.error(`Error: --template is required in non-interactive mode. Available templates: ${t||`(none)`}`),process.exit(1)}let t=await promptTemplate(S).catch(t=>{if(!isCancelled(t))throw t;ge.error(`Cancelled.`)});if(t===void 0)return process.exit(1);C=t.name}let N=S.find(t=>t.name===C),F=await promptSetup({offered:N?supportedRuntimes(N):[],runtime:t.runtime,packageManager:t[`package-manager`],install:t.install,interactive:n});if(F===void 0)return process.exit(1);await createProject({projectName:t[`project-name`],template:C,runtime:F.runtime,force:t.force,install:t.install,packageManager:F.packageManager})}}});function defaultTargetFor(t){let n=Un(t,Wn(t));return In(Hn(t),n)}var KB,qB,JB=__esmMin(()=>{_e(),sv(),Bd(),Xn(),Hu(),KB=promisify(execFile),qB={command:`gresource <xml>`,description:"Compile a GResource XML descriptor into a binary .gresource bundle (wraps `glib-compile-resources`).",builder:t=>t.positional(`xml`,{description:`Path to the .gresource.xml descriptor`,type:`string`,normalize:!0,demandOption:!0}).option(`sourcedir`,{description:`Directory containing the resource files referenced by <xml>`,type:`string`,normalize:!0}).option(`target`,{alias:`t`,description:`Output .gresource file (default: <xml-without-.xml> next to <xml>)`,type:`string`,normalize:!0}).option(`verbose`,{description:`Print the underlying glib-compile-resources invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=In(t.xml),S=t.target?In(t.target):defaultTargetFor(n),C=[`--sourcedir=${t.sourcedir?In(t.sourcedir):Hn(n)}`,`--target=${S}`,n];t.verbose&&ge.log(`[gjsify gresource] glib-compile-resources ${C.join(` `)}`),await mkdir$1(Hn(S),{recursive:!0});try{let{stdout:n,stderr:N}=await KB(`glib-compile-resources`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gresource] wrote ${S}`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gresource] glib-compile-resources not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gresource] glib-compile-resources failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function mergeCatalogues(t){let n=t.template,S=new Set;for(let{locale:n}of t.catalogues){if(S.has(n))throw Error(`mergeCatalogues: two catalogues both claim locale "${n}". msgfmt APPENDS each --locale, so the chain would emit a duplicate key (desktop-file-validate: "multiple keys named Name[${n}]"; appstreamcli: "tag-duplicated") from two exit-0 calls. Merge them into one .po first (msgcat --use-first) and pass that.`);S.add(n)}for(let[S,C]of t.catalogues.entries()){let N=zn(t.workDir,`${S}${t.extension}`),F=[t.mode,`--template=${n}`,`--locale=${C.locale}`,`--output-file=${N}`,C.po];t.onCall?.(F),execFileSync(`msgfmt`,F,{stdio:`pipe`}),n=N}return n}var YB=__esmMin(()=>{sv(),Xn()});async function listLanguages(t){return(await readdir$1(t)).filter(t=>t.endsWith(`.po`)&&!t.startsWith(`.`)).map(t=>t.slice(0,-3)).sort()}function stripXmlComments(t){return t.replace(/<!--[\s\S]*?-->/g,``)}async function ensureDir(t){await mkdir$1(t,{recursive:!0})}async function fileExists(t){try{return await stat$1(t),!0}catch{return!1}}async function compileMerged(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}let S=zn(t.outDir,t.filename);await ensureDir(t.outDir);let C=await mkdtemp$1(zn(tmpdir(),`gjsify-gettext-`));try{let N=await readFile$1(mergeCatalogues({mode:`--${t.format}`,template:t.template,extension:`-${Un(t.template).replace(/\.in$/,``)}`,catalogues:n.map(n=>({locale:n,po:zn(t.poDir,`${n}.po`)})),workDir:C,onCall:t.verbose?t=>ge.log(`[gjsify gettext] msgfmt ${t.join(` `)}`):void 0}),`utf-8`);await writeFile$1(S,t.removeXmlComments&&t.format===`xml`?stripXmlComments(N):N)}finally{await rm$1(C,{recursive:!0,force:!0})}t.verbose&&ge.log(`[gjsify gettext] merged ${n.length} language(s) into ${S}`)}async function compileCatalogues(t){let n=await listLanguages(t.poDir);if(n.length===0){ge.warn(`[gjsify gettext] no .po files found in ${t.poDir}`);return}for(let S of n){let n=zn(t.outDir,S,`LC_MESSAGES`);await ensureDir(n);let C=[`--output-file=${zn(n,t.filename)}`,zn(t.poDir,`${S}.po`)];t.verbose&&ge.log(`[gjsify gettext] msgfmt ${C.join(` `)}`),await XB(`msgfmt`,C)}t.verbose&&ge.log(`[gjsify gettext] compiled ${n.length} language(s) into ${t.outDir}`)}function defaultFilename(t,n,S){switch(n){case`mo`:return`${t}.mo`;case`desktop`:return`${t}.desktop`;case`xml`:return S?Un(S.replace(/\.in$/,``)):`${t}.xml`}}var XB,ZB,QB=__esmMin(()=>{_e(),sv(),Bd(),a_(),Xn(),Hu(),YB(),XB=promisify(execFile),ZB={command:`gettext <poDir> <outDir>`,description:`Compile gettext .po files to .mo (per-language locale tree), or merge every catalogue into a .desktop / AppStream template via msgfmt --desktop / --xml.`,builder:t=>t.positional(`poDir`,{description:`Directory containing <lang>.po files`,type:`string`,normalize:!0,demandOption:!0}).positional(`outDir`,{description:`Output directory (locale tree for --format=mo, plain dir for xml/desktop)`,type:`string`,normalize:!0,demandOption:!0}).option(`domain`,{description:"Text domain / application ID (e.g. `org.pixelrpg.maker`)",type:`string`,normalize:!0,demandOption:!0}).option(`format`,{description:`Output format`,type:`string`,choices:[`mo`,`xml`,`desktop`],default:`mo`}).option(`template`,{description:"Required for --format=xml|desktop: the file msgfmt substitutes into. Its SUFFIX matters — msgfmt --xml finds its ITS rules by filename pattern, so an AppStream template must be named `*.metainfo.xml[.in]`.",type:`string`,normalize:!0}).option(`metainfo`,{description:`Deprecated alias for --template.`,type:`string`,normalize:!0,hidden:!0}).option(`filename`,{description:`Override the output filename (defaults to <domain>.<ext>)`,type:`string`,normalize:!0}).option(`remove-xml-comments`,{description:`For --format=xml: strip XML comments from the compiled output`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print each msgfmt invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=In(t.poDir),S=In(t.outDir),C=t.domain,N=t.format??`mo`,F=t.template??t.metainfo,I=F?In(F):void 0,H=t.filename??defaultFilename(C,N,I),W=!!t.verbose,q=!!t[`remove-xml-comments`];if(!await fileExists(n)){ge.error(`[gjsify gettext] PO directory does not exist: ${n}`),process.exitCode=1;return}if(N!==`mo`&&I===void 0){ge.error(`[gjsify gettext] --format=${N} needs a template to substitute into: pass \`--template <file>\`. msgfmt has no way to produce this format from .po files alone.`+(N===`xml`?" Name it `*.metainfo.xml[.in]` — msgfmt --xml finds its ITS rules by filename pattern.":``)),process.exitCode=1;return}try{N===`mo`?await compileCatalogues({poDir:n,outDir:S,filename:H,verbose:W}):await compileMerged({poDir:n,outDir:S,format:N,template:I,filename:H,removeXmlComments:q,verbose:W})}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gettext] msgfmt not found. Install it via your distro (package: gettext).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gettext] msgfmt failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}}),$B,eV,tV=__esmMin(()=>{_e(),sv(),Bd(),Xn(),Hu(),$B=promisify(execFile),eV={command:`gsettings <schemadir>`,description:"Compile GSettings schema XML files into a binary gschemas.compiled (wraps `glib-compile-schemas`).",builder:t=>t.positional(`schemadir`,{description:`Directory containing *.gschema.xml descriptors`,type:`string`,normalize:!0,demandOption:!0}).option(`targetdir`,{alias:`t`,description:`Directory to write gschemas.compiled (default: <schemadir>)`,type:`string`,normalize:!0}).option(`strict`,{description:`Abort on any schema warning (passes --strict to glib-compile-schemas)`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print the underlying glib-compile-schemas invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=In(t.schemadir),S=t.targetdir?In(t.targetdir):n,C=[];t.strict&&C.push(`--strict`),C.push(`--targetdir=${S}`),C.push(n),t.verbose&&ge.log(`[gjsify gsettings] glib-compile-schemas ${C.join(` `)}`),await mkdir$1(S,{recursive:!0});try{let{stdout:n,stderr:N}=await $B(`glib-compile-schemas`,C);n&&process.stdout.write(n),N&&process.stderr.write(N),t.verbose&&ge.log(`[gjsify gsettings] wrote ${S}/gschemas.compiled`)}catch(t){let n=t;n?.code===`ENOENT`?ge.error(`[gjsify gsettings] glib-compile-schemas not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(n?.stderr&&process.stderr.write(n.stderr),ge.error(`[gjsify gsettings] glib-compile-schemas failed${n?.code===void 0?``:` (exit ${n.code})`}`)),process.exitCode=typeof n?.code==`number`?n.code:1}}}});function readPackageJson(t){let n=In(t,`package.json`),S;try{S=readFileSync(n,`utf-8`)}catch{throw Error(`gjsify flatpak: no package.json found at ${n}`)}try{return JSON.parse(S)}catch(t){throw Error(`gjsify flatpak: package.json at ${n} is not valid JSON: ${t.message}`)}}function looksLikeAppId(t){return typeof t==`string`&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*){2,}$/.test(t)}function defaultCiContainer(t,n){return`ghcr.io/flathub-infra/flatpak-github-actions:${`${t}-${n}`}`}var nV,rV=__esmMin(()=>{rf(),Xn(),nV=`gjsify-sources.json`});function resolveRuntime(t,n){let S=n.runtime??t?.runtime??`gnome`;if(S!==`gnome`&&S!==`freedesktop`)throw Error(`gjsify flatpak: unknown runtime "${S}" (expected "gnome" or "freedesktop")`);let C=n.runtimeVersion??t?.runtimeVersion??(S===`gnome`?`51`:`24.08`);return S===`gnome`?{runtime:S,runtimeId:`org.gnome.Platform`,sdk:`org.gnome.Sdk`,runtimeVersion:C}:{runtime:S,runtimeId:`org.freedesktop.Platform`,sdk:`org.freedesktop.Sdk`,runtimeVersion:C}}function deriveAppendPath(t){let n=[];for(let S of t){let t=/^org\.freedesktop\.Sdk\.Extension\.([A-Za-z0-9-]+)$/.exec(S);t&&n.push(`/usr/lib/sdk/${t[1]}/bin`)}return n.push(`/app/bin`),n}var iV,aV,oV=__esmMin(()=>{iV=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],aV=[]});function pickFlatpakBuildKeys(t,n){let S=t??{},C={},N=[];for(let t of cV){let F=S[t];if(F!==void 0){C[t]=F;continue}let I=n[t];I!==void 0&&N.push(t),C[t]=I}return{values:C,fromLegacy:N}}function resolveShipFlatpakSettings(t){let n=t.ship.flatpak??{},{values:S,fromLegacy:C}=pickFlatpakBuildKeys(n,t.flatpak),N=resolveRuntime(S,{}),F=S.sdkExtensions??[],{appendPath:I,finishArgs:H,cleanup:W}=S;return{settings:{runtime:N.runtimeId,runtimeVersion:N.runtimeVersion,sdk:N.sdk,branch:n.branch??`stable`,sdkExtensions:[...F],appendPath:I??(F.length>0?deriveAppendPath(F):[]),finishArgs:H??(t.kind===`cli`?aV:iV),cleanup:[...new Set([...W??[],...t.kind===`app`?[lV]:[]])]},warnings:C.length===0?[]:[deprecationWarning(C)]}}function assertNoDroppedFlatpakModules(t){let n=[`modules`,`extraModules`].filter(n=>(t[n]?.length??0)>0);if(n.length===0)return;let S=n.map(t=>`gjsify.flatpak.${t}`).join(` and `);throw Error(`gjsify ship: ${S} ${n.length>1?`are`:`is`} set, but the \`flatpak\` target renders ONE module, the staged payload, and would drop ${n.length>1?`them`:`it`} (ADR 0024 § 2). Build this Flatpak with \`gjsify flatpak init\` + \`gjsify flatpak build\`, which honour the key, or leave \`flatpak\` out of \`--target\` / \`gjsify.ship.targets\`.`)}function deprecationWarning(t){let n=t.map(t=>`gjsify.flatpak.${t}`).join(`, `),S=t.map(t=>`gjsify.ship.flatpak.${t}`).join(`, `);return`DEPRECATION: ${n} ${t.length>1?`are`:`is`} read by \`gjsify ship\` for compatibility and will be removed in ${sV}. Move ${t.length>1?`them`:`it`} to ${S} — both spellings resolve until then, and \`gjsify.ship.flatpak\` wins where both are set. The app METADATA in \`gjsify.flatpak\` (name, summary, developer, categories, licence) is NOT deprecated: both blocks describe the same application and either may carry it (ADR 0024 § 8).`}var sV,cV,lV,uV=__esmMin(()=>{oV(),sV=`1.0.0`,cV=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`],lV=`/share/icons/hicolor/scalable`});function loadDesktopTemplate(){return dV}function validateAppMetadata(t){let n=t.metadata,S=t.configKey,C=[];return(!n.developer?.id||!n.developer?.name)&&C.push({field:`${S}.developer`,hint:`Set \`${S}.developer = { "id": "io.github.you", "name": "Your Name" }\` in package.json. The id is reverse-DNS.`}),n.summary||C.push({field:`${S}.summary`,hint:`One-line app summary, ≤80 chars, no trailing period. Example: "Learn 6502 assembly language".`}),n.description||C.push({field:`${S}.description`,hint:`Plain text (split on blank lines) or DescriptionBlock[] for rich content with bullet lists + translator hints.`}),n.license?.project||C.push({field:`${S}.license.project`,hint:`SPDX identifier of the project license, e.g. "MIT", "GPL-3.0-or-later".`}),n.homepageUrl||C.push({field:`${S}.homepageUrl`,hint:`Required by Flathub. Example: "https://github.com/you/your-repo".`}),C}function renderMetainfoApp$1(t){return renderMetainfo(t,`desktop-application`)}function renderMetainfoCli$1(t){return renderMetainfo(t,`console-application`)}function renderDesktopEntry(t){let n=t.metadata,S=(n.categories??[`Utility`]).join(`;`)+`;`,C=n.keywords?.length?`Keywords=${n.keywords.join(`;`)};\n`:``,N=n.provides?.mimetypes??[],F=N.length?`MimeType=${N.join(`;`)};\n`:``;return substitute(loadDesktopTemplate(),{NAME:t.name,SUMMARY:n.summary??t.name,COMMAND:`${t.command}${execFieldCode(N)}`,APP_ID:t.appId,CATEGORIES_LINE:S,KEYWORDS_LINE:C,MIMETYPES_LINE:F})}function execFieldCode(t){return t.some(t=>t.startsWith(`x-scheme-handler/`))?` %u`:t.length>0?` %f`:``}function renderMetainfo(t,n){let S=t.metadata,C=t.copyrightYear??new Date().getFullYear(),N=S.developer?.name??``,F=[];F.push(`<?xml version="1.0" encoding="UTF-8"?>`),F.push(`<!-- Copyright ${C} ${escapeXml(N)} -->`),F.push(`<component type="${n}">`),F.push(` <id>${escapeXml(t.appId)}</id>`),F.push(` <metadata_license>${escapeXml(S.license?.metadata??`CC0-1.0`)}</metadata_license>`),F.push(` <project_license>${escapeXml(S.license?.project??``)}</project_license>`),F.push(` <name>${escapeXml(t.name)}</name>`),pushTranslatorHint(F,S.summaryTranslatorHint,` `),F.push(` <summary>${escapeXml(S.summary??t.name)}</summary>`),S.iconRemote&&F.push(` <icon type="remote">${escapeXml(S.iconRemote)}</icon>`),F.push(` <description>`);for(let t of renderDescriptionBlocks(S.description??``,` `))F.push(t);if(F.push(` </description>`),S.developer?.id&&S.developer?.name){F.push(` <developer id="${escapeXml(S.developer.id)}">`);let t=S.developer.nameTranslatable===!0?``:` translate="no"`;F.push(` <name${t}>${escapeXml(S.developer.name)}</name>`),S.developer.email&&F.push(` <email>${escapeXml(S.developer.email)}</email>`),F.push(` </developer>`)}n===`desktop-application`&&F.push(` <launchable type="desktop-id">${escapeXml(t.appId)}.desktop</launchable>`),S.screenshots?.length&&(F.push(` <screenshots>`),S.screenshots.forEach((t,n)=>{let S=t.type??(n===0?`default`:void 0),C=S?` type="${escapeXml(S)}"`:``,N=t.environment?` environment="${escapeXml(t.environment)}"`:``;F.push(` <screenshot${C}${N}>`),F.push(` <image>${escapeXml(t.url)}</image>`);for(let[n,S]of Object.entries(t.localizedUrls??{}))F.push(` <image xml:lang="${escapeXml(n)}">${escapeXml(S)}</image>`);t.caption&&(pushTranslatorHint(F,t.captionTranslatorHint,` `),F.push(` <caption>${escapeXml(t.caption)}</caption>`)),F.push(` </screenshot>`)}),F.push(` </screenshots>`)),S.homepageUrl&&F.push(` <url type="homepage">${escapeXml(S.homepageUrl)}</url>`),S.bugtrackerUrl&&F.push(` <url type="bugtracker">${escapeXml(S.bugtrackerUrl)}</url>`),S.vcsBrowserUrl&&F.push(` <url type="vcs-browser">${escapeXml(S.vcsBrowserUrl)}</url>`),S.donationUrl&&channelAllowsDonations(t.channel)&&F.push(` <url type="donation">${escapeXml(S.donationUrl)}</url>`),S.translateUrl&&F.push(` <url type="translate">${escapeXml(S.translateUrl)}</url>`);let I=normaliseContentRating(S.contentRating);if(I.attributes&&Object.keys(I.attributes).length>0){F.push(` <content_rating type="${escapeXml(I.type)}">`);for(let[t,n]of Object.entries(I.attributes))F.push(` <content_attribute id="${escapeXml(t)}">${escapeXml(n)}</content_attribute>`);F.push(` </content_rating>`)}else F.push(` <content_rating type="${escapeXml(I.type)}" />`);if(S.releases?.length){F.push(` <releases>`);for(let t of S.releases)if(t.description===void 0)F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}" />`);else{F.push(` <release version="${escapeXml(t.version)}" date="${escapeXml(t.date)}">`),F.push(` <description>`);for(let n of renderDescriptionBlocks(t.description,` `))F.push(n);F.push(` </description>`),F.push(` </release>`)}F.push(` </releases>`)}if(S.categories?.length){F.push(` <categories>`);for(let t of S.categories)F.push(` <category>${escapeXml(t)}</category>`);F.push(` </categories>`)}if(S.keywords?.length){F.push(` <keywords>`);for(let t of S.keywords)F.push(` <keyword>${escapeXml(t)}</keyword>`);F.push(` </keywords>`)}if(n===`desktop-application`&&S.branding&&(F.push(` <branding>`),F.push(` <color type="primary" scheme_preference="light">${escapeXml(S.branding.accentLight)}</color>`),F.push(` <color type="primary" scheme_preference="dark">${escapeXml(S.branding.accentDark)}</color>`),F.push(` </branding>`)),S.kudos?.length){F.push(` <kudos>`);for(let t of S.kudos)F.push(` <kudo>${escapeXml(t)}</kudo>`);F.push(` </kudos>`)}let H=S.provides?.binaries??[t.command],W=S.provides?.mimetypes??[],q=S.provides?.dbus??[];if(H.length||W.length||q.length){F.push(` <provides>`);for(let t of H)F.push(` <binary>${escapeXml(t)}</binary>`);for(let t of W)F.push(` <mediatype>${escapeXml(t)}</mediatype>`);for(let t of q)F.push(` <dbus type="${escapeXml(t.type)}">${escapeXml(t.id)}</dbus>`);F.push(` </provides>`)}if(S.supports?.controls?.length||S.supports?.internet){F.push(` <supports>`);for(let t of S.supports.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.supports.internet&&F.push(` <internet>${escapeXml(S.supports.internet)}</internet>`),F.push(` </supports>`)}if(S.requires?.displayLengthMin||S.requires?.controls?.length||S.requires?.internet){F.push(` <requires>`),S.requires.displayLengthMin&&F.push(` <display_length compare="ge">${S.requires.displayLengthMin}</display_length>`);for(let t of S.requires.controls??[])F.push(` <control>${escapeXml(t)}</control>`);S.requires.internet&&F.push(` <internet>${escapeXml(S.requires.internet)}</internet>`),F.push(` </requires>`)}if(S.recommends?.displayLengthMin||S.recommends?.controls?.length){F.push(` <recommends>`),S.recommends.displayLengthMin&&F.push(` <display_length compare="ge">${S.recommends.displayLengthMin}</display_length>`);for(let t of S.recommends.controls??[])F.push(` <control>${escapeXml(t)}</control>`);F.push(` </recommends>`)}return F.push(`</component>`),F.join(`
977
977
  `)+`
978
978
  `}function renderDescriptionBlocks(t,n){let S=typeof t==`string`?stringToBlocks(t):t,C=[];for(let t of S)if(`p`in t)pushTranslatorHint(C,t.translatorHint,n),C.push(`${n}<p>${escapeXml(t.p.trim().replace(/\s+/g,` `))}</p>`);else{pushTranslatorHint(C,t.translatorHint,n),C.push(`${n}<ul>`);for(let S of t.ul)typeof S==`string`?C.push(`${n} <li>${escapeXml(S)}</li>`):(pushTranslatorHint(C,S.translatorHint,`${n} `),C.push(`${n} <li>${escapeXml(S.item)}</li>`));C.push(`${n}</ul>`)}return C}function stringToBlocks(t){return t.trim().split(/\n\n+/).map(t=>({p:t.trim().replace(/\s+/g,` `)}))}function pushTranslatorHint(t,n,S){n&&t.push(`${S}<!-- TRANSLATORS: ${n} -->`)}function normaliseContentRating(t){return t===void 0?{type:`oars-1.1`}:typeof t==`string`?{type:t}:{type:t.type??`oars-1.1`,attributes:t.attributes}}function substitute(t,n){let S=t;for(let[t,C]of Object.entries(n))S=S.split(`{{${t}}}`).join(C);return S}function escapeXml(t){return t.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`)}var dV,fV=__esmMin(()=>{Oh(),dV=`[Desktop Entry]
@@ -1256,7 +1256,7 @@ jq -n --arg v "$version" --arg d "$date" ${N.join(` `)} \\
1256
1256
  reported, so the first symptom can be an unrelated-looking bundler error
1257
1257
  (\`Could not load <file>\` from rolldown, for the CSS bridge). Nothing to
1258
1258
  install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=zn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(zn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var MG,NG,PG,FG,IG=__esmMin(()=>{_e(),rf(),Xn(),cr(),sv(),jG(),BI(),sL(),fL(),kR(),Vz(),qR(),fz(),zR(),mv(),HI(),DV(),Gz(),Ez(),Oz(),GR(),jz(),MG=process.platform===`win32`?`junction`:void 0,NG=18e5,PG={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:t=>t.positional(`packages`,{description:`Optional package specs. With none, runs a full project install.`,type:`string`,array:!0}).option(`global`,{description:`Install into the user-global XDG location and symlink bins into ~/.local/bin.`,type:`boolean`,alias:`g`,default:!1}).option(`save-dev`,{type:`boolean`,alias:`D`}).option(`save-peer`,{type:`boolean`}).option(`save-optional`,{type:`boolean`,alias:`O`}).option(`immutable`,{description:`CI mode: install strictly from gjsify-lock.json, fail if the lockfile is missing or stale. Equivalent to yarn --immutable / npm ci --frozen-lockfile.`,type:`boolean`,default:!1}).option(`refresh-lockfile`,{description:`Re-resolve every dependency to the newest version satisfying its range and rewrite the lockfile (bumps in-range transitive deps). Without it, a resolve preserves versions already pinned in the lockfile and only resolves new/changed deps — the npm/yarn/pnpm default. Mirrors yarn install --mode=update-lockfile.`,type:`boolean`,default:!1}).option(`focus`,{description:`Install only the named workspaces (package names), the workspaces they depend on, and their external dependencies, as if they were the only members of the monorepo (yarn workspaces focus). Reads gjsify-lock.json and never rewrites it; fails if it is missing or stale. Workspace projects only.`,type:`string`,array:!0}).option(`verbose`,{description:`Verbose install logging.`,type:`boolean`,default:!1}).option(`quiet`,{description:`Silence the progress bar.`,type:`boolean`,default:!1}).option(`progress`,{description:`Show a TTY-aware progress bar for resolve / download / extract phases. Auto-enabled when stderr is a TTY (override with --no-progress). Implicitly off under --verbose (per-package log lines replace the bar) or --quiet.`,type:`boolean`,default:!0}).option(`backend`,{description:"Install backend. `native` (default) routes through `@gjsify/{semver,npm-registry,tar}` — no Node/npm at runtime. `npm` shells out to `npm install` as an escape hatch for cases the native backend does not yet model (Yarn PnP repos, lifecycle scripts). Overrides `GJSIFY_INSTALL_BACKEND` if both are set.",type:`string`,choices:[`native`,`npm`]}).option(`timeout`,{description:`Overall install wall-clock timeout in ms (default 1800000 = 30 min). On timeout, all in-flight registry fetches are aborted and the install exits non-zero with a clear "install timed out — likely a registry slowdown" message. Per-request timeouts in @gjsify/npm-registry (default 30s) still apply within this budget. Set to 0 to disable the overall budget.`,type:`number`,default:NG}).option(`os`,{description:"Resolve/install for this OS instead of the running one (npm config key `os`, e.g. darwin, win32, linux). Affects which packages pass the os/cpu/libc compatibility check; the lockfile stays platform-independent either way.",type:`string`}).option(`cpu`,{description:"Resolve/install for this CPU architecture instead of the running one (npm config key `cpu`, e.g. x64, arm64).",type:`string`}).option(`libc`,{description:"Resolve/install for this libc family instead of probing the host (npm config key `libc`: glibc or musl). Only meaningful with --os=linux. A package declaring a libc is incompatible when the target libc is unknown.",type:`string`}).option(`force`,{description:"Install a REQUIRED dependency even when its os/cpu/libc excludes the target, instead of failing with EBADPLATFORM (npm config key `force`). Incompatible OPTIONAL dependencies stay skipped — npm ignores --force for those too, and a binary that cannot load is not worth downloading.",type:`boolean`,default:!1}).option(`prune`,{description:`After installing, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable. Skipped automatically under --immutable, and whenever --os/--cpu/--libc is given: an install must never delete against a target the user typed.`,type:`boolean`,default:!0}),handler:async t=>{if(applyPlatformConfigFromFlags(t),t.immutable){if(t.packages&&t.packages.length>0)return ge.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(t.global)return ge.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(t[`refresh-lockfile`])return ge.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1);assertNoDevLinkUnderImmutable(process.cwd())}if(t.global){if(!t.packages||t.packages.length===0)return ge.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let n of[`save-dev`,`save-peer`,`save-optional`])t[n]&&ge.warn(`gjsify install --global ignores --${n}: global installs do not modify a project package.json.`);await installGlobalAndLink(t.packages,{verbose:t.verbose,prune:t.prune});return}if(warnOnCliVersionSkew(process.cwd()),(t.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(t),pruneProjectPrefix(t),await runPostInstallChecks(t);return}let n=t.timeout>0?t.timeout:0,S=n>0?new AbortController:null,C=S===null?null:setTimeout(()=>S.abort(Error(`install-overall-timeout`)),n),N=n>0?setTimeout(()=>{let t=Math.round(n/100)/10;ge.error(`gjsify install: the ${t}s budget elapsed and the abort did not unwind within 10s — forcing exit. That means one of two things, and this timer cannot distinguish them: the install was still WORKING (a cold tree here extracts several GB, and extraction blocks the loop in multi-second synchronous stretches), or a step genuinely wedged. Re-running tells you which, and is safe: extraction is idempotent, every package already on disk is skipped, so a second run finishes the remainder in a fraction of the time. A re-run that makes NO further progress is a real wedge — file an issue.`),forceExit(1)},n+1e4):null;N?.unref?.();try{await projectInstallNative(t,S?.signal),pruneProjectPrefix(t),await runPostInstallChecks(t)}catch(t){if(S!==null&&S.signal.aborted&&isAbortedFromOverallTimeout(t)){let t=Math.round(n/100)/10;return ge.error(`gjsify install: timed out after ${t}s — likely a registry slowdown or a wedged extract.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw t}finally{C!==null&&clearTimeout(C),N!==null&&clearTimeout(N)}}},FG=`@gjsify/cli`});function sweepCheckouts(t,n){let S=null;try{S=readDevLinkOverride(t)?.checkout??null}catch{S=null}return S&&S!==n?[S,n]:[n]}var LG,RG,zG=__esmMin(()=>{_e(),rf(),Xn(),jz(),LG={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually uses are linked: declared dependencies plus everything in its lockfile or installed node_modules, transitive and nested copies included.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=In(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n),nested:consumerNestedPlacements(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} uses (declared, locked or installed)${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Bn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H);writeDevLinkOverride(n,{version:1,checkout:C,packages:I});let re=ensureLocallyIgnored(n);ge.log(`\n ${ne.length} link(s) written, ${H.length-ne.length} already current.`),Z.length>0&&ge.log(` ${te.length} of ${Z.length} retired link(s) removed.`),ge.log(` override: ${N}`),re===`added`&&ge.log(` git: ${kz} added to .git/info/exclude (local, never committed)`),re===`no-git`&&ge.log(` git: ${n} is not a git repository — nothing to ignore`),re===`unreadable-git`&&ge.warn(` ! git: ${n} has a .git POINTER that does not parse, so ${kz} is NOT ignored. Add it to .gitignore by hand, or the next \`git add -A\` commits your local override.`),ge.log("\nEvery `gjsify install` here now re-applies these links and says so.\n`gjsify install --immutable` refuses while the override exists. Undo: `gjsify unlink`.")}},RG={command:`unlink`,description:"Undo `gjsify link`: remove the development links and the .gjsify-link.json override, then reinstall the registry copies.",builder:t=>t.option(`dry-run`,{description:`Print what would be removed and change nothing.`,type:`boolean`,default:!1}).option(`install`,{description:"Reinstall after unlinking, to put the registry copies back where the links were. On by default; --no-install leaves the holes for a later `gjsify install`.",type:`boolean`,default:!0}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=devLinkPath(n);if(!existsSync(C)){ge.log(`gjsify unlink: no development link in ${n} (no ${kz}).`);return}let N=[];try{let t=readDevLinkOverride(n)?.checkout;t&&N.push(t)}catch{}let F=[];try{F=prepareDevLinks(n)?.links??[]}catch(t){ge.warn(`gjsify unlink: ${t instanceof Error?t.message:String(t)}\n Removing the override anyway; any dangling links are cleaned by the reinstall.`)}let I=`gjsify unlink${S?` (dry-run)`:``}`;if(ge.log(`${I} in ${n}`),S){let t=new Set(F.map(t=>t.name));for(let S of scanDevLinks(n,N))t.add(S.name);for(let n of[...t].sort())ge.log(` would remove link ${n}`);ge.log(` would remove ${C}`),ge.log(` would remove ${kz} entry from .git/info/exclude (if this module wrote it)`),ge.log(`\n${I}: nothing changed. Drop --dry-run to apply.`);return}let H=removeDevLinks(F),W=new Set(H.map(t=>t.name));for(let t of retireDevLinks(n,N,new Set))W.has(t.name)||H.push(t);for(let t of H)ge.log(` unlinked ${t.name}`);let q=scanDevLinks(n,N);if(q.length>0)return ge.error(`gjsify unlink: ${q.length} link(s) still point into a checkout and could not be removed:\n`+q.map(t=>` ${t.name} ${t.linkPath} → ${t.target}`).join(`
1259
- `)+`\n ${C} is kept so this stays undoable. Remove the paths above and re-run.`),process.exit(1);if(removeDevLinkOverride(n),ge.log(` removed ${C}`),removeLocalIgnore(n)===`removed`&&ge.log(` removed ${kz} entry from .git/info/exclude`),t.install===!1){ge.log(`\n ${H.length} link(s) removed. Run \`gjsify install\` to restore the registry copies.`);return}ge.log(`\n ${H.length} link(s) removed — reinstalling to restore the registry copies.\n`);let{runCli:Y}=await Promise.resolve().then(()=>(AY(),kY));await Y([`install`])}}});function splitWorkspaceSpecifier(t,n){if(t.startsWith(`.`)||t.startsWith(`/`)||t.includes(`:`))return null;let S=t.split(`/`),C=t.startsWith(`@`)?[2]:[1];for(let t of C){let C=S.slice(0,t).join(`/`);if(!n.has(C))continue;let N=S.slice(t).join(`/`);return{name:C,subpath:N?`./${N}`:`.`}}return null}function resolveRelative(t,n){let S=In(Hn(t),n);for(let t of[S,`${S}.js`,`${S}.mjs`,zn(S,`index.js`)])try{if(statSync(t).isFile())return t}catch{}return null}function workspaceEntry(t,n){let S=t.manifest,pick=t=>{if(typeof t==`string`)return t;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;for(let t of[`node`,`import`,`default`,`gjs`])if(t in n){let S=pick(n[t]);if(S)return S}return null},C=null;if(typeof S.exports==`string`?C=n===`.`?S.exports:null:S.exports&&typeof S.exports==`object`&&(C=pick(S.exports[n])),!C&&n===`.`&&(C=typeof S.module==`string`?S.module:null,C??=typeof S.main==`string`?S.main:null),!C)return null;let N=In(t.location,C);return existsSync(N)?N:null}function workspacePeers(t,n){return Object.keys(t.peerDependencies??{}).filter(t=>n.has(t))}function cliRuntimeClosure(t,n={}){let S=new Map(t.map(t=>[t.name,t])),C=new Set,N=n.entry,F=n.cliManifest;if(N===void 0||F===void 0){let t=cliPackageDir(),n=null;if(t)try{n=JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{}if(F??=n,N===void 0){let S=n?.bin,C=typeof S==`string`?S:S?.gjsify??n?.main;N=t&&C?In(t,C):null}}for(let t of workspacePeers(F??{},S))C.add(t);if(!N||!existsSync(N))return C;let I=new Set,H=[N];for(;H.length>0;){let t=H.shift();if(I.has(t))continue;I.add(t);let n;try{n=readFileSync(t,`utf8`)}catch{continue}for(let N of moduleSpecifiers$1(n)){if(N.startsWith(`.`)){let n=resolveRelative(t,N);n&&H.push(n);continue}let n=splitWorkspaceSpecifier(N,S),F=n?S.get(n.name):void 0;if(!n||!F)continue;C.add(n.name);for(let t of workspacePeers(F.manifest,S))C.add(t);let I=workspaceEntry(F,n.subpath);I&&H.push(I)}}return C}var BG=__esmMin(()=>{rf(),Xn(),cP(),Sh()});function signalTree(t,n,S){for(let t=n.length-1;t>=0;t--)try{process.kill(n[t],S)}catch{}try{t.kill(S)}catch{}}function killActiveChildren(){let t=new Map;for(let n of VG){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of VG){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},HG).unref?.()}function assertEveryIncludeMatches(t,n){if(!n||n.length===0)return;let S=n.filter(n=>filterWorkspaces(t,{include:[n]}).length===0);if(S.length===0)return;let C=[`gjsify foreach: --include matched no workspace (${S.length} of ${n.length} pattern(s)):`];for(let n of S){C.push(` ${JSON.stringify(n)}`);let S=stripSurroundingQuotes(n);if(S!==n&&filterWorkspaces(t,{include:[S]}).length>0){C.push(` → matches as ${JSON.stringify(S)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let N=t.map(t=>t.name).filter(t=>t.toLowerCase().includes(S.replace(/\*/g,``).toLowerCase())).slice(0,3);N.length>0&&C.push(` → did you mean: ${N.join(`, `)}?`)}throw C.push(` ${t.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ge.error(C.join(`
1259
+ `)+`\n ${C} is kept so this stays undoable. Remove the paths above and re-run.`),process.exit(1);if(removeDevLinkOverride(n),ge.log(` removed ${C}`),removeLocalIgnore(n)===`removed`&&ge.log(` removed ${kz} entry from .git/info/exclude`),t.install===!1){ge.log(`\n ${H.length} link(s) removed. Run \`gjsify install\` to restore the registry copies.`);return}ge.log(`\n ${H.length} link(s) removed — reinstalling to restore the registry copies.\n`);let{runCli:Y}=await Promise.resolve().then(()=>(aX(),iX));await Y([`install`])}}});function splitWorkspaceSpecifier(t,n){if(t.startsWith(`.`)||t.startsWith(`/`)||t.includes(`:`))return null;let S=t.split(`/`),C=t.startsWith(`@`)?[2]:[1];for(let t of C){let C=S.slice(0,t).join(`/`);if(!n.has(C))continue;let N=S.slice(t).join(`/`);return{name:C,subpath:N?`./${N}`:`.`}}return null}function resolveRelative(t,n){let S=In(Hn(t),n);for(let t of[S,`${S}.js`,`${S}.mjs`,zn(S,`index.js`)])try{if(statSync(t).isFile())return t}catch{}return null}function workspaceEntry(t,n){let S=t.manifest,pick=t=>{if(typeof t==`string`)return t;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;for(let t of[`node`,`import`,`default`,`gjs`])if(t in n){let S=pick(n[t]);if(S)return S}return null},C=null;if(typeof S.exports==`string`?C=n===`.`?S.exports:null:S.exports&&typeof S.exports==`object`&&(C=pick(S.exports[n])),!C&&n===`.`&&(C=typeof S.module==`string`?S.module:null,C??=typeof S.main==`string`?S.main:null),!C)return null;let N=In(t.location,C);return existsSync(N)?N:null}function workspacePeers(t,n){return Object.keys(t.peerDependencies??{}).filter(t=>n.has(t))}function cliRuntimeClosure(t,n={}){let S=new Map(t.map(t=>[t.name,t])),C=new Set,N=n.entry,F=n.cliManifest;if(N===void 0||F===void 0){let t=cliPackageDir(),n=null;if(t)try{n=JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{}if(F??=n,N===void 0){let S=n?.bin,C=typeof S==`string`?S:S?.gjsify??n?.main;N=t&&C?In(t,C):null}}for(let t of workspacePeers(F??{},S))C.add(t);if(!N||!existsSync(N))return C;let I=new Set,H=[N];for(;H.length>0;){let t=H.shift();if(I.has(t))continue;I.add(t);let n;try{n=readFileSync(t,`utf8`)}catch{continue}for(let N of moduleSpecifiers$1(n)){if(N.startsWith(`.`)){let n=resolveRelative(t,N);n&&H.push(n);continue}let n=splitWorkspaceSpecifier(N,S),F=n?S.get(n.name):void 0;if(!n||!F)continue;C.add(n.name);for(let t of workspacePeers(F.manifest,S))C.add(t);let I=workspaceEntry(F,n.subpath);I&&H.push(I)}}return C}var BG=__esmMin(()=>{rf(),Xn(),cP(),Sh()});function signalTree(t,n,S){for(let t=n.length-1;t>=0;t--)try{process.kill(n[t],S)}catch{}try{t.kill(S)}catch{}}function killActiveChildren(){let t=new Map;for(let n of VG){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of VG){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},HG).unref?.()}function assertEveryIncludeMatches(t,n){if(!n||n.length===0)return;let S=n.filter(n=>filterWorkspaces(t,{include:[n]}).length===0);if(S.length===0)return;let C=[`gjsify foreach: --include matched no workspace (${S.length} of ${n.length} pattern(s)):`];for(let n of S){C.push(` ${JSON.stringify(n)}`);let S=stripSurroundingQuotes(n);if(S!==n&&filterWorkspaces(t,{include:[S]}).length>0){C.push(` → matches as ${JSON.stringify(S)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let N=t.map(t=>t.name).filter(t=>t.toLowerCase().includes(S.replace(/\*/g,``).toLowerCase())).slice(0,3);N.length>0&&C.push(` → did you mean: ${N.join(`, `)}?`)}throw C.push(` ${t.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ge.error(C.join(`
1260
1260
  `)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(t){return t.length>=2&&(t[0]===`'`||t[0]===`"`)&&t[t.length-1]===t[0]?t.slice(1,-1):t}async function runSequential(t,n,S,C,N,F){for(let I of t)await runOne(I,n,S,!1,C,N,F)}async function runParallel(t,n,S,C,N,F,I){let H=0,W=[];for(let q=0;q<C;q++)W.push((async()=>{for(;H<t.length;)await runOne(t[H++],n,S,!0,N,F,I)})());await Promise.all(W)}async function runTopologicalParallel(t,n,S,C,N,F,I,H){let W=new Map([...buildDependencyGraph(t,{includeDev:F}).edges].map(([t,n])=>[t,new Set(n)])),q=new Map(t.map(t=>[t.name,t])),Y=t.length,X=new Set,Z=0,te=!process.stdout.isTTY||N,ne=new Map,re=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),ie=(Number.isFinite(re)&&re>0?re:20)*6e4;return new Promise((t,F)=>{let re=null,ae=Date.now(),describeInflight=()=>[...ne.entries()].map(([t,n])=>`${t} (${Math.round((Date.now()-n)/1e3)}s)`).join(`, `),failFast=t=>{re||(re=t,killActiveChildren(),setTimeout(()=>settle(),UG).unref?.())},oe=setInterval(()=>{let t=Date.now()-ae;t<3e5||ne.size===0||(ge.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(t/6e4)}min — in-flight: ${describeInflight()}`),t>=ie&&failFast(Error(`gjsify foreach: stalled — no workspace completed for ${Math.round(t/6e4)}min (override via GJSIFY_FOREACH_STALL_MINUTES); killed in-flight: ${describeInflight()}`)))},6e4);oe.unref?.();let settle=()=>{clearInterval(oe),re?F(re):t()},pump=()=>{if(!re){for(;Z<C;){let t=[...W.entries()].filter(([,t])=>[...t].every(t=>X.has(t))).map(([t])=>t);if(t.length===0)break;let C=t.sort()[0];W.delete(C),Z++,ne.set(C,Date.now()),te&&ge.error(`[gjsify foreach] start ${C} (${X.size}/${Y} done, ${Z} in flight)`),runOne(q.get(C),n,S,!0,N,I,H).then(()=>{X.add(C)}).catch(t=>{failFast(t instanceof Error?t:Error(String(t)))}).finally(()=>{Z--,ne.delete(C),ae=Date.now(),re?Z===0&&settle():W.size===0&&Z===0?settle():pump()})}W.size>0&&Z===0&&!re&&(clearInterval(oe),F(Error(`gjsify foreach --topological: stuck — workspaces ${[...W.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne(t,n,S,C,N,F,I){if(F){N&&ge.error(`[${t.name}] $ ${n} ${S.join(` `)}`),await spawnPrefixed(n,S,t.location,C?`[${t.name}] `:null);return}if(I&&I.tryRestore(t))return;let H=I?.snapshotOutputs(t),W=detectPackageManager(),q=W===`gjsify`?[`run`,n,...S]:[`run`,n,...S.length>0?[`--`,...S]:[]];N&&ge.error(`[${t.name}] $ ${W} ${q.join(` `)}`),await spawnPrefixed(W,q,t.location,C?`[${t.name}] `:null),I&&H&&I.storeAfterSuccess(t,H)}async function spawnPrefixed(t,n,S,C){let N=null,F=[];try{let I=await spawnToCompletion(t,n,{completion:`exit`,cwd:S,stdio:C?`pipe`:`inherit`,color:!0,onSpawn:t=>{N=t,VG.add(t);let n=!process.stdout.isTTY;C&&t.stdout&&t.stderr&&(F.push(prefixLines(t.stdout,process.stdout,C,n)),F.push(prefixLines(t.stderr,process.stderr,C,n)))}});for(let t of F)t();if(I.code!==0)throw Error(`${t} ${n.join(` `)} exited with code ${I.code}`)}finally{N&&VG.delete(N)}}var VG,HG,UG,WG,GG=__esmMin(()=>{_e(),mv(),rz(),a_(),BI(),HI(),BG(),iB(),xR(),cB(),dB(),VG=new Set,HG=5e3,UG=15e3,WG={command:`foreach [script] [args..]`,description:"Run a workspace script across all (or filtered) workspaces. Drop-in for `yarn workspaces foreach`: -A/--all, -p/--parallel, -t/--topological, --include, --exclude, --no-private. Pass --exec to run an arbitrary command instead of a script.",builder:t=>t.positional(`script`,{description:"Script name to run in each workspace (`run <name>`-equivalent). With --exec, the command to run instead.",type:`string`}).positional(`args`,{description:`Extra arguments forwarded to each child invocation.`,type:`string`,array:!0}).option(`all`,{description:"Include workspaces declared as `private: true`.",type:`boolean`,alias:`A`,default:!1}).option(`parallel`,{description:`Run workspaces in parallel (capped by --jobs).`,type:`boolean`,alias:`p`,default:!1}).option(`topological`,{description:`Wait for each workspace's deps to finish before starting it (production deps only).`,type:`boolean`,alias:`t`,default:!1}).option(`topological-dev`,{description:`Like --topological but also respects devDependencies (often cyclic — use sparingly).`,type:`boolean`,default:!1}).option(`include`,{description:`Glob pattern to include workspaces by name (repeatable). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=t.exec===!0,N=t.script,F=t.args??[];if(!C){let n=doubleDashArgs(t);n.length>0&&(F=[...F,...n])}if(C){let n=doubleDashArgs(t);if(n.length>0&&(N?F=[...F,...n]:(N=n[0],F=[...F,...n.slice(1)])),!N)return ge.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(S,t.include);let I=filterWorkspaces(S,{include:t.include,exclude:t.exclude,noPrivate:t.private===!1});if(t[`with-dependencies`]===!0){let n=affectedClosure(buildDependencyGraph(S,{includeDev:t[`topological-dev`]===!0}),I.map(t=>t.name));I=filterWorkspaces(S.filter(t=>n.has(t.name)),{exclude:t.exclude,noPrivate:t.private===!1})}if(!C){if(!N)return ge.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let t=N;I=I.filter(n=>typeof(n.manifest.scripts??{})[t]==`string`)}if(typeof t.shard==`string`&&t.shard.length>0){let n=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(t.shard);if(!n)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let S=Number(n[1]),C=Number(n[2]);if(C<1||S<1||S>C)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(C>1){let t=[...I].sort((t,n)=>t.name<n.name?-1:+(t.name>n.name));I=t.filter((t,n)=>n%C===S-1),ge.log(`gjsify foreach: shard ${S}/${C} → ${I.length} of ${t.length} workspace(s)`)}}if(I.length===0){ge.log(`gjsify foreach: no workspaces match (${C?`exec`:`script`}="${N}", include=${JSON.stringify(t.include??[])}, exclude=${JSON.stringify(t.exclude??[])})`);return}(t.topological||t[`topological-dev`])&&(I=topologicalSort(buildDependencyGraph(I,{includeDev:t[`topological-dev`]===!0})));let H=t.verbose===!0,W=N,q=t.cached??buildCacheEnabledByEnv();if(t.cached===!0&&C)return ge.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let Y=q&&!C?new BuildCacheRunner({root:n,workspaces:S,script:W,args:F,targets:I.map(t=>t.name)}):void 0,X=t.parallel===!0?cliRuntimeClosure(S):new Set,Z=X.size>0?I.filter(t=>X.has(t.name)):[],te=Z.length>0?I.filter(t=>!X.has(t.name)):I;try{if(Z.length>0){ge.error(`[gjsify foreach] serial prefix: ${Z.length} package(s) the running CLI imports — ${Z.map(t=>t.name).join(`, `)}`);for(let t of Z)ge.error(`[gjsify foreach] start ${t.name} (serial prefix)`),await runOne(t,W,F,!0,H,C,Y)}if(t.parallel&&!t.topological&&!t[`topological-dev`]){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runParallel(te,W,F,n,H,C,Y)}else if(t.parallel){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runTopologicalParallel(te,W,F,n,H,t[`topological-dev`]===!0,C,Y)}else await runSequential(te,W,F,H,C,Y)}catch(t){return killActiveChildren(),ge.error(t.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(t,n,S,C={}){let N=(n.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${t}/package.json`)}let F=findWorkspaceRoot(t),I=[zn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(zn(F,`node_modules`,`.bin`));let H=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},W={...process.env,...H,PATH:[...I,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:S,npm_package_name:n.name??``,npm_package_version:n.version??``,...C.env};if(C.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let q=await spawnToCompletion(N,[],{completion:`return`,cwd:t,env:W,shell:!0,stdio:C.stdio===`inherit-stderr`?`inherit-stderr`:C.stdio===`pipe`?`pipe`:`inherit`});if(q.code!==0)throw Error(`gjsify lifecycle-script: "${S}" in ${t} exited with ${describeExit(q)}`);return!0}var KG=__esmMin(()=>{Xn(),mv(),HI()});async function packWorkspace(t,n={}){let S=zn(t,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${t}`);let C=readFileSync(S,`utf-8`),N=JSON.parse(C),F=typeof N.name==`string`?N.name:``,I=typeof N.version==`string`?N.version:`0.0.0`;if(!F)throw Error(`gjsify pack: package.json at ${t} has no "name"`);let H=n.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(t,N,S,{optional:!0,stdio:n.lifecycleStdio});let W=readFileSync(S,`utf-8`),q=W===C?N:JSON.parse(W),Y=n.skipWorkspaceRewrite?q:rewriteWorkspaceDeps(q,t),X=JSON.stringify(Y,null,indentOf(W))+`
1261
1261
  `,Z=collectPackedFiles(t,q);assertTypeDeclarationsShipped(t,q,Z);let te=[{name:`package/`,directory:!0,mode:493}],ne=[],re=0;for(let n of Z){let S;S=n===`package.json`?new TextEncoder().encode(X):new Uint8Array(readFileSync(zn(t,n)));let C=statSync(zn(t,n)).mode&511;te.push({name:`package/${n}`,body:S,mode:C,mtime:0}),ne.push({path:n,size:S.byteLength,mode:C}),re+=S.byteLength}let ie=await gzip(createTarball(te)),ae=`${F.startsWith(`@`)?F.slice(1).replace(`/`,`-`):F}-${I}.tgz`,oe=createHash(`sha1`).update(ie).digest(`hex`),Q=`sha512-${createHash(`sha512`).update(ie).digest(`base64`)}`,se=n.destination?In(n.destination):t,ce=zn(se,ae);return n.dryRun||(mkdirSync(se,{recursive:!0}),writeFileSync(ce,ie)),{filename:ae,name:F,version:I,size:ie.byteLength,unpackedSize:re,shasum:oe,integrity:Q,entryCount:ne.length,files:ne,absolutePath:n.dryRun?null:ce}}function collectPackedFiles(t,n){let S=forceIncluded(n),C=Array.isArray(n.files)?n.files.filter(t=>typeof t==`string`):null,N=new Set;if(C)for(let n of expandFilesPatterns(t,C))N.add(n);else{let n=loadIgnore(t);for(let S of walkAll(t))n(S)||N.add(S)}for(let n of S)existsSync(zn(t,n))&&N.add(n);return[...N].sort()}function collectTypeDeclarationRefs(t){let n=new Set,add=t=>{if(typeof t!=`string`)return;let S=t.replace(/^\.\//,``);S.includes(`*`)||n.add(S)};for(let n of[`types`,`typings`])add(t[n]);let walk=t=>{if(!(!t||typeof t!=`object`)){if(Array.isArray(t)){for(let n of t)walk(n);return}for(let[n,S]of Object.entries(t))n===`types`||n===`typings`?add(S):walk(S)}};return walk(t.exports),[...n]}function assertTypeDeclarationsShipped(t,n,S){let C=new Set(S),N=collectTypeDeclarationRefs(n).filter(n=>{let S=zn(t,n);return existsSync(S)&&statSync(S).isFile()&&!C.has(n)});if(N.length===0)return;let F=typeof n.name==`string`?n.name:`(unnamed)`,I=Array.isArray(n.files)?JSON.stringify(n.files):`(none)`;throw Error(`gjsify pack: ${F} references TypeScript declaration file(s) via "exports"/"types" that exist on disk but are excluded from the tarball by the "files" allowlist (${I}):\n`+N.map(t=>` - ${t}`).join(`
1262
1262
  `)+`
@@ -1910,10 +1910,10 @@ await runStorybook({
1910
1910
  applicationId: ${JSON.stringify(n)},${F}
1911
1911
  stories: collectStoryModules([${N}]),
1912
1912
  });
1913
- `}var OJ,kJ=__esmMin(()=>{_e(),rf(),Xn(),N_(),__name$1(readPackage$4,`readPackage`),__name$1(generateEntry$4,`generateEntry`),OJ={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:t=>t.option(`stories`,{description:`Directory scanned recursively for *.story.ts (default: src, or gjsify.storybook.stories)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.storybook.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto; use auto,dom for canvas/DOM stories)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-storybook)`,type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle (gi:// → @gjsify/node-gi) and require @gjsify/node-gi installed in the project.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`watch`,{description:`Rebuild and relaunch when a story file changes`,type:`boolean`,default:!1}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$4(n),C=S.gjsify?.storybook??{},N=In(n,t.stories??C.stories??`src`),F=t.appId??C.applicationId??deriveAppId(S.name),I=t.title??C.title,H=t.globals??C.globals??`auto`,W=t.runtime??C.runtime??hostRuntime$1(),q=W===`gjs`?`gjs`:`node`,Y=zn(n,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`storybook.${q}.mjs`),writeEntry=()=>{let t=findStoryFiles(N).sort();return writeFileSync(X,generateEntry$4(t,F,I)),t.length},te=writeEntry();if(te===0)return ge.error(`No *.story.ts files found under ${Bn(n,N)||N}\n\n \`gjsify storybook\` renders the stories of the CURRENT project: it discovers\n \`*.story.ts\` files and launches a component browser over them. Point it at a\n different directory with --stories <dir> (or \`gjsify.storybook.stories\` in\n package.json) if yours live elsewhere.\n\n To SEE a storybook without authoring one first, run the curated Libadwaita\n component browser — it is a showcase, so it needs no project at all:\n\n gjsify showcase adwaita-storybook`),process.exit(1);ge.log(`Found ${te} story file(s) under ${Bn(n,N)||`.`} (runtime: ${W})`);let{runCli:ne}=await Promise.resolve().then(()=>(AY(),kY)),buildBundle=()=>ne([`build`,X,`--app`,q,`--globals`,H,`--outfile`,Z]),launch=async()=>{if(W===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(LR(),IR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else if(W===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(zR(),RR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:t}=await Promise.resolve().then(()=>(zR(),RR));await t(W,Z,[],{completion:`exit`,exitOnSuccess:!0})}};if(!t.watch){if(await buildBundle(),t.buildOnly)return;await launch();return}let{runWatchLoop:re,spawnBundleSupervised:ie}=await Promise.resolve().then(()=>(DJ(),EJ));await re({dir:N,dirLabel:Bn(n,N)||`.`,label:`storybook`,prepare:()=>{writeEntry()},build:buildBundle,spawnChild:t.buildOnly?null:()=>ie(W,Z,n,`the storybook`),output:Z})}}});function resolveSitePackage(t){let n=In(t);for(;;){let t=zn(n,`node_modules`,`@gjsify`,`site`);if(existsSync(zn(t,`package.json`)))return t;let S=Hn(n);if(S===n)return;n=S}}function gjsOnPath(){return spawnSync(`gjs`,[`--version`],{stdio:`ignore`}).status===0}function pickRuntime(t,n){if(t)return t;let S=hostRuntime$1();return S===`gjs`||resolveNodeGi(n)?S:gjsOnPath()?`gjs`:S}function generateEntry$3(t,n=`gjsify site`){let S=`// Auto-generated by \`${n}\` — do not edit by hand.\nimport { runSiteCli } from '@gjsify/site';\n`;return t===`gjs`?`${S}import system from 'system';\n\nsystem.exit(await runSiteCli(system.programArgs));\n`:`${S}\nprocess.exit(await runSiteCli(process.argv.slice(2)));\n`}async function dispatchSite(t){let n=process.cwd(),S=resolveSitePackage(n);if(!S)return ge.error(`${t.invokedAs}: @gjsify/site is not installed in this project.\n\n The generator ships as its own package so a project only pays for it when it
1913
+ `}var OJ,kJ=__esmMin(()=>{_e(),rf(),Xn(),N_(),__name$1(readPackage$4,`readPackage`),__name$1(generateEntry$4,`generateEntry`),OJ={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:t=>t.option(`stories`,{description:`Directory scanned recursively for *.story.ts (default: src, or gjsify.storybook.stories)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.storybook.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto; use auto,dom for canvas/DOM stories)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-storybook)`,type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle (gi:// → @gjsify/node-gi) and require @gjsify/node-gi installed in the project.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`watch`,{description:`Rebuild and relaunch when a story file changes`,type:`boolean`,default:!1}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$4(n),C=S.gjsify?.storybook??{},N=In(n,t.stories??C.stories??`src`),F=t.appId??C.applicationId??deriveAppId(S.name),I=t.title??C.title,H=t.globals??C.globals??`auto`,W=t.runtime??C.runtime??hostRuntime$1(),q=W===`gjs`?`gjs`:`node`,Y=zn(n,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`storybook.${q}.mjs`),writeEntry=()=>{let t=findStoryFiles(N).sort();return writeFileSync(X,generateEntry$4(t,F,I)),t.length},te=writeEntry();if(te===0)return ge.error(`No *.story.ts files found under ${Bn(n,N)||N}\n\n \`gjsify storybook\` renders the stories of the CURRENT project: it discovers\n \`*.story.ts\` files and launches a component browser over them. Point it at a\n different directory with --stories <dir> (or \`gjsify.storybook.stories\` in\n package.json) if yours live elsewhere.\n\n To SEE a storybook without authoring one first, run the curated Libadwaita\n component browser — it is a showcase, so it needs no project at all:\n\n gjsify showcase adwaita-storybook`),process.exit(1);ge.log(`Found ${te} story file(s) under ${Bn(n,N)||`.`} (runtime: ${W})`);let{runCli:ne}=await Promise.resolve().then(()=>(aX(),iX)),buildBundle=()=>ne([`build`,X,`--app`,q,`--globals`,H,`--outfile`,Z]),launch=async()=>{if(W===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(LR(),IR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else if(W===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(zR(),RR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:t}=await Promise.resolve().then(()=>(zR(),RR));await t(W,Z,[],{completion:`exit`,exitOnSuccess:!0})}};if(!t.watch){if(await buildBundle(),t.buildOnly)return;await launch();return}let{runWatchLoop:re,spawnBundleSupervised:ie}=await Promise.resolve().then(()=>(DJ(),EJ));await re({dir:N,dirLabel:Bn(n,N)||`.`,label:`storybook`,prepare:()=>{writeEntry()},build:buildBundle,spawnChild:t.buildOnly?null:()=>ie(W,Z,n,`the storybook`),output:Z})}}});function resolveSitePackage(t){let n=In(t);for(;;){let t=zn(n,`node_modules`,`@gjsify`,`site`);if(existsSync(zn(t,`package.json`)))return t;let S=Hn(n);if(S===n)return;n=S}}function gjsOnPath(){return spawnSync(`gjs`,[`--version`],{stdio:`ignore`}).status===0}function pickRuntime(t,n){if(t)return t;let S=hostRuntime$1();return S===`gjs`||resolveNodeGi(n)?S:gjsOnPath()?`gjs`:S}function generateEntry$3(t,n=`gjsify site`){let S=`// Auto-generated by \`${n}\` — do not edit by hand.\nimport { runSiteCli } from '@gjsify/site';\n`;return t===`gjs`?`${S}import system from 'system';\n\nsystem.exit(await runSiteCli(system.programArgs));\n`:`${S}\nprocess.exit(await runSiteCli(process.argv.slice(2)));\n`}async function dispatchSite(t){let n=process.cwd(),S=resolveSitePackage(n);if(!S)return ge.error(`${t.invokedAs}: @gjsify/site is not installed in this project.\n\n The generator ships as its own package so a project only pays for it when it
1914
1914
  publishes a page or a store listing. Add it, then run this again:
1915
1915
 
1916
- npm install --save-dev @gjsify/site`),process.exit(1);if(t.needsClient&&!existsSync(zn(S,`lib`,`client`,`site.js`)))return ge.error(`${t.invokedAs}: ${S} has no built client bundle (lib/client/site.js).\n In a source checkout, build the package first: \`gjsify workspace site build\`.`),process.exit(1);let C=pickRuntime(t.runtime,n),N=C===`gjs`?`gjs`:`node`,F=zn(n,`node_modules`,`.cache`,`gjsify-site`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.${N}.ts`),H=zn(F,`site.${N}.mjs`);writeFileSync(I,generateEntry$3(N,t.invokedAs));let W=t.globals??`auto`;if(N===`gjs`){let{BuildAction:t}=await Promise.resolve().then(()=>(uR(),sR));await t.bundleFileForGjs(I,H,{globals:W,preserveDefaultExport:!1,toolchainAnchor:t.runningCliFile(),logLevel:`silent`})}else{let{runCli:t}=await Promise.resolve().then(()=>(AY(),kY));await t([`build`,I,`--app`,N,`--globals`,W,`--outfile`,H])}let q=[...t.argv.slice(0,1),`--package-dir`,S,...t.argv.slice(1)];if(C===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(LR(),IR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}if(C===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(zR(),RR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}let{runRuntimeBundle:Y}=await Promise.resolve().then(()=>(zR(),RR));await Y(C,H,q,{completion:`exit`,exitOnSuccess:!0})}var AJ=__esmMin(()=>{_e(),sv(),rf(),Xn(),N_(),zR(),__name$1(generateEntry$3,`generateEntry`)}),jJ,MJ=__esmMin(()=>{Xn(),AJ(),jJ={command:`site <operation>`,description:`Render this project's static landing page from its AppStream metainfo (downloads, screenshots, release notes, support links), or sync the page catalogues.`,builder:t=>t.positional(`operation`,{description:`build — render the pages; i18n — update the page catalogues`,type:`string`,choices:[`build`,`i18n`],demandOption:!0}).option(`root`,{description:`Repository to read from (default: the working directory)`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: <root>/dist)`,type:`string`}).option(`offline`,{description:`Skip every network call`,type:`boolean`,default:!1}).option(`drafts`,{description:"build: include blog posts marked `draft: true`",type:`boolean`,default:!1}).option(`cache`,{description:`Use the one-hour HTTP response cache (--no-cache to ignore it)`,type:`boolean`,default:!0}).option(`cache-dir`,{description:`Where the response cache and the image renditions live`,defaultDescription:`<root>/node_modules/.cache/gjsify-site`,type:`string`}).option(`check`,{description:`i18n: report what is out of date instead of writing it`,type:`boolean`,default:!1}).option(`package`,{description:`i18n: sync @gjsify/site's own catalogues instead of this project's`,type:`boolean`,default:!1}).option(`runtime`,{description:"Runtime to build for and run on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle and require @gjsify/node-gi in the project; without it the default falls back to gjs.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}),handler:async t=>{let n=process.cwd(),S=[t.operation];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.offline&&S.push(`--offline`),t.drafts&&S.push(`--drafts`),t.cache?t.cacheDir&&S.push(`--cache-dir`,In(n,t.cacheDir)):S.push(`--no-cache`),t.check&&S.push(`--check`),t.package&&S.push(`--package`),await dispatchSite({invokedAs:`gjsify site`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:t.operation===`build`})}}});function readFlag(t,n){let S=`--${n}`;for(let n=0;n<t.length;n++){let C=t[n];if(C===S)return t[n+1];if(C.startsWith(`${S}=`))return C.slice(S.length+1)}}function withFlag(t,n,S){let C=`--${n}`,N=[...t];for(let t=0;t<N.length;t++){let n=N[t];if(n===C)return N[t+1]=S,N;if(n.startsWith(`${C}=`))return N[t]=`${C}=${S}`,N}return N.push(C,S),N}function buildEntryPoint(t){let n=t[1];if(!(n===void 0||n.startsWith(`-`)))return n}function noEntryError(t,n){let S=n?`\`${t}\` is not a plain \`gjsify build <entry> …\` command, so its entry point cannot be read`:`this package declares no \`${t}\` script`;return Error(`gjsify dev: nothing to build — ${S}.\n Name the entry point directly: gjsify dev src/index.ts\n or point at another script: gjsify dev --script <name>`)}function planDev(t){let n=t.scripts[t.scriptName],S=typeof n==`string`?gjsifyCommandArgv(n):null,C=S&&S[0]===`build`?S:null,N=t.entry??(C?buildEntryPoint(C):void 0);if(N===void 0)throw noEntryError(t.scriptName,typeof n==`string`);let F;return C?(F=[...C],buildEntryPoint(C)===void 0?F.splice(1,0,N):F[1]=N):F=[`build`,N],F=withFlag(F,`app`,t.app),t.globals!==void 0&&(F=withFlag(F,`globals`,t.globals)),t.outfile!==void 0&&(F=withFlag(F,`outfile`,t.outfile)),{buildArgv:F,bundle:readFlag(F,`outfile`)??t.declaredBundle,watchDir:t.watchDir??Hn(N)}}function noBundleError(t,n){return Error(`gjsify dev: nothing to launch — neither \`${t}\` nor --outfile names an output file, and this package declares no ${n===`gjs`?"`gjsify.main`":"`gjsify.example.node`"}.\n Pass one: gjsify dev --outfile dist/index.${n}.mjs\n or rebuild without launching: gjsify dev --build-only`)}var NJ=__esmMin(()=>{Xn(),rR()});function readPackage$3(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}var PJ,FJ=__esmMin(()=>{_e(),rf(),Xn(),NJ(),_v(),N_(),__name$1(readPackage$3,`readPackage`),PJ={command:`dev [entry]`,description:`Watch this project, rebuild on change and relaunch the app.`,builder:t=>t.positional(`entry`,{description:"Entry point to build (default: the one the build script names, e.g. src/index.ts from `build:gjs`).",type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle.",type:`string`,choices:hv,defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`script`,{description:`package.json script the build flags are read from (default: build:gjs, or build:node for node/bun/deno).`,type:`string`}).option(`globals`,{description:"Override the build script `--globals` value.",type:`string`}).option(`outfile`,{description:"Override the build script `--outfile` path.",type:`string`}).option(`watch-dir`,{description:`Directory watched recursively (default: the directory of the entry point).`,type:`string`}).option(`debounce`,{description:`Quiet window in ms after a change before rebuilding.`,type:`number`,default:200}).option(`build-only`,{description:`Rebuild on every change but never launch the app.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$3(n),C=t.runtime??hostRuntime$1(),N=buildAppForRuntime(C),F=t.script??(N===`gjs`?`build:gjs`:`build:node`),I;try{I=planDev({scripts:S.scripts??{},scriptName:F,app:N,declaredBundle:N===`gjs`?S.gjsify?.main:S.gjsify?.example?.node,entry:t.entry,globals:t.globals,outfile:t.outfile,watchDir:t.watchDir})}catch(t){return ge.error(t.message),process.exit(1)}let H=I.bundle===void 0?void 0:In(n,I.bundle);if(H===void 0&&!t.buildOnly)return ge.error(noBundleError(F,N).message),process.exit(1);let W=In(n,I.watchDir);if(!existsSync(W))return ge.error(`gjsify dev: nothing to watch — ${Bn(n,W)||W} does not exist.\n Point the loop at your sources: gjsify dev --watch-dir <dir>`),process.exit(1);let q=H===void 0?`\`${F}\` output`:Bn(n,H);ge.log(`Watching ${Bn(n,W)||`.`} → ${q} (runtime: ${C})`);let{runCli:Y}=await Promise.resolve().then(()=>(AY(),kY)),{runWatchLoop:X,spawnBundleSupervised:Z}=await Promise.resolve().then(()=>(DJ(),EJ));await X({dir:W,dirLabel:Bn(n,W)||`.`,label:`dev`,build:()=>Y(I.buildArgv),spawnChild:t.buildOnly||H===void 0?null:()=>Z(C,H,n,`this project`),output:H,debounceMs:t.debounce})}}});function readPackage$2(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveStorybookAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function deriveBrowserAppId$1(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function hasDep(t,n){return!!(t.dependencies?.[n]||t.devDependencies?.[n])}function generateEntry$2(t,n,S,C,N){let F=JSON.stringify(n),I=N?`, { address: ${JSON.stringify(N)} }`:``;return t===`storybook`?`// Auto-generated by \`gjsify debug\` — do not edit by hand.
1916
+ npm install --save-dev @gjsify/site`),process.exit(1);if(t.needsClient&&!existsSync(zn(S,`lib`,`client`,`site.js`)))return ge.error(`${t.invokedAs}: ${S} has no built client bundle (lib/client/site.js).\n In a source checkout, build the package first: \`gjsify workspace site build\`.`),process.exit(1);let C=pickRuntime(t.runtime,n),N=C===`gjs`?`gjs`:`node`,F=zn(n,`node_modules`,`.cache`,`gjsify-site`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.${N}.ts`),H=zn(F,`site.${N}.mjs`);writeFileSync(I,generateEntry$3(N,t.invokedAs));let W=t.globals??`auto`;if(N===`gjs`){let{BuildAction:t}=await Promise.resolve().then(()=>(uR(),sR));await t.bundleFileForGjs(I,H,{globals:W,preserveDefaultExport:!1,toolchainAnchor:t.runningCliFile(),logLevel:`silent`})}else{let{runCli:t}=await Promise.resolve().then(()=>(aX(),iX));await t([`build`,I,`--app`,N,`--globals`,W,`--outfile`,H])}let q=[...t.argv.slice(0,1),`--package-dir`,S,...t.argv.slice(1)];if(C===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(LR(),IR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}if(C===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(zR(),RR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}let{runRuntimeBundle:Y}=await Promise.resolve().then(()=>(zR(),RR));await Y(C,H,q,{completion:`exit`,exitOnSuccess:!0})}var AJ=__esmMin(()=>{_e(),sv(),rf(),Xn(),N_(),zR(),__name$1(generateEntry$3,`generateEntry`)}),jJ,MJ=__esmMin(()=>{Xn(),AJ(),jJ={command:`site <operation>`,description:`Render this project's static landing page from its AppStream metainfo (downloads, screenshots, release notes, support links), or sync the page catalogues.`,builder:t=>t.positional(`operation`,{description:`build — render the pages; i18n — update the page catalogues`,type:`string`,choices:[`build`,`i18n`],demandOption:!0}).option(`root`,{description:`Repository to read from (default: the working directory)`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: <root>/dist)`,type:`string`}).option(`offline`,{description:`Skip every network call`,type:`boolean`,default:!1}).option(`drafts`,{description:"build: include blog posts marked `draft: true`",type:`boolean`,default:!1}).option(`cache`,{description:`Use the one-hour HTTP response cache (--no-cache to ignore it)`,type:`boolean`,default:!0}).option(`cache-dir`,{description:`Where the response cache and the image renditions live`,defaultDescription:`<root>/node_modules/.cache/gjsify-site`,type:`string`}).option(`check`,{description:`i18n: report what is out of date instead of writing it`,type:`boolean`,default:!1}).option(`package`,{description:`i18n: sync @gjsify/site's own catalogues instead of this project's`,type:`boolean`,default:!1}).option(`runtime`,{description:"Runtime to build for and run on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle and require @gjsify/node-gi in the project; without it the default falls back to gjs.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}),handler:async t=>{let n=process.cwd(),S=[t.operation];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.offline&&S.push(`--offline`),t.drafts&&S.push(`--drafts`),t.cache?t.cacheDir&&S.push(`--cache-dir`,In(n,t.cacheDir)):S.push(`--no-cache`),t.check&&S.push(`--check`),t.package&&S.push(`--package`),await dispatchSite({invokedAs:`gjsify site`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:t.operation===`build`})}}});function readFlag(t,n){let S=`--${n}`;for(let n=0;n<t.length;n++){let C=t[n];if(C===S)return t[n+1];if(C.startsWith(`${S}=`))return C.slice(S.length+1)}}function withFlag(t,n,S){let C=`--${n}`,N=[...t];for(let t=0;t<N.length;t++){let n=N[t];if(n===C)return N[t+1]=S,N;if(n.startsWith(`${C}=`))return N[t]=`${C}=${S}`,N}return N.push(C,S),N}function buildEntryPoint(t){let n=t[1];if(!(n===void 0||n.startsWith(`-`)))return n}function noEntryError(t,n){let S=n?`\`${t}\` is not a plain \`gjsify build <entry> …\` command, so its entry point cannot be read`:`this package declares no \`${t}\` script`;return Error(`gjsify dev: nothing to build — ${S}.\n Name the entry point directly: gjsify dev src/index.ts\n or point at another script: gjsify dev --script <name>`)}function planDev(t){let n=t.scripts[t.scriptName],S=typeof n==`string`?gjsifyCommandArgv(n):null,C=S&&S[0]===`build`?S:null,N=t.entry??(C?buildEntryPoint(C):void 0);if(N===void 0)throw noEntryError(t.scriptName,typeof n==`string`);let F;return C?(F=[...C],buildEntryPoint(C)===void 0?F.splice(1,0,N):F[1]=N):F=[`build`,N],F=withFlag(F,`app`,t.app),t.globals!==void 0&&(F=withFlag(F,`globals`,t.globals)),t.outfile!==void 0&&(F=withFlag(F,`outfile`,t.outfile)),{buildArgv:F,bundle:readFlag(F,`outfile`)??t.declaredBundle,watchDir:t.watchDir??Hn(N)}}function noBundleError(t,n){return Error(`gjsify dev: nothing to launch — neither \`${t}\` nor --outfile names an output file, and this package declares no ${n===`gjs`?"`gjsify.main`":"`gjsify.example.node`"}.\n Pass one: gjsify dev --outfile dist/index.${n}.mjs\n or rebuild without launching: gjsify dev --build-only`)}var NJ=__esmMin(()=>{Xn(),rR()});function readPackage$3(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}var PJ,FJ=__esmMin(()=>{_e(),rf(),Xn(),NJ(),_v(),N_(),__name$1(readPackage$3,`readPackage`),PJ={command:`dev [entry]`,description:`Watch this project, rebuild on change and relaunch the app.`,builder:t=>t.positional(`entry`,{description:"Entry point to build (default: the one the build script names, e.g. src/index.ts from `build:gjs`).",type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle.",type:`string`,choices:hv,defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`script`,{description:`package.json script the build flags are read from (default: build:gjs, or build:node for node/bun/deno).`,type:`string`}).option(`globals`,{description:"Override the build script `--globals` value.",type:`string`}).option(`outfile`,{description:"Override the build script `--outfile` path.",type:`string`}).option(`watch-dir`,{description:`Directory watched recursively (default: the directory of the entry point).`,type:`string`}).option(`debounce`,{description:`Quiet window in ms after a change before rebuilding.`,type:`number`,default:200}).option(`build-only`,{description:`Rebuild on every change but never launch the app.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$3(n),C=t.runtime??hostRuntime$1(),N=buildAppForRuntime(C),F=t.script??(N===`gjs`?`build:gjs`:`build:node`),I;try{I=planDev({scripts:S.scripts??{},scriptName:F,app:N,declaredBundle:N===`gjs`?S.gjsify?.main:S.gjsify?.example?.node,entry:t.entry,globals:t.globals,outfile:t.outfile,watchDir:t.watchDir})}catch(t){return ge.error(t.message),process.exit(1)}let H=I.bundle===void 0?void 0:In(n,I.bundle);if(H===void 0&&!t.buildOnly)return ge.error(noBundleError(F,N).message),process.exit(1);let W=In(n,I.watchDir);if(!existsSync(W))return ge.error(`gjsify dev: nothing to watch — ${Bn(n,W)||W} does not exist.\n Point the loop at your sources: gjsify dev --watch-dir <dir>`),process.exit(1);let q=H===void 0?`\`${F}\` output`:Bn(n,H);ge.log(`Watching ${Bn(n,W)||`.`} → ${q} (runtime: ${C})`);let{runCli:Y}=await Promise.resolve().then(()=>(aX(),iX)),{runWatchLoop:X,spawnBundleSupervised:Z}=await Promise.resolve().then(()=>(DJ(),EJ));await X({dir:W,dirLabel:Bn(n,W)||`.`,label:`dev`,build:()=>Y(I.buildArgv),spawnChild:t.buildOnly||H===void 0?null:()=>Z(C,H,n,`this project`),output:H,debounceMs:t.debounce})}}});function readPackage$2(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveStorybookAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function deriveBrowserAppId$1(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function hasDep(t,n){return!!(t.dependencies?.[n]||t.devDependencies?.[n])}function generateEntry$2(t,n,S,C,N){let F=JSON.stringify(n),I=N?`, { address: ${JSON.stringify(N)} }`:``;return t===`storybook`?`// Auto-generated by \`gjsify debug\` — do not edit by hand.
1917
1917
  import { runDevtoolsMcp, storybookProfile } from '@gjsify/devtools-mcp';
1918
1918
 
1919
1919
  await runDevtoolsMcp(storybookProfile(${F}${I}));
@@ -1933,18 +1933,21 @@ await runDevtoolsMcp({
1933
1933
  version: ${JSON.stringify(C)},
1934
1934
  busNameBase: ${F},${N?`\n address: ${JSON.stringify(N)},`:``}
1935
1935
  });
1936
- `}var IJ,LJ=__esmMin(()=>{_e(),rf(),Xn(),__name$1(readPackage$2,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$2,`generateEntry`),IJ={command:`debug`,description:`Launch an MCP bridge for a devtools-enabled gjsify app (org.gjsify.Devtools).`,builder:t=>t.option(`bus-name`,{description:`App DBus base name (default: gjsify.devtools.busNameBase, or the storybook app-id)`,type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`profile`,{description:`Tool profile: generic | storybook | browser | cdp (default: auto — storybook if @gjsify/storybook is a dep, browser if @gjsify/devtools-browser is, cdp if @gjsify/devtools-cdp is, else generic)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-debug)`,type:`string`}).option(`build-only`,{description:`Build the bridge bundle but do not launch it (for a .mcp.json command pointing at the bundle)`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$2(n),C=S.gjsify?.devtools??{},N=t.profile??C.profile??(hasDep(S,`@gjsify/storybook`)?`storybook`:hasDep(S,`@gjsify/devtools-browser`)?`browser`:hasDep(S,`@gjsify/devtools-cdp`)?`cdp`:`generic`),F=t.busName??C.busNameBase??(N===`storybook`?S.gjsify?.storybook?.applicationId??deriveStorybookAppId(S.name):N===`browser`||N===`cdp`?S.gjsify?.browse?.applicationId??deriveBrowserAppId$1(S.name):void 0);if(!F)return ge.error(`gjsify debug: no bus name — set package.json#gjsify.devtools.busNameBase or pass --bus-name <org.example.App>`),process.exit(1);let I=t.globals??C.globals??`auto`,H=S.name?`${S.name}-devtools`:`gjsify-devtools`,W=zn(n,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(W,{recursive:!0});let q=zn(W,`entry.ts`),Y=t.out?In(n,t.out):zn(W,`bridge.gjs.mjs`),X=t.address??C.address;writeFileSync(q,generateEntry$2(N,F,H,`0.8.0`,X)),ge.error(`[gjsify debug] profile=${N} bus=${F}${X?` address=${X}`:``}`);let{runCli:Z}=await Promise.resolve().then(()=>(AY(),kY));if(await Z([`build`,q,`--app`,`gjs`,`--shebang`,`--globals`,I,`--outfile`,Y]),t.buildOnly){ge.error(`[gjsify debug] built ${Y}`);return}let{runGjsBundle:te}=await Promise.resolve().then(()=>(LR(),IR));await te(Y,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage$1(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function generateEntry$1(){return`// Auto-generated by \`gjsify devtools\` — do not edit by hand.
1936
+ `}var IJ,LJ=__esmMin(()=>{_e(),rf(),Xn(),__name$1(readPackage$2,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$2,`generateEntry`),IJ={command:`debug`,description:`Launch an MCP bridge for a devtools-enabled gjsify app (org.gjsify.Devtools).`,builder:t=>t.option(`bus-name`,{description:`App DBus base name (default: gjsify.devtools.busNameBase, or the storybook app-id)`,type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`profile`,{description:`Tool profile: generic | storybook | browser | cdp (default: auto — storybook if @gjsify/storybook is a dep, browser if @gjsify/devtools-browser is, cdp if @gjsify/devtools-cdp is, else generic)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-debug)`,type:`string`}).option(`build-only`,{description:`Build the bridge bundle but do not launch it (for a .mcp.json command pointing at the bundle)`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$2(n),C=S.gjsify?.devtools??{},N=t.profile??C.profile??(hasDep(S,`@gjsify/storybook`)?`storybook`:hasDep(S,`@gjsify/devtools-browser`)?`browser`:hasDep(S,`@gjsify/devtools-cdp`)?`cdp`:`generic`),F=t.busName??C.busNameBase??(N===`storybook`?S.gjsify?.storybook?.applicationId??deriveStorybookAppId(S.name):N===`browser`||N===`cdp`?S.gjsify?.browse?.applicationId??deriveBrowserAppId$1(S.name):void 0);if(!F)return ge.error(`gjsify debug: no bus name — set package.json#gjsify.devtools.busNameBase or pass --bus-name <org.example.App>`),process.exit(1);let I=t.globals??C.globals??`auto`,H=S.name?`${S.name}-devtools`:`gjsify-devtools`,W=zn(n,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(W,{recursive:!0});let q=zn(W,`entry.ts`),Y=t.out?In(n,t.out):zn(W,`bridge.gjs.mjs`),X=t.address??C.address;writeFileSync(q,generateEntry$2(N,F,H,`0.8.0`,X)),ge.error(`[gjsify debug] profile=${N} bus=${F}${X?` address=${X}`:``}`);let{runCli:Z}=await Promise.resolve().then(()=>(aX(),iX));if(await Z([`build`,q,`--app`,`gjs`,`--shebang`,`--globals`,I,`--outfile`,Y]),t.buildOnly){ge.error(`[gjsify debug] built ${Y}`);return}let{runGjsBundle:te}=await Promise.resolve().then(()=>(LR(),IR));await te(Y,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage$1(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function generateEntry$1(){return`// Auto-generated by \`gjsify devtools\` — do not edit by hand.
1937
1937
  import system from 'system';
1938
1938
 
1939
1939
  import { runDevtoolsCli } from '@gjsify/devtools-mcp';
1940
1940
 
1941
1941
  system.exit(await runDevtoolsCli(system.programArgs));
1942
- `}var RJ,zJ=__esmMin(()=>{_e(),rf(),Xn(),__name$1(readPackage$1,`readPackage`),__name$1(generateEntry$1,`generateEntry`),RJ={command:`devtools <operation> [operands..]`,description:"Drive a running devtools-enabled app from a script: capture a screenshot to a file, find a widget, activate it, send a key. Peer of `gjsify debug`, which speaks MCP for an AI agent.",builder:t=>t.positional(`operation`,{description:`Control-plane operation: shot | find | activate | key | tree | property | …`,type:`string`,demandOption:!0}).positional(`operands`,{description:"Subcommand arguments — e.g. the output path for `shot`, the selector for `find`.",type:`string`,array:!0}).option(`bus-name`,{description:"App DBus base name — the app's Gtk application id (default: gjsify.devtools.busNameBase, then the storybook app-id). Unlike `gjsify debug` there is no derived fallback: the bus name IS the application id, and guessing it produces a name nothing answers to",type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`instance`,{description:`App instance label for a multi-instance app (default: GJSIFY_DEVTOOLS_INSTANCE)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-devtools)`,type:`string`}).option(`timeout`,{description:`Seconds to keep polling GetStatus for the control plane to answer (default: 30). 0 = do not wait`,type:`number`,default:30}),handler:async t=>{let n=process.cwd(),S=readPackage$1(n),C=S.gjsify?.devtools??{},N=t.busName??C.busNameBase??S.gjsify?.storybook?.applicationId??S.gjsify?.browse?.applicationId;if(!N)return ge.error(`gjsify devtools: no bus name — the bus name IS the app's Gtk application id, so it cannot be derived from the package name. Pass --bus-name <org.example.App> (the app prints it when it exports the control plane) or set package.json#gjsify.devtools.busNameBase.`),process.exit(1);let F=zn(n,`node_modules`,`.cache`,`gjsify-devtools`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.ts`),H=t.out?In(n,t.out):zn(F,`cli.gjs.mjs`),W=t.globals??`auto`;writeFileSync(I,generateEntry$1()),ge.error(`[gjsify devtools] bus=${N}${t.address?` address=${t.address}`:``}${t.instance?` instance=${t.instance}`:``}`);let{runCli:q}=await Promise.resolve().then(()=>(AY(),kY));await q([`build`,I,`--app`,`gjs`,`--globals`,W,`--outfile`,H]);let Y=[t.operation,...t.operands??[],`--bus-name`,N];t.address&&Y.push(`--address`,t.address),t.instance&&Y.push(`--instance`,t.instance),Y.push(`--timeout`,String(t.timeout));let{runGjsBundle:X}=await Promise.resolve().then(()=>(LR(),IR));await X(H,Y,{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveBrowserAppId(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function generateEntry(t,n,S,C,N){let F=S?`\n title: ${JSON.stringify(S)},`:``,I=n?`\n homeUrl: ${JSON.stringify(n)},`:``,H=C===void 0?``:`\n inspectorPort: ${C},`,W=N?`\n screenshot: ${JSON.stringify(N)},`:``;return`// Auto-generated by \`gjsify browse\` — do not edit by hand.
1942
+ `}var RJ,zJ=__esmMin(()=>{_e(),rf(),Xn(),__name$1(readPackage$1,`readPackage`),__name$1(generateEntry$1,`generateEntry`),RJ={command:`devtools <operation> [operands..]`,description:"Drive a running devtools-enabled app from a script: capture a screenshot to a file, find a widget, activate it, send a key. Peer of `gjsify debug`, which speaks MCP for an AI agent.",builder:t=>t.positional(`operation`,{description:`Control-plane operation: shot | find | activate | key | tree | property | …`,type:`string`,demandOption:!0}).positional(`operands`,{description:"Subcommand arguments — e.g. the output path for `shot`, the selector for `find`.",type:`string`,array:!0}).option(`bus-name`,{description:"App DBus base name — the app's Gtk application id (default: gjsify.devtools.busNameBase, then the storybook app-id). Unlike `gjsify debug` there is no derived fallback: the bus name IS the application id, and guessing it produces a name nothing answers to",type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`instance`,{description:`App instance label for a multi-instance app (default: GJSIFY_DEVTOOLS_INSTANCE)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-devtools)`,type:`string`}).option(`timeout`,{description:`Seconds to keep polling GetStatus for the control plane to answer (default: 30). 0 = do not wait`,type:`number`,default:30}),handler:async t=>{let n=process.cwd(),S=readPackage$1(n),C=S.gjsify?.devtools??{},N=t.busName??C.busNameBase??S.gjsify?.storybook?.applicationId??S.gjsify?.browse?.applicationId;if(!N)return ge.error(`gjsify devtools: no bus name — the bus name IS the app's Gtk application id, so it cannot be derived from the package name. Pass --bus-name <org.example.App> (the app prints it when it exports the control plane) or set package.json#gjsify.devtools.busNameBase.`),process.exit(1);let F=zn(n,`node_modules`,`.cache`,`gjsify-devtools`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.ts`),H=t.out?In(n,t.out):zn(F,`cli.gjs.mjs`),W=t.globals??`auto`;writeFileSync(I,generateEntry$1()),ge.error(`[gjsify devtools] bus=${N}${t.address?` address=${t.address}`:``}${t.instance?` instance=${t.instance}`:``}`);let{runCli:q}=await Promise.resolve().then(()=>(aX(),iX));await q([`build`,I,`--app`,`gjs`,`--globals`,W,`--outfile`,H]);let Y=[t.operation,...t.operands??[],`--bus-name`,N];t.address&&Y.push(`--address`,t.address),t.instance&&Y.push(`--instance`,t.instance),Y.push(`--timeout`,String(t.timeout));let{runGjsBundle:X}=await Promise.resolve().then(()=>(LR(),IR));await X(H,Y,{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveBrowserAppId(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function generateEntry(t,n,S,C,N){let F=S?`\n title: ${JSON.stringify(S)},`:``,I=n?`\n homeUrl: ${JSON.stringify(n)},`:``,H=C===void 0?``:`\n inspectorPort: ${C},`,W=N?`\n screenshot: ${JSON.stringify(N)},`:``;return`// Auto-generated by \`gjsify browse\` — do not edit by hand.
1943
1943
  import { runBrowserDevtools } from '@gjsify/devtools-browser';
1944
1944
 
1945
1945
  await runBrowserDevtools({
1946
1946
  applicationId: ${JSON.stringify(t)},${F}${I}${H}${W}
1947
1947
  });
1948
- `}var BJ,VJ=__esmMin(()=>{_e(),rf(),Xn(),BJ={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:t=>t.positional(`url`,{description:`Initial URL to load (default: page:welcome)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.browse.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto,dom — WebKit/iframe need DOM globals)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-browse)`,type:`string`}).option(`devtools`,{description:`Enable the MCP devtools control plane (sets GJSIFY_DEVTOOLS=1)`,type:`boolean`,default:!1}).option(`inspector-port`,{description:`Enable WebKit's remote inspector protocol on this port + the Cdp* methods (implies --devtools)`,type:`number`}).option(`screenshot`,{description:`One-shot: load the URL, capture a WebKit screenshot to this path, and exit (CI / quick captures).`,type:`string`}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage(n),C=S.gjsify?.browse??{},N=t.appId??C.applicationId??deriveBrowserAppId(S.name),F=t.title??C.title,I=t.globals??C.globals??`auto,dom`,H=t.url,W=t.inspectorPort??C.inspectorPort,q=t.devtools||W!==void 0,Y=zn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?In(n,t.screenshot):void 0)),ge.log(`[gjsify browse] app=${N}${H?` url=${H}`:``}${q?` devtools=1`:``}${W===void 0?``:` inspector-port=${W}`}`);let{runCli:te}=await Promise.resolve().then(()=>(AY(),kY));if(await te([`build`,X,`--app`,`gjs`,`--globals`,I,`--outfile`,Z]),t.buildOnly){ge.log(`[gjsify browse] built ${Z}`);return}q&&(process.env.GJSIFY_DEVTOOLS=`1`),W!==void 0&&(process.env.WEBKIT_INSPECTOR_HTTP_SERVER=`127.0.0.1:${W}`);let{runGjsBundle:ne}=await Promise.resolve().then(()=>(LR(),IR));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function webextIconPaths(t,n,S){let C=t.sources.get(n);if(C===void 0)throw Error(`gjsify webext: the manifest asks for icon "${n}", and \`gjsify.webext.icons.sources\` declares ${[...t.sources.keys()].map(t=>`"${t}"`).join(`, `)||`none`}.`);let N=t.svgTargets.has(S.id),F={};for(let S of t.sizes)F[String(S)]=N?`icons/${Un(C.get(S))}`:`icons/${n}-${S}.png`;return F}function svgIconFiles(t){let n=new Map;for(let[S,C]of t.sources)for(let t of C.values()){let C=`icons/${Un(t)}`,N=n.get(C);if(N!==void 0&&N!==t)throw Error(`gjsify webext: icon "${S}" uses ${t}, and ${N} has the same file name; an SVG target would receive only one of them as `+C+`. Rename one.`);n.set(C,t)}return n}async function renderWebextIcons(t,n,S=rasterizeSvg){let C=n.some(n=>!t.svgTargets.has(n.id)),N=n.some(n=>t.svgTargets.has(n.id)),F=new Map;if(C){let n=new Map;for(let[S,C]of t.sources)for(let[t,N]of C)n.set(N,[...n.get(N)??[],{size:t,name:S}]);for(let[t,C]of n){let n=await S({svg:t,sizes:[...new Set(C.map(t=>t.size))],command:`gjsify webext`});for(let{size:t,name:S}of C)F.set(`icons/${S}-${t}.png`,n.get(t))}}return{png:F,svg:N?svgIconFiles(t):new Map}}function writeWebextIcons(t,n,S,C){if(mkdirSync(zn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,zn(C,n));else for(let[n,S]of t.png)writeFileSync(zn(C,n),S)}var HJ=__esmMin(()=>{rf(),Xn(),bH()});function isRecord$1(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function mergeManifest(t,n){let S={...t};for(let[t,C]of Object.entries(n))C===null?delete S[t]:isRecord$1(C)&&isRecord$1(S[t])?S[t]=mergeManifest(S[t],C):S[t]=C;return S}function applyTargetOverrides(t,n){let{$targets:S,...C}=t;if(S===void 0)return C;if(!isRecord$1(S))throw Error("gjsify webext: the manifest's `$targets` must be an object.");let N=S[n];if(N===void 0)return C;if(!isRecord$1(N))throw Error(`gjsify webext: \`$targets["${n}"]\` in the manifest must be an object.`);return mergeManifest(C,N)}async function composeManifest(t,n){let S=typeof t==`function`?await t(n):applyTargetOverrides(t,n.target);if(!isRecord$1(S))throw Error(`gjsify webext: the manifest for ${n.target} is not an object (got ${typeof S}).`);if(S.version!==void 0)return S;let C={};for(let[t,N]of Object.entries(S))C[t]=N,t===`name`&&(C.version=n.version);return C.version===void 0&&(C.version=n.version),C}async function loadManifestTemplate(t){if(/\.json$/i.test(t))try{return JSON.parse(readFileSync(t,`utf8`))}catch(n){throw Error(`gjsify webext: ${t} is not valid JSON: ${n.message}`)}let n,cleanup=null;if(isGjs()){let{BuildAction:S}=await Promise.resolve().then(()=>(uR(),sR)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Un(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=zn(Hn(C),`manifest-${process.pid}-${++UJ}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++UJ}`;try{let S=(await import(n)).default;if(typeof S!=`function`&&!isRecord$1(S))throw Error(`gjsify webext: ${t} has no default export. Export the manifest object, or a function \`(ctx) => manifest\` that receives the target.`);return S}finally{cleanup?.()}}function addPath(t,n){typeof n!=`string`||n===``||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.includes(`*`)||t.add(n.replace(/^\//,``).replace(/[?#].*$/,``))}function addIconValue(t,n){if(typeof n==`string`)addPath(t,n);else if(isRecord$1(n))for(let S of Object.values(n))addPath(t,S)}function manifestFileReferences(t){let n=new Set,S=t.background;if(isRecord$1(S)&&(addPath(n,S.service_worker),addPath(n,S.page),Array.isArray(S.scripts)))for(let t of S.scripts)addPath(n,t);if(Array.isArray(t.content_scripts)){for(let S of t.content_scripts)if(isRecord$1(S)){for(let t of[`js`,`css`])if(Array.isArray(S[t]))for(let C of S[t])addPath(n,C)}}for(let S of[`action`,`browser_action`,`page_action`,`sidebar_action`]){let C=t[S];isRecord$1(C)&&(addPath(n,C.default_popup),addPath(n,C.default_panel),addIconValue(n,C.default_icon))}if(isRecord$1(t.options_ui)&&addPath(n,t.options_ui.page),addPath(n,t.options_page),addPath(n,t.devtools_page),isRecord$1(t.side_panel)&&addPath(n,t.side_panel.default_path),addIconValue(n,t.icons),isRecord$1(t.chrome_url_overrides))for(let S of Object.values(t.chrome_url_overrides))addPath(n,S);if(Array.isArray(t.web_accessible_resources)){for(let S of t.web_accessible_resources)if(typeof S==`string`)addPath(n,S);else if(isRecord$1(S)&&Array.isArray(S.resources))for(let t of S.resources)addPath(n,t)}return[...n].sort()}function checkManifest(t,n,S){let C=[];t.manifest_version!==n.manifestVersion&&C.push(`manifest_version is ${JSON.stringify(t.manifest_version)}, and target ${n.id} is Manifest V${n.manifestVersion}. gjsify does not convert keys between versions — branch on \`ctx.manifestVersion\` in the manifest.`);for(let N of manifestFileReferences(t))existsSync(zn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(zn(S,`_locales`)),F=t.default_locale;return N&&typeof F!=`string`?C.push(`_locales/ exists but the manifest sets no default_locale; the browser refuses to load it.`):!N&&F!==void 0?C.push(`the manifest sets default_locale "${String(F)}" but there is no _locales/ directory.`):typeof F==`string`&&!existsSync(zn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var UJ,WJ=__esmMin(()=>{rf(),Xn(),cr(),N_(),__name$1(isRecord$1,`isRecord`),UJ=0});function planPage(t,n,S){let C=Hn(n),N=[],F=[],local=t=>{if(ZJ.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return Rn(n)?n:In(C,n)},I=S.replace(GJ,n=>{let S=qJ.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!QJ.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:YJ.test(n)?`esm`:`iife`,output:F}),n.replace(qJ,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(KJ,t=>{if(!XJ.test(t))return t;let n=JJ.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Un(S);return F.push({source:S,output:C}),t.replace(JJ,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var GJ,KJ,qJ,JJ,YJ,XJ,ZJ,QJ,$J=__esmMin(()=>{Xn(),GJ=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,KJ=/<link\b[^>]*>/gi,qJ=/\bsrc\s*=\s*(["'])([^"']+)\1/i,JJ=/\bhref\s*=\s*(["'])([^"']+)\1/i,YJ=/\btype\s*=\s*["']module["']/i,XJ=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,ZJ=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,QJ=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=eY?n:eY}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=zn(S,C.name);C.isDirectory()?walk(N):n.push({path:Bn(t,N).split(/[\\/]/).join(`/`),mode:420,data:readFileSync(N)})}};return walk(t),n}async function buildWebext(t){let{config:n,targets:S,outDir:C,define:N}=t,F=t.log??(t=>ge.log(t)),I=t.mode===`production`&&n.minify,H=zn(C,`.stage`);rmSync(H,{recursive:!0,force:!0}),mkdirSync(H,{recursive:!0});try{for(let[S,C]of n.scripts)await t.bundle({entry:C,outfile:zn(H,`${S}.js`),format:`iife`,define:N,minify:I});let W=new Map;for(let[S,C]of n.pages){let n=planPage(S,C,readFileSync(C,`utf8`));for(let S of n.scripts)await t.bundle({entry:S.entry,outfile:zn(H,S.output),format:S.format,define:N,minify:I});for(let t of n.stylesheets){let n=W.get(t.output);if(n!==void 0&&n!==t.source)throw Error(`gjsify webext: pages link ${n} and ${t.source}, which would both be written as ${t.output}. Rename one.`);W.set(t.output,t.source),cpSync(t.source,zn(H,t.output))}writeFileSync(zn(H,`${S}.html`),n.html)}let q=n.icons,Y=q?await renderWebextIcons(q,S,t.rasterize):null,X=await loadManifestTemplate(n.manifest),Z={folders:new Map,zips:new Map};for(let I of S){let S=zn(C,I.id);t.inPlace||rmSync(S,{recursive:!0,force:!0}),mkdirSync(S,{recursive:!0}),n.publicDir&&cpSync(n.publicDir,S,{recursive:!0}),n.localesDir&&cpSync(n.localesDir,zn(S,`_locales`),{recursive:!0}),cpSync(H,S,{recursive:!0}),q&&Y&&writeWebextIcons(Y,q,I,S);let W=await composeManifest(X,{target:I.id,browser:I.browser,manifestVersion:I.manifestVersion,mode:t.mode,version:n.version,define:N,icons:t=>{if(!q)throw Error(`gjsify webext: the manifest asks for icon "${t}" and \`gjsify.webext.icons\` is not declared.`);return webextIconPaths(q,t,I)}});writeFileSync(zn(S,`manifest.json`),`${JSON.stringify(W,null,2)}\n`);let te=checkManifest(W,I,S);if(te.length>0)throw Error(`gjsify webext: ${I.id} would not load:\n - ${te.join(`
1949
- - `)}`);if(Z.folders.set(I.id,S),F(`built ${Bn(process.cwd(),S)||S}`),t.zip){let t=zn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Bn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var eY,tY=__esmMin(()=>{_e(),rf(),Xn(),WW(),HJ(),WJ(),$J(),eY=315532800});function parseWebextTarget(t){let n=/^([a-z]+)-mv([23])$/.exec(t),S=n?.[1];if(!n||S===void 0||!nY.includes(S))throw Error(`gjsify webext: unknown target "${t}". A target is <browser>-mv<2|3> with browser one of ${nY.join(`, `)} (e.g. chrome-mv3, firefox-mv2).`);let C=n[2]===`2`?2:3,N=C===2?iY.get(S):void 0;if(N!==void 0)throw Error(`gjsify webext: target "${t}" does not exist any more: ${N}. Use ${S}-mv3.`);return{id:t,browser:S,manifestVersion:C}}function webExtRunTarget(t){return t.browser===`firefox`?`firefox-desktop`:t.browser===`chrome`||t.browser===`edge`||t.browser===`opera`?`chromium`:null}var nY,rY,iY,aY=__esmMin(()=>{nY=[`chrome`,`edge`,`firefox`,`opera`,`safari`],rY=[`chrome-mv3`,`firefox-mv3`],iY=new Map([[`chrome`,`chrome has removed Manifest V2`],[`edge`,`edge has removed Manifest V2`],[`opera`,`opera's extension store accepts Manifest V3 only`]])});function isRecord(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function defaultArtifactName(t){let n=(t??`extension`).replace(/^@[^/]+\//,``);return n===``?`extension`:n}function iconSourceForSize(t,n){if(typeof t==`string`)return t;let S=Object.keys(t).filter(t=>/^\d+$/.test(t)).map(Number).sort((t,n)=>t-n).find(t=>n<=t);return S===void 0?t.default:t[String(S)]}function resolveWebextConfig(t,n,S=defaultExists){let C=[],N=t.gjsify?.webext;if(N===void 0)throw Error("gjsify webext: this package declares no `gjsify.webext` block in package.json. Add one naming at least the manifest and one script or page — see `gjsify webext build --help`.");if(!isRecord(N))throw Error("gjsify webext: `gjsify.webext` must be an object.");let F=N,abs=t=>Rn(t)?t:In(n,t),need=(t,n,N)=>{let F=abs(n);return S(F,N)||C.push(`${t} "${n}" is not a ${N===`dir`?`directory`:`file`}.`),F},I=[],H=F.targets??[...rY];if(!Array.isArray(H)||H.length===0)C.push("`targets` must be a non-empty array of target names.");else for(let t of H)try{I.some(n=>n.id===t)?C.push(`target "${t}" is listed twice.`):I.push(parseWebextTarget(String(t)))}catch(t){C.push(t.message.replace(/^gjsify webext: /,``))}let W=``;if(F.manifest!==void 0)W=need("`manifest`",F.manifest,`file`);else{let t=sY.find(t=>S(zn(n,t),`file`));t===void 0?C.push(`no \`manifest\` declared and none of ${sY.join(`, `)} exists.`):W=zn(n,t)}let q=new Map,claim=(t,n)=>{let S=q.get(t);S===void 0?q.set(t,n):C.push(`${n} and ${S} both write ${t}.`)},readEntries=t=>{let n=new Map,S=F[t];if(S===void 0)return n;if(!isRecord(S))return C.push(`\`${t}\` must map an output name to a source file.`),n;for(let[N,F]of Object.entries(S)){if(!cY.test(N)){C.push(`\`${t}.${N}\`: an output name is a plain file name (letters, digits, . _ -).`);continue}if(typeof F!=`string`){C.push(`\`${t}.${N}\` must be a path.`);continue}n.set(N,need(`\`${t}.${N}\``,F,`file`)),t===`scripts`?claim(`${N}.js`,`\`scripts.${N}\``):claim(`${N}.html`,`\`pages.${N}\``)}return n},Y=readEntries(`scripts`),X=readEntries(`pages`);Y.size===0&&X.size===0&&C.push("declare at least one entry under `scripts` or `pages`; there is nothing to build.");for(let t of X.keys())Y.has(t)&&C.push(`\`scripts.${t}\` and the script of \`pages.${t}\` both write ${t}.js.`);let Z=null;if(F.icons!==void 0)if(!isRecord(F.icons)||!isRecord(F.icons.sources))C.push("`icons` must be an object with a `sources` map (icon name → SVG).");else{let t=F.icons.sizes??oY;(!Array.isArray(t)||t.length===0||t.some(t=>!Number.isInteger(t)||t<=0))&&C.push("`icons.sizes` must be a non-empty list of positive integers.");let n=new Set(F.icons.svg??[]);for(let t of n)I.some(n=>n.id===t)||C.push(`\`icons.svg\` names "${t}", which is not one of this package's targets.`);let N=new Map;for(let[n,I]of Object.entries(F.icons.sources)){if(!cY.test(n)){C.push(`\`icons.sources.${n}\`: an icon name is a plain file name.`);continue}if(typeof I!=`string`&&!isRecord(I)){C.push(`\`icons.sources.${n}\` must be an SVG path or a map of size ceilings to SVGs.`);continue}let F=new Map;for(let S of t){let t=iconSourceForSize(I,S);if(t===void 0){C.push(`\`icons.sources.${n}\` has no SVG for ${S} px — add a "default".`);continue}/\.svg$/i.test(t)||C.push(`\`icons.sources.${n}\`: "${t}" is not an .svg file.`),F.set(S,abs(t))}for(let t of new Set(F.values()))S(t,`file`)||C.push(`\`icons.sources.${n}\`: "${t}" does not exist.`);N.set(n,F)}Z={sizes:t,sources:N,svgTargets:n}}let optionalDir=(t,C)=>{let N=F[t];if(N!==void 0)return need(`\`${t}\``,N,`dir`);let I=zn(n,C);return S(I,`dir`)?I:null},te=optionalDir(`public`,`public`),ne=optionalDir(`locales`,`_locales`),re=F.define??{};(!isRecord(re)||Object.values(re).some(t=>typeof t!=`string`))&&C.push("`define` must map identifiers to JS expressions given as strings.");let ie=F.watch??[];if((!Array.isArray(ie)||ie.some(t=>typeof t!=`string`))&&C.push("`watch` must be a list of directories."),C.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${zn(n,`package.json`)}:\n - ${C.join(`
1950
- - `)}`);return{root:n,name:F.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,manifest:W,scripts:Y,pages:X,icons:Z,publicDir:te,localesDir:ne,outDir:abs(F.outDir??`.output`),define:re,watch:ie.map(abs),minify:F.minify??!0}}function defaultExists(t,n){if(!existsSync(t))return!1;let S=statSync(t);return n===`dir`?S.isDirectory():S.isFile()}function selectTargets(t,n){return n===void 0||n.length===0?t.targets:n.map(n=>{let S=t.targets.find(t=>t.id===n);if(S)return S;throw parseWebextTarget(n),Error(`gjsify webext: target "${n}" is not in \`gjsify.webext.targets\` (${t.targets.map(t=>t.id).join(`, `)}).`)})}var oY,sY,cY,lY=__esmMin(()=>{rf(),Xn(),aY(),oY=[16,32,48,128],sY=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],cY=/^[A-Za-z0-9][A-Za-z0-9._-]*$/});function webExtRunArgs(t){let n=webExtRunTarget(t.target);if(n===null)throw Error(`gjsify webext dev: web-ext cannot launch ${t.target.browser}. Build with \`gjsify webext build --target ${t.target.id}\` and load the folder by hand, or pass \`--no-launch\`.`);let S=[`run`,`--source-dir`,t.sourceDir,`--target`,n,`--no-input`,`--profile-create-if-missing`];return n===`firefox-desktop`?(S.push(`--firefox-profile`,t.profile,`--keep-profile-changes`),t.browserBinary&&S.push(`--firefox`,t.browserBinary),t.headless&&S.push(`--arg=-headless`)):(S.push(`--chromium-profile`,t.profile),t.browserBinary&&S.push(`--chromium-binary`,t.browserBinary),t.headless&&S.push(`--arg=--headless=new`)),S}function defaultDevProfile(t,n,S=process.env){return zn(S.XDG_CACHE_HOME||zn(homedir(),`.cache`),`gjsify`,`webext`,t,n.id)}function resolveWebExt(t,n=process.platform,S=process.env){let C=n===`win32`?`web-ext.cmd`:`web-ext`;for(let n=t;;n=Hn(n)){let t=zn(n,`node_modules`,`.bin`);if(existsSync(zn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(Jn)}};if(Hn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var uY,dY=__esmMin(()=>{rf(),a_(),Xn(),sL(),aY(),uY="gjsify webext dev: `web-ext` is not installed. Add it to the project (`gjsify install --save-dev web-ext`) or install it globally, or pass `--no-launch` to rebuild without a browser."});function loadConfig(t){let n=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function effectiveDefines(t,n){let S={...t.define};for(let t of n){let n=t.indexOf(`=`);if(n<=0)throw Error(`gjsify webext: --define "${t}" is not KEY=VALUE.`);S[t.slice(0,n)]=t.slice(n+1)}return S}async function bundleInProcess(t){let{runCli:n}=await Promise.resolve().then(()=>(AY(),kY)),S=[`build`,t.entry,`--app`,`browser`,`--format`,t.format,`--outfile`,t.outfile];for(let[n,C]of Object.entries(t.define))S.push(`--define`,`${n}=${C}`);t.minify||S.push(`--no-minify`),await n(S)}async function runBuild(t,n){let S=process.cwd(),C=loadConfig(S),N=t.mode===`development`?`development`:`production`;await buildWebext({config:C,targets:selectTargets(C,t.target),outDir:t.outDir?In(S,t.outDir):C.outDir,mode:N,define:effectiveDefines(C,t.define),inPlace:!1,zip:n,bundle:bundleInProcess})}function devTarget(t,n){if(n&&n.length>1)throw Error(`gjsify webext dev: pass one --target.`);let[S]=selectTargets(t,n);return n&&n.length===1?S:t.targets.find(t=>t.browser===`firefox`)??S}function devWatchTargets(t,n){let skip=t=>t===`node_modules`||t.startsWith(`.`),S=[{path:t.root,recursive:!1}];for(let C of readdirSync(t.root,{withFileTypes:!0})){let N=zn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+qn)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var fY,pY,mY,hY,gY,_Y,vY,yY=__esmMin(()=>{_e(),rf(),Xn(),AJ(),tY(),lY(),dY(),fY={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},pY={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},mY={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},hY={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,fY).option(`out-dir`,pY).option(`define`,mY).option(`mode`,{description:`Passed to the manifest as ctx.mode; development also skips minification.`,type:`string`,choices:[`production`,`development`],default:`production`}),handler:t=>runBuild(t,!1)},gY={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,fY).option(`out-dir`,pY).option(`define`,mY),handler:t=>runBuild(t,!0)},_Y={command:`dev`,description:`Build one target in development mode, launch it in a browser via web-ext, and rebuild in place on change.`,builder:t=>t.option(`target`,{...fY,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,mY).option(`launch`,{description:`Start a browser with the extension (--no-launch only rebuilds).`,type:`boolean`,default:!0}).option(`browser-binary`,{description:`Browser executable web-ext should start.`,type:`string`}).option(`profile`,{description:`Browser profile directory (default: $XDG_CACHE_HOME/gjsify/webext/<name>/<target>).`,type:`string`}).option(`headless`,{description:`Start the browser without a window.`,type:`boolean`,default:!1}).option(`debounce`,{description:`Quiet window in ms before a rebuild.`,type:`number`,default:200}),handler:async t=>{let n=process.cwd(),S=loadConfig(n),C=devTarget(S,t.target),N=t.outDir?In(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=zn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(uY);let W=null,stopBrowser=()=>{W?.kill()};process.on(`SIGINT`,stopBrowser),process.on(`SIGTERM`,stopBrowser);let launch=async()=>{if(H===null||W!==null)return;let N=t.profile?In(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(Hn(N),{recursive:!0});let F=webExtRunArgs({sourceDir:I,target:C,profile:N,browserBinary:t.browserBinary,headless:t.headless});ge.log(`[webext] launching ${C.id} with profile ${N}`);let{spawnSupervised:q}=await Promise.resolve().then(()=>(DJ(),EJ));W=await q(H.cmd,F,H.env),W.on(`exit`,t=>{ge.log(`[webext] browser closed (${t??0}) — stopping`),process.exit(0)})},{runWatchLoop:q}=await Promise.resolve().then(()=>(DJ(),EJ));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+qn),build:async()=>{await buildWebext({config:S,targets:[C],outDir:N,mode:`development`,define:F,inPlace:!0,zip:!1,bundle:bundleInProcess}),await launch()},spawnChild:null,debounceMs:t.debounce})}},vY={command:`listing`,description:`Derive the store listings (Chrome Web Store, Edge Add-ons, Firefox AMO) from the AppStream metainfo, the gettext catalogues and the screenshots: texts, permission justifications and exact-size images.`,builder:t=>t.option(`store`,{description:`Which store to write (default: all).`,type:`string`,choices:[`cws`,`edge`,`amo`,`all`],default:`all`}).option(`stores`,{description:`Several stores at once, comma separated (cws,edge,amo) or all; wins over --store.`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: dist/listing).`,type:`string`}).option(`check`,{description:`Validate against the store limits; write nothing.`,type:`boolean`,default:!1}).option(`metainfo`,{description:`AppStream metainfo (default: gjsify.webext.listing.metainfo, else gjsify.site.metainfo).`,type:`string`}).option(`config`,{description:`JSON file that overrides the gjsify.webext.listing block of package.json.`,type:`string`}).option(`pot`,{description:`Also write the config strings as a gettext template.`,type:`string`}).option(`root`,{description:`Project root (default: the working directory).`,type:`string`}).option(`offline`,{description:`Skip downloading screenshots hosted elsewhere.`,type:`boolean`,default:!1}).option(`runtime`,{description:`Runtime to run on: gjs | node | bun | deno (default: the host runtime).`,type:`string`,choices:[`gjs`,`node`,`bun`,`deno`]}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto).",type:`string`}),handler:async t=>{let n=process.cwd(),S=[`listing`,`--store`,t.stores??t.store];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.check&&S.push(`--check`),t.metainfo&&S.push(`--metainfo`,t.metainfo),t.config&&S.push(`--config`,In(n,t.config)),t.pot&&S.push(`--pot`,In(n,t.pot)),t.offline&&S.push(`--offline`),await dispatchSite({invokedAs:`gjsify webext listing`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:!1})}}}),bY,xY=__esmMin(()=>{yY(),bY={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(hY.command,hY.description,hY.builder,hY.handler).command(gY.command,gY.description,gY.builder,gY.handler).command(_Y.command,_Y.description,_Y.builder,_Y.handler).command(vY.command,vY.description,vY.builder,vY.handler).demandCommand(1).strict()}});function blueprintsUnder(t,n){let S;try{S=statSync(t)}catch{return n}if(!S.isDirectory())return t.endsWith(`.blp`)&&n.push(t),n;for(let S of readdirSync(t).sort())SY.has(S)||S.startsWith(`.`)||blueprintsUnder(zn(t,S),n);return n}var SY,CY,formatFor,wY,TY=__esmMin(()=>{_e(),rf(),Xn(),_A(),wA(),SY=new Set([`node_modules`,`dist`,`lib`,`.git`]),CY=new Map,formatFor=t=>{let n=CY.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return CY.set(t,S),S},wY={command:`types [paths..]`,description:"Generate the `<name>.d.blp.ts` type sidecar for each .blp (ADR 0088), so `import { build }` / `import { GTypeName }` type-check before anything is built. Defaults to the current directory.",builder:t=>t.positional(`paths`,{description:`Files or directories to scan for .blp (default: the current directory)`,type:`string`,array:!0,normalize:!0,default:[]}).option(`check`,{description:`Write nothing; exit non-zero when a sidecar is missing or stale`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print every file considered, not only the ones that changed`,type:`boolean`,default:!1}),handler:async t=>{let n=t.paths??[],S=(n.length>0?n:[`.`]).map(t=>Rn(t)?t:In(process.cwd(),t)),C=[];for(let t of S)blueprintsUnder(t,C);let N=[],F=0;for(let n of C){let S=sidecarPathFor(n),C=emitTypedSidecar(parseBlueprint(readFileSync(n,`utf8`),n),Un(n),formatFor(Hn(n))),I;try{I=readFileSync(S,`utf8`)}catch{I=void 0}if(I===C){t.verbose&&ge.log(`[gjsify blueprint types] current: ${S}`);continue}if(t.check){N.push(S);continue}writeFileSync(S,C,`utf8`),F+=1,ge.log(`[gjsify blueprint types] wrote ${S}`)}if(t.check){if(N.length===0){ge.log(`[gjsify blueprint types] ${C.length} .blp checked, every sidecar current.`);return}for(let t of N)ge.error(`[gjsify blueprint types] missing or stale: ${t}`);ge.error(`[gjsify blueprint types] run without --check to regenerate.`),process.exitCode=1;return}ge.log(`[gjsify blueprint types] ${C.length} .blp scanned, ${F} sidecar(s) written, ${C.length-F} already current.`)}}}),EY,DY=__esmMin(()=>{TY(),EY={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(wY.command,wY.description,wY.builder,wY.handler).demandCommand(1).strict()}}),OY=__esmMin(()=>{hR(),_R(),bR(),wR(),VR(),WR(),$z(),tB(),rB(),pB(),EB(),GB(),JB(),QB(),tV(),QV(),CG(),AG(),SB(),IG(),zG(),GG(),dB(),XG(),MK(),LK(),GK(),rq(),aq(),cq(),uq(),gq(),Sq(),Aq(),Nq(),Fq(),Lq(),Kq(),Jq(),Xq(),rJ(),cJ(),uJ(),TJ(),kJ(),MJ(),FJ(),LJ(),zJ(),VJ(),xY(),DY()}),kY=__exportAll$5({runCli:()=>runCli});function runtimeLabel(){let t=gjsSystemVersion();if(t!==void 0){let n=Number(t);return`GJS ${Math.floor(n/1e4)}.${Math.floor(n%1e4/100)}.${n%100} (SpiderMonkey)`}return isBun()?`Bun ${globalThis.Bun?.version??process.versions.bun??``}`.trim():isDeno()?`Deno ${globalThis.Deno?.version?.deno??``}`.trim():isNode()?`Node.js ${process.version}`:`unknown runtime`}async function runCli(t){ensureGjsifyShimOnPath();let n=sh(t);await n.scriptName(Ch).version(cliVersion()).strict().fail((t,S)=>{let C=classifyCliFailure(t,S);if(C.kind===`usage`)throw n.showHelp(`error`),Error(C.message,{cause:S})}).wrap(n.terminalWidth()).command(WB.command,WB.description,WB.builder,WB.handler).command(PG.command,PG.description,PG.builder,PG.handler).command(LG.command,LG.description,LG.builder,LG.handler).command(RG.command,RG.description,RG.builder,RG.handler).command(mR.command,mR.description,mR.builder,mR.handler).command(gR.command,gR.description,gR.builder,gR.handler).command(yR.command,yR.description,yR.builder,yR.handler).command(CR.command,CR.description,CR.builder,CR.handler).command(BR.command,BR.description,BR.builder,BR.handler).command(UR.command,UR.description,UR.builder,UR.handler).command(Qz.command,Qz.description,Qz.builder,Qz.handler).command(xB.command,xB.description,xB.builder,xB.handler).command(eB.command,eB.description,eB.builder,eB.handler).command(nB.command,nB.description,nB.builder,nB.handler).command(fB.command,fB.description,fB.builder,fB.handler).command(TB.command,TB.description,TB.builder,TB.handler).command(qB.command,qB.description,qB.builder,qB.handler).command(ZB.command,ZB.description,ZB.builder,ZB.handler).command(eV.command,eV.description,eV.builder,eV.handler).command(ZV.command,ZV.description,ZV.builder,ZV.handler).command(xG.command,xG.description,xG.builder,xG.handler).command(kG.command,kG.description,kG.builder,kG.handler).command(WG.command,WG.description,WG.builder,WG.handler).command(uB.command,uB.description,uB.builder,uB.handler).command(qG.command,qG.description,qG.builder,qG.handler).command(jK.command,jK.description,jK.builder,jK.handler).command(iq.command,iq.description,iq.builder,iq.handler).command(IK.command,IK.description,IK.builder,IK.handler).command(WK.command,WK.description,WK.builder,WK.handler).command(nq.command,nq.description,nq.builder,nq.handler).command(sq.command,sq.description,sq.builder,sq.handler).command(lq.command,lq.description,lq.builder,lq.handler).command(hq.command,hq.description,hq.builder,hq.handler).command(xq.command,xq.description,xq.builder,xq.handler).command(Oq.command,Oq.description,Oq.builder,Oq.handler).command(Mq.command,Mq.description,Mq.builder,Mq.handler).command(Iq.command,Iq.description,Iq.builder,Iq.handler).command(Pq.command,Pq.description,Pq.builder,Pq.handler).command($q.command,$q.description,$q.builder,$q.handler).command(Gq.command,Gq.description,Gq.builder,Gq.handler).command(qq.command,qq.description,qq.builder,qq.handler).command(Yq.command,Yq.description,Yq.builder,Yq.handler).command(sJ.command,sJ.description,sJ.builder,sJ.handler).command(lJ.command,lJ.description,lJ.builder,lJ.handler).command(CJ.command,CJ.description,CJ.builder,CJ.handler).command(OJ.command,OJ.description,OJ.builder,OJ.handler).command(jJ.command,jJ.description,jJ.builder,jJ.handler).command(PJ.command,PJ.description,PJ.builder,PJ.handler).command(IJ.command,IJ.description,IJ.builder,IJ.handler).command(RJ.command,RJ.description,RJ.builder,RJ.handler).command(BJ.command,BJ.description,BJ.builder,BJ.handler).command(bY.command,bY.description,bY.builder,bY.handler).command(EY.command,EY.description,EY.builder,EY.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var AY=__esmMin(()=>{ch(),lh(),Sh(),OY(),wh(),N_(),Yz()});AY(),N_(),Zz();function pendingFailureCode(t,n){if(n||t==null)return null;let S=Number(t);return Number.isFinite(S)&&S!==0?S:null}function exitOnReportedFailure(){let t=pendingFailureCode(process.exitCode,isDaemonCommand());t!==null&&gjsExit(t)}_e(),N_();try{await runCli(hideBin(process.argv))}catch(t){let n=typeof t==`object`&&t&&typeof t.code==`string`?t.code:``,S=t instanceof Error?t.message:String(t);ge.error(n&&!S.includes(n)?`${n}: ${S}`:S),process.env.GJSIFY_DEBUG&&t instanceof Error&&t.stack&&ge.error(t.stack),process.exitCode=1,gjsExit(1)}exitOnReportedFailure();const jY=globalThis.process,MY=Number(jY?.exitCode);Number.isInteger(MY)&&MY!==0&&jY.exit(MY);
1948
+ `}var BJ,VJ=__esmMin(()=>{_e(),rf(),Xn(),BJ={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:t=>t.positional(`url`,{description:`Initial URL to load (default: page:welcome)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.browse.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto,dom — WebKit/iframe need DOM globals)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-browse)`,type:`string`}).option(`devtools`,{description:`Enable the MCP devtools control plane (sets GJSIFY_DEVTOOLS=1)`,type:`boolean`,default:!1}).option(`inspector-port`,{description:`Enable WebKit's remote inspector protocol on this port + the Cdp* methods (implies --devtools)`,type:`number`}).option(`screenshot`,{description:`One-shot: load the URL, capture a WebKit screenshot to this path, and exit (CI / quick captures).`,type:`string`}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage(n),C=S.gjsify?.browse??{},N=t.appId??C.applicationId??deriveBrowserAppId(S.name),F=t.title??C.title,I=t.globals??C.globals??`auto,dom`,H=t.url,W=t.inspectorPort??C.inspectorPort,q=t.devtools||W!==void 0,Y=zn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?In(n,t.screenshot):void 0)),ge.log(`[gjsify browse] app=${N}${H?` url=${H}`:``}${q?` devtools=1`:``}${W===void 0?``:` inspector-port=${W}`}`);let{runCli:te}=await Promise.resolve().then(()=>(aX(),iX));if(await te([`build`,X,`--app`,`gjs`,`--globals`,I,`--outfile`,Z]),t.buildOnly){ge.log(`[gjsify browse] built ${Z}`);return}q&&(process.env.GJSIFY_DEVTOOLS=`1`),W!==void 0&&(process.env.WEBKIT_INSPECTOR_HTTP_SERVER=`127.0.0.1:${W}`);let{runGjsBundle:ne}=await Promise.resolve().then(()=>(LR(),IR));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function createChromeBackend(t,n={}){let S=t.CHROME_WEB_STORE_PUBLISHER_ID,C=t.CHROME_WEB_STORE_ITEM_ID,N=`publishers/${encodeURIComponent(S)}/items/${encodeURIComponent(C)}`,F=[...secretValuesOf(`chrome`,t)],I=n.fetchImpl??((...t)=>globalThis.fetch(...t)),H,scrub=t=>redactSecrets(t,F),fail=(t,n)=>new StoreApiError(`chrome`,t,scrub(n)),describe=async t=>{let n=await t.text().catch(()=>``);try{let t=JSON.parse(n),S=typeof t.error==`string`?[t.error,t.error_description].filter(Boolean).join(`: `):t.error?.message;if(S)return S.slice(0,400)}catch{}return n.trim().slice(0,200)||`empty response`},send=async(t,S)=>{n.log?.(`${S.method??`GET`} ${t} ${JSON.stringify(redactHeaders(S.headers))}`);try{return await I(t,S)}catch(t){throw fail(void 0,t instanceof Error?t.message:String(t))}},token=async()=>{if(H!==void 0)return H;let n=new URLSearchParams({client_id:t.CHROME_WEB_STORE_CLIENT_ID,client_secret:t.CHROME_WEB_STORE_CLIENT_SECRET,refresh_token:t.CHROME_WEB_STORE_REFRESH_TOKEN,grant_type:`refresh_token`}),S=await send(HJ,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:n.toString()});if(!S.ok){let t=await describe(S),n=S.status===400||S.status===401?` ${WJ}`:``;throw fail(S.status,`token exchange refused: ${t}.${n}`)}let C=await S.json().catch(()=>({}));if(typeof C.access_token!=`string`||C.access_token===``)throw fail(S.status,`token exchange answered without an access_token`);return H=C.access_token,F.push(H),H},call=async(t,n)=>{let S=await token();return send(t,{...n,headers:{...n.headers,authorization:`Bearer ${S}`}})},readStatus=async()=>{let t=await call(`${UJ}/v2/${N}:fetchStatus`,{method:`GET`});if(!t.ok)throw fail(t.status,`fetchStatus failed: ${await describe(t)}`);return await t.json().catch(()=>{throw fail(t.status,`fetchStatus answered with something that is not JSON`)})},refuseIfBusy=(t,n)=>{let S=t.submittedItemRevisionStatus,C=versionOf(S);if(S?.state===`PENDING_REVIEW`)throw C===n?new StoreVersionAlreadyThereError(`chrome`,n):new StoreInReviewError(`chrome`,`version ${C??`(unknown)`} is pending review; wait for it or cancel it in the Developer Dashboard.`);if(versionOf(t.publishedItemRevisionStatus)===n||C===n)throw new StoreVersionAlreadyThereError(`chrome`,n)},classify=t=>{switch(t){case`PENDING_REVIEW`:return`in-review`;case`PUBLISHED`:case`PUBLISHED_TO_TESTERS`:return`published`;case`REJECTED`:return`rejected`;case`STAGED`:case`CANCELLED`:return`draft`;default:return`unknown`}};return{store:`chrome`,async upload(t){refuseIfBusy(await readStatus(),t.version);let n=await call(`${UJ}/upload/v2/${N}:upload`,{method:`POST`,headers:{"content-type":`application/zip`},body:readFileSync(t.zipPath)});if(!n.ok)throw fail(n.status,`upload failed: ${await describe(n)}`);let S=await n.json().catch(()=>({}));switch(S.uploadState){case`SUCCEEDED`:return{operationId:S.name,ingested:!0,detail:`uploadState SUCCEEDED, crxVersion ${S.crxVersion??`(not reported)`}`};case`IN_PROGRESS`:return{operationId:S.name,ingested:!1,detail:`uploadState IN_PROGRESS — poll fetchStatus`};case`FAILED`:throw fail(n.status,`upload accepted but the store reports uploadState FAILED; check the package in the Developer Dashboard`);default:throw fail(n.status,`upload answered with uploadState ${S.uploadState??`(none)`}, which is not a state this client knows`)}},async publish(t){let n=(await readStatus()).submittedItemRevisionStatus;if(n?.state===`PENDING_REVIEW`)throw new StoreInReviewError(`chrome`,`version ${versionOf(n)??`(unknown)`} is pending review already.`);let S=t.deployPercentage!==void 0&&t.deployPercentage<100?{deployInfos:[{deployPercentage:t.deployPercentage}]}:{},C=await call(`${UJ}/v2/${N}:publish`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(S)});if(!C.ok){let t=await describe(C),n=C.status===400||C.status===409||C.status===412?` ${GJ}`:``;throw fail(C.status,`publish refused: ${t}.${n}`)}let F=await C.json().catch(()=>({}));return{state:classify(F.state),detail:`publish answered state ${F.state??`(none)`}`}},async status(){let t=await readStatus();if(t.takenDown===!0)return{state:`rejected`,detail:`takenDown is true — a policy violation; see the Developer Dashboard`};if(t.lastAsyncUploadState===`IN_PROGRESS`)return{state:`unknown`,ingesting:!0,detail:`lastAsyncUploadState IN_PROGRESS`};if(t.lastAsyncUploadState===`FAILED`)return{state:`rejected`,detail:`lastAsyncUploadState FAILED — the store could not ingest the package`};let n=t.submittedItemRevisionStatus;if(n?.state!==void 0)return{state:classify(n.state),version:versionOf(n),detail:`submittedItemRevisionStatus.state ${n.state}`};let S=t.publishedItemRevisionStatus;return S?.state===void 0?{state:`unknown`,detail:`fetchStatus carried no revision status and no upload state in the past 24 h`}:{state:classify(S.state),version:versionOf(S),detail:`publishedItemRevisionStatus.state ${S.state}`}}}}var HJ,UJ,WJ,GJ,versionOf,KJ=__esmMin(()=>{rf(),aY(),HJ=`https://oauth2.googleapis.com/token`,UJ=`https://chromewebstore.googleapis.com`,WJ=`Create a new OAuth client in the Google Cloud Console (APIs & Services → Credentials) and a new refresh token with the scope https://www.googleapis.com/auth/chromewebstore, e.g. in https://developers.google.com/oauthplayground ("Use your own OAuth credentials"); then update CHROME_WEB_STORE_CLIENT_ID, CHROME_WEB_STORE_CLIENT_SECRET and CHROME_WEB_STORE_REFRESH_TOKEN.`,GJ=`If the visibility was changed in the Developer Dashboard, the API refuses to publish until the item has been published by hand once with the new visibility: publish once in the Developer Dashboard by hand (einmal im Dashboard von Hand veröffentlichen), then retry.`,versionOf=t=>t?.distributionChannels?.find(t=>t.crxVersion!==void 0)?.crxVersion});function operationIdFrom(t){if(t===null)return null;let n=t.trim().split(`?`)[0].split(`/`).filter(Boolean);return n.length>0?n[n.length-1]:null}function errorLines(t){return Array.isArray(t)?t.map(t=>typeof t==`string`?t:typeof t==`object`&&t&&typeof t.message==`string`?t.message:JSON.stringify(t)):[]}var qJ,JJ,YJ,XJ,ZJ,createEdgeBackend,QJ=__esmMin(()=>{rf(),aY(),qJ=`edge`,JJ=`https://api.addons.microsoftedge.microsoft.com`,YJ=`00000000-0000-0000-0000-000000000000`,XJ=400,ZJ=`The API key was rejected. API keys expire (Microsoft announced 72 days — unverified in the API docs); renew it in Partner Center → Microsoft Edge → Publish API → "Create API credentials", then update EDGE_ADDONS_API_KEY.`,createEdgeBackend=(t,n={})=>{let S=t.EDGE_ADDONS_PRODUCT_ID,C=t.EDGE_ADDONS_CLIENT_ID,N=t.EDGE_ADDONS_API_KEY,F=[...secretValuesOf(qJ,t),C],I=`${JJ}/v1/products/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,XJ),H=null;async function send(t,S,F={}){let I={Authorization:`ApiKey ${N}`,"X-ClientID":C};F.contentType!==void 0&&(I[`Content-Type`]=F.contentType),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(I))}`);let H=n.fetchImpl??globalThis.fetch,W;try{W=await H(S,{method:t,headers:I,body:F.body})}catch(t){throw new StoreApiError(qJ,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${W.status}`),W.status>=200&&W.status<300)return W;let q=await W.text().catch(()=>``);throw new StoreApiError(qJ,W.status,failureDetail(W.status,q))}function failureDetail(t,n){let S=clean(n.trim());return t===401?S===``?ZJ:`${ZJ} Store said: ${S}`:t===404?`the product id or operation id is unknown, or the product is not yours — check EDGE_ADDONS_PRODUCT_ID.`+(S===``?``:` Store said: ${S}`):t===429?`throttled — too many requests; retry later.`:S===``?`the store gave no reason.`:S}async function accepted(t,n){let S=operationIdFrom(t.headers.get(`location`));if(S===null)throw new StoreApiError(qJ,t.status,`${n} was accepted but the response has no Location header.`);return S}async function upload(t){let n=new Uint8Array(readFileSync(t.zipPath)),S=await send(`POST`,`${I}/submissions/draft/package`,{contentType:`application/zip`,body:n}),C=await accepted(S,`the upload`);return{operationId:C,ingested:!1,detail:`HTTP ${S.status} accepted — upload operation ${C} is pending.`}}async function publish(t){let n=t.notes??``,S=JSON.stringify({notes:n}),C=await send(`POST`,`${I}/submissions`,{contentType:`application/json`,body:S}),N=await accepted(C,`the publish request`);return H={operationId:N,version:t.version},{state:`unknown`,operationId:N,detail:`HTTP ${C.status} accepted — publish operation ${N} is pending; the submission is not confirmed yet.`}}async function operation(t,n,S){let C=await send(`GET`,`${I}/${t===`upload`?`submissions/draft/package/operations`:`submissions/operations`}/${encodeURIComponent(n)}`),N=await C.text(),F;try{F=JSON.parse(N)}catch{throw new StoreApiError(qJ,C.status,`the ${t} operation answered something that is not JSON.`)}let H=clean(F.message??``);switch(F.status){case`InProgress`:return{state:`in-progress`,detail:`${t} operation ${n} is still running.`};case`Succeeded`:return{state:`succeeded`,detail:H===``?`${t} operation succeeded.`:H};case`Failed`:throw failure(F,H,S);default:throw new StoreApiError(qJ,C.status,`the ${t} operation has an unrecognised status: ${clean(String(F.status))}.`)}}function failure(t,n,S){let C=t.errorCode??``;if(C===`NoModulesUpdated`)return new StoreVersionAlreadyThereError(qJ,S??`in the draft`);if(C===`InProgressSubmission`)return new StoreInReviewError(qJ,n===``?`a submission is already in progress.`:n);let N=errorLines(t.errors).map(clean),F=[C===``?null:`${C}:`,n===``?null:n,...N].filter(t=>t!==null).join(` `);return new StoreApiError(qJ,200,F===``?`the operation failed without a reason.`:F)}async function status(){if(H===null)return{state:`unknown`,detail:`Edge Add-ons has no endpoint that reads a product; only an operation id can be read, and this run has none.`};let t=await operation(`publish`,H.operationId,H.version);return t.state===`succeeded`?{state:`in-review`,version:H.version,detail:t.detail}:{state:`unknown`,version:H.version,detail:t.detail}}async function verifyCredentials(){try{await send(`GET`,`${I}/submissions/operations/${YJ}`)}catch(t){if(t instanceof StoreApiError&&t.httpStatus===404)return;throw t}}return{store:qJ,upload,publish,status,operation,verifyCredentials}}});function asStoreId(t){return $J.includes(t)?t:null}function resolveStoreCredentials(t,n){let S=eY[t],C={},N=[];for(let t of S){let S=n[t.env];S===void 0||S===``?N.push(t):C[t.env]=S}if(N.length>0)throw new StoreCredentialsMissingError(t,N);return C}function secretValuesOf(t,n){return eY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function redactHeaders(t){let n={};for(let[S,C]of Object.entries(t)){let t=S.toLowerCase();n[t]=rY.includes(t)||/token|secret|key/.test(t)?nY:C}return n}function redactSecrets(t,n){let S=t;for(let t of[...n].filter(t=>t.length>1).sort((t,n)=>n.length-t.length))S=S.split(t).join(nY);return S}function isIdempotentSkip(t){return t instanceof StoreVersionAlreadyThereError||t instanceof StoreInReviewError}function createStoreBackend(t,n,S){let C=iY[t];if(C===void 0)throw new StoreUnsupportedError(t,t===`amo`?"use `gjsify webext sign` for AMO; this slice ships the Chrome and Edge backends only (ADR 0077 § Amendment 1)":`no backend is registered for it`);return C(resolveStoreCredentials(t,n),S)}var $J,eY,tY,nY,rY,StoreCredentialsMissingError,StoreUnsupportedError,StoreVersionAlreadyThereError,StoreInReviewError,StoreApiError,iY,aY=__esmMin(()=>{KJ(),QJ(),$J=[`chrome`,`edge`,`amo`],eY={chrome:[{env:`CHROME_WEB_STORE_PUBLISHER_ID`,secret:!1,what:`the publisher the item belongs to`},{env:`CHROME_WEB_STORE_ITEM_ID`,secret:!1,what:`the item id from the Developer Dashboard`},{env:`CHROME_WEB_STORE_CLIENT_ID`,secret:!1,what:`the OAuth client id`},{env:`CHROME_WEB_STORE_CLIENT_SECRET`,secret:!0,what:`the OAuth client secret`},{env:`CHROME_WEB_STORE_REFRESH_TOKEN`,secret:!0,what:`the refresh token the access token is minted from`}],edge:[{env:`EDGE_ADDONS_PRODUCT_ID`,secret:!1,what:`the product id from Partner Center`},{env:`EDGE_ADDONS_CLIENT_ID`,secret:!1,what:`the client id sent as X-ClientID`},{env:`EDGE_ADDONS_API_KEY`,secret:!0,what:"the API key sent as `Authorization: ApiKey …`"}],amo:[{env:`WEB_EXT_API_KEY`,secret:!1,what:"the AMO JWT issuer (`web-ext`'s own name for it)"},{env:`WEB_EXT_API_SECRET`,secret:!0,what:`the AMO JWT secret`}]},tY={chrome:{id:`chrome`,label:`Chrome Web Store`,implemented:!0,createsListings:!1},edge:{id:`edge`,label:`Edge Add-ons`,implemented:!0,createsListings:!1},amo:{id:`amo`,label:`addons.mozilla.org`,implemented:!1,createsListings:!1}},nY=`<redacted>`,rY=[`authorization`,`x-clientid`,`x-goog-api-key`,`cookie`,`set-cookie`],StoreCredentialsMissingError=class extends Error{store;missing;constructor(t,n){super(`gjsify webext submit: ${tY[t].label} needs ${n.length} environment variable(s) this run does not set:\n`+n.map(t=>` ${t.env} — ${t.what}`).join(`
1949
+ `)+`
1950
+ Set them in the environment, never in package.json (ADR 0077 § Amendment 1).`),this.store=t,this.missing=n,this.name=`StoreCredentialsMissingError`}},StoreUnsupportedError=class extends Error{store;constructor(t,n){super(`gjsify webext submit: ${tY[t].label} is not implemented — ${n}`),this.store=t,this.name=`StoreUnsupportedError`}},StoreVersionAlreadyThereError=class extends Error{store;version;constructor(t,n){super(`${tY[t].label}: version ${n} is already there — nothing to submit.`),this.store=t,this.version=n,this.name=`StoreVersionAlreadyThereError`}},StoreInReviewError=class extends Error{store;constructor(t,n){super(`${tY[t].label}: a submission is in review — ${n}`),this.store=t,this.name=`StoreInReviewError`}},StoreApiError=class extends Error{store;httpStatus;constructor(t,n,S){super(`${tY[t].label}: ${n===void 0?`request failed`:`HTTP ${n}`} — ${S}`),this.store=t,this.httpStatus=n,this.name=`StoreApiError`}},iY={chrome:createChromeBackend,edge:createEdgeBackend}});function pollBackoffFor(t){return stepFrom(cY,t)}function retryBackoffFor(t,n){return stepFrom(n?uY:lY,t)}function isRepeatableFailure(t){if(!(t instanceof StoreApiError))return!1;let n=t.httpStatus;return n===void 0||fY.includes(n)?!0:n>=500&&n<600}function isThrottled(t){return t instanceof StoreApiError&&t.httpStatus===429}function retryDecision(t,n){return isRepeatableFailure(t)?n===`publish`&&t instanceof StoreApiError&&t.httpStatus===void 0?`verify-first`:`retry`:`fatal`}async function driveSubmission(t,n={}){let{backend:S}=t,C=t.upload.version,N=n.now??(()=>Date.now()),F=n.sleep??(t=>new Promise(n=>setTimeout(n,t))),I=n.timeoutMs??6e5,H=n.secrets??[],W=N(),q=[],Y=0,X=0,Z=0,clean=t=>redactSecrets(t,H),note=t=>n.log?.(clean(`gjsify webext submit: ${t}`)),remaining=()=>I-(N()-W),endPhase=(t,n)=>{q.push({phase:t,requests:Z,elapsedMs:N()-W,detail:clean(n)}),Z=0},finish=(t,n)=>({store:S.store,version:C,verdict:t,exitCode:oY[t],detail:clean(n),phases:q,elapsedMs:N()-W,requests:Y,retries:X,retryable:sY.includes(t)}),fromError=(t,n,S)=>{let C=n instanceof Error?n.message:String(n);return endPhase(t,C),n instanceof StoreVersionAlreadyThereError?finish(`already-there`,C):n instanceof StoreInReviewError?finish(`in-review`,C):S?finish(`failed`,`${C} — repeated 3x or until the ${I} ms deadline; the failure class is repeatable, so calling again later may work.`):finish(`rejected`,C)},call=async(t,n)=>{for(let S=0;;S++){Y++,Z++;try{return{kind:`value`,value:await n()}}catch(n){if(isIdempotentSkip(n))return{kind:`error`,error:n,exhausted:!1};let C=retryDecision(n,t);if(C===`fatal`)return{kind:`error`,error:n,exhausted:!1};if(C===`verify-first`)return{kind:`lost`,error:n};let N=remaining();if(S>=3||N<=0)return{kind:`error`,error:n,exhausted:!0};let I=Math.min(retryBackoffFor(S,isThrottled(n)),N);note(`${t} failed with a repeatable error, retry ${S+1} of 3 in ${I} ms — `+(n instanceof Error?n.message:String(n))),X++,await F(I)}}},aboutOurVersion=t=>t.version===void 0||t.version===C,waitFor=async(t,n,I,H)=>{let q=S.operation;if(q===void 0&&I!==void 0&&t===`publish`)return endPhase(n,H),{kind:`end`,result:finish(`unverifiable`,`${H} The publish was accepted and the ${S.store} backend declares no operation() to read ${I} with, so whether a submission exists cannot be established from here. It may well be in review — check the dashboard; the fix is operation() on that backend.`)};for(let H=0;;H++){if(q!==void 0&&I!==void 0){let N=await call(`read`,()=>q.call(S,t,I,C));if(N.kind===`error`)return{kind:`end`,result:fromError(n,N.error,N.exhausted)};if(N.kind===`value`&&N.value.state===`succeeded`)return{kind:`done`,detail:N.value.detail};N.kind===`value`&&note(`${t} operation ${I}: ${N.value.detail}`)}else{let C=await call(`read`,()=>S.status());if(C.kind===`error`)return{kind:`end`,result:fromError(n,C.error,C.exhausted)};if(C.kind===`value`){let S=C.value;if(S.state===`rejected`)return endPhase(n,S.detail),{kind:`end`,result:finish(`rejected`,S.detail)};if(t===`upload`&&S.ingesting!==!0||t===`publish`&&aboutOurVersion(S)&&(S.state===`published`||S.state===`in-review`))return{kind:`done`,detail:S.detail};note(`status while waiting for the ${t}: ${S.detail}`)}}let Y=remaining();if(Y<=0){let S=`the ${t} was accepted and had not resolved after ${N()-W} ms`+(I===void 0?``:` (operation ${I})`)+'. Nothing is lost: call `gjsify webext submit` again — it reads the store\'s state first and will report "already there" or "in review" if this one landed meanwhile. Raise --timeout to wait longer.';return endPhase(n,S),{kind:`end`,result:finish(`unresolved`,S)}}await F(Math.min(pollBackoffFor(H),Y))}};note(`${S.store}: uploading ${C} from ${t.upload.zipPath}`);let te=await call(`upload`,()=>S.upload(t.upload));if(te.kind===`error`)return fromError(`upload`,te.error,te.exhausted);if(te.kind===`lost`)return fromError(`upload`,te.error,!1);if(endPhase(`upload`,te.value.detail),!te.value.ingested){let t=await waitFor(`upload`,`await-upload`,te.value.operationId,te.value.detail);if(t.kind===`end`)return t.result;endPhase(`await-upload`,t.detail)}if(t.publish===void 0)return finish(`uploaded`,`${C} is in the ${S.store} draft and was NOT submitted — pass --submit to ask for review.`);let ne=t.publish,re=0;for(;;){note(`${S.store}: asking for review of ${C}`);let t=await call(`publish`,()=>S.publish(ne));if(t.kind===`error`)return fromError(`publish`,t.error,t.exhausted);if(t.kind===`lost`){let n=t.error instanceof Error?t.error.message:String(t.error);note(`the publish request got no answer (${n}) — asking the store whether it arrived`);let C=await call(`read`,()=>S.status());if(C.kind!==`value`)return fromError(`publish`,C.error,C.kind===`error`&&C.exhausted);let N=C.value;if(N.state===`rejected`)return endPhase(`publish`,N.detail),finish(`rejected`,N.detail);if(aboutOurVersion(N)&&(N.state===`in-review`||N.state===`published`))return endPhase(`publish`,N.detail),finish(N.state===`published`?`published`:`submitted`,`the publish request got no answer, and the store reports it arrived: ${N.detail}`);if(N.state===`draft`&&aboutOurVersion(N)&&re<dY&&remaining()>0){re++,X++,note(`the store still holds a draft (${N.detail}) — sending the publish request once more`);continue}let F=`the publish request got no answer (${n}) and the store's own state does not say whether it arrived: ${N.detail}. The request was NOT repeated — a second one would risk a second submission. Call \`gjsify webext submit\` again once the store settles; it reads the state first.`;return endPhase(`publish`,F),finish(`unresolved`,F)}let n=t.value;if(endPhase(`publish`,n.detail),n.state===`rejected`)return finish(`rejected`,n.detail);if(n.state===`published`)return finish(`published`,n.detail);if(n.state===`in-review`)return finish(`submitted`,n.detail);let N=await waitFor(`publish`,`await-publish`,n.operationId,n.detail);return N.kind===`end`?N.result:(endPhase(`await-publish`,N.detail),finish(`submitted`,N.detail))}}var oY,sY,cY,lY,uY,dY,stepFrom,fY,pY=__esmMin(()=>{aY(),oY={uploaded:0,submitted:0,published:0,"already-there":0,"in-review":0,rejected:1,failed:1,unresolved:3,unverifiable:4},sY=[`in-review`,`failed`,`unresolved`],cY=[2e3,4e3,8e3,15e3,3e4],lY=[1e3,2e3,4e3],uY=[5e3,15e3,3e4],dY=1,stepFrom=(t,n)=>t[Math.min(Math.max(n,0),t.length-1)]??t[t.length-1]??0,fY=[408,429]});function isTagRef(t){return t!==void 0&&t.startsWith(`refs/tags/`)&&t.length>10}function defaultZipPath(t,n){let S=t.targets.find(t=>t.browser===n);if(S===void 0)throw Error(`gjsify webext submit: gjsify.webext.targets has no ${n} target, so there is no zip to derive. Add ${n}-mv3 or pass --zip.`);return zn(t.outDir,`${t.name}-${t.version}-${S.id}.zip`)}function preflightStoreJson(t,n,S){let C;try{C=JSON.parse(t)}catch{return{problems:[`${S} is not valid JSON — regenerate it with \`gjsify webext listing\`.`],manual:[]}}let N=C;if(N.version!==1||!Array.isArray(N.fields))return{problems:[`${S} is not a store.json (version 1) — regenerate it with \`gjsify webext listing\`.`],manual:[]};if(N.store!==n)return{problems:[`${S} is for store "${String(N.store)}", expected "${n}".`],manual:[]};let F=[],I=[];for(let t of N.fields){let n=t.label??t.key??`(unnamed field)`;t.status===`manual`?I.push(n):t.required===!0&&t.status===`missing`&&F.push(`required field "${n}" is missing in ${S}.`)}return{problems:F,manual:I}}function secretsOf(t,n){return eY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function describeResult(t,n){let S=[`${n} ${t.version}: ${t.verdict} — ${t.detail}`];for(let n of t.phases)S.push(` ${n.phase}: ${n.detail} (${n.requests} request(s), ${n.elapsedMs} ms)`);return t.retryable&&S.push(` Calling again later, unchanged, can make progress.`),S}async function runSubmit(t){let{env:n,project:S}=t,C=asStoreId(t.store),N=C===null?[]:secretsOf(C,n),clean=t=>redactSecrets(t,N),out=n=>t.out(clean(n)),err=n=>t.err(clean(n));try{if(C===null)throw Error(`gjsify webext submit: unknown store "${t.store}".`);let F=tY[C];if(!F.implemented)throw new StoreUnsupportedError(C,"use `gjsify webext sign` for AMO; Firefox is distributed by the project itself");if(t.submit&&!isTagRef(n.GITHUB_REF))throw Error(`gjsify webext submit: --submit asks the store for review and runs only on a tag ($GITHUB_REF must start with refs/tags/). Without --submit the zip is uploaded as a draft.`);let I;if(t.timeoutSeconds!==void 0){if(!Number.isFinite(t.timeoutSeconds)||t.timeoutSeconds<0)throw Error(`gjsify webext submit: --timeout is a number of seconds, 0 or more.`);I=t.timeoutSeconds*1e3}let H=mY[C],W=zn(In(S.root,t.listingDir??`dist/listing`),H,`store.json`);if(!existsSync(W))throw Error(`gjsify webext submit: ${W} does not exist. Run \`gjsify webext listing --store ${H}\` first; it is the preflight for the listing the dashboard will ask about.`);let q=preflightStoreJson(readFileSync(W,`utf8`),H,W);if(q.problems.length>0)throw Error(`gjsify webext submit: preflight failed, nothing was sent:\n ${q.problems.join(`
1951
+ `)}`);q.manual.length>0&&out(` by hand in the dashboard: ${q.manual.join(`, `)}`);let Y=In(t.zip??defaultZipPath(S,C));if(!t.dryRun&&!existsSync(Y))throw Error(`gjsify webext submit: ${Y} does not exist. Run \`gjsify webext zip\` first or pass --zip.`);let X=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0,Z={fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:X},te=(t.createBackend??createStoreBackend)(C,n,Z);if(t.dryRun)return te.verifyCredentials===void 0?(out(`${F.label}: dry run — credentials are set; this backend has no read-only check, so they are unverified. Nothing was uploaded.`),0):(await te.verifyCredentials(),out(`${F.label}: dry run — credentials accepted (one read). ${existsSync(Y)?`The zip exists`:`No zip at ${Y} yet`}. Nothing was uploaded.`),0);let ne=await driveSubmission({backend:te,upload:{zipPath:Y,version:S.version},publish:t.submit?{version:S.version}:void 0},{timeoutMs:I,sleep:t.sleep,now:t.now,log:X,secrets:N}),re=ne.exitCode===0?out:err;for(let t of describeResult(ne,F.label))re(t);return oY[ne.verdict]}catch(t){return err(t instanceof Error?t.message:String(t)),1}}var mY,hY=__esmMin(()=>{rf(),Xn(),aY(),pY(),mY={chrome:`cws`,edge:`edge`}});function webextIconPaths(t,n,S){let C=t.sources.get(n);if(C===void 0)throw Error(`gjsify webext: the manifest asks for icon "${n}", and \`gjsify.webext.icons.sources\` declares ${[...t.sources.keys()].map(t=>`"${t}"`).join(`, `)||`none`}.`);let N=t.svgTargets.has(S.id),F={};for(let S of t.sizes)F[String(S)]=N?`icons/${Un(C.get(S))}`:`icons/${n}-${S}.png`;return F}function svgIconFiles(t){let n=new Map;for(let[S,C]of t.sources)for(let t of C.values()){let C=`icons/${Un(t)}`,N=n.get(C);if(N!==void 0&&N!==t)throw Error(`gjsify webext: icon "${S}" uses ${t}, and ${N} has the same file name; an SVG target would receive only one of them as `+C+`. Rename one.`);n.set(C,t)}return n}async function renderWebextIcons(t,n,S=rasterizeSvg){let C=n.some(n=>!t.svgTargets.has(n.id)),N=n.some(n=>t.svgTargets.has(n.id)),F=new Map;if(C){let n=new Map;for(let[S,C]of t.sources)for(let[t,N]of C)n.set(N,[...n.get(N)??[],{size:t,name:S}]);for(let[t,C]of n){let n=await S({svg:t,sizes:[...new Set(C.map(t=>t.size))],command:`gjsify webext`});for(let{size:t,name:S}of C)F.set(`icons/${S}-${t}.png`,n.get(t))}}return{png:F,svg:N?svgIconFiles(t):new Map}}function writeWebextIcons(t,n,S,C){if(mkdirSync(zn(C,`icons`),{recursive:!0}),n.svgTargets.has(S.id))for(let[n,S]of t.svg)copyFileSync(S,zn(C,n));else for(let[n,S]of t.png)writeFileSync(zn(C,n),S)}var gY=__esmMin(()=>{rf(),Xn(),bH()});function isRecord$1(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function mergeManifest(t,n){let S={...t};for(let[t,C]of Object.entries(n))C===null?delete S[t]:isRecord$1(C)&&isRecord$1(S[t])?S[t]=mergeManifest(S[t],C):S[t]=C;return S}function applyTargetOverrides(t,n){let{$targets:S,...C}=t;if(S===void 0)return C;if(!isRecord$1(S))throw Error("gjsify webext: the manifest's `$targets` must be an object.");let N=S[n];if(N===void 0)return C;if(!isRecord$1(N))throw Error(`gjsify webext: \`$targets["${n}"]\` in the manifest must be an object.`);return mergeManifest(C,N)}async function composeManifest(t,n){let S=typeof t==`function`?await t(n):applyTargetOverrides(t,n.target);if(!isRecord$1(S))throw Error(`gjsify webext: the manifest for ${n.target} is not an object (got ${typeof S}).`);if(S.version!==void 0)return S;let C={};for(let[t,N]of Object.entries(S))C[t]=N,t===`name`&&(C.version=n.version);return C.version===void 0&&(C.version=n.version),C}async function loadManifestTemplate(t){if(/\.json$/i.test(t))try{return JSON.parse(readFileSync(t,`utf8`))}catch(n){throw Error(`gjsify webext: ${t} is not valid JSON: ${n.message}`)}let n,cleanup=null;if(isGjs()){let{BuildAction:S}=await Promise.resolve().then(()=>(uR(),sR)),C=await S.bundleFileForGjsCached(t,{cacheSubdir:`webext`,label:Un(t),cache:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(t).href)}}),N=zn(Hn(C),`manifest-${process.pid}-${++_Y}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++_Y}`;try{let S=(await import(n)).default;if(typeof S!=`function`&&!isRecord$1(S))throw Error(`gjsify webext: ${t} has no default export. Export the manifest object, or a function \`(ctx) => manifest\` that receives the target.`);return S}finally{cleanup?.()}}function addPath(t,n){typeof n!=`string`||n===``||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.includes(`*`)||t.add(n.replace(/^\//,``).replace(/[?#].*$/,``))}function addIconValue(t,n){if(typeof n==`string`)addPath(t,n);else if(isRecord$1(n))for(let S of Object.values(n))addPath(t,S)}function manifestFileReferences(t){let n=new Set,S=t.background;if(isRecord$1(S)&&(addPath(n,S.service_worker),addPath(n,S.page),Array.isArray(S.scripts)))for(let t of S.scripts)addPath(n,t);if(Array.isArray(t.content_scripts)){for(let S of t.content_scripts)if(isRecord$1(S)){for(let t of[`js`,`css`])if(Array.isArray(S[t]))for(let C of S[t])addPath(n,C)}}for(let S of[`action`,`browser_action`,`page_action`,`sidebar_action`]){let C=t[S];isRecord$1(C)&&(addPath(n,C.default_popup),addPath(n,C.default_panel),addIconValue(n,C.default_icon))}if(isRecord$1(t.options_ui)&&addPath(n,t.options_ui.page),addPath(n,t.options_page),addPath(n,t.devtools_page),isRecord$1(t.side_panel)&&addPath(n,t.side_panel.default_path),addIconValue(n,t.icons),isRecord$1(t.chrome_url_overrides))for(let S of Object.values(t.chrome_url_overrides))addPath(n,S);if(Array.isArray(t.web_accessible_resources)){for(let S of t.web_accessible_resources)if(typeof S==`string`)addPath(n,S);else if(isRecord$1(S)&&Array.isArray(S.resources))for(let t of S.resources)addPath(n,t)}return[...n].sort()}function checkManifest(t,n,S){let C=[];t.manifest_version!==n.manifestVersion&&C.push(`manifest_version is ${JSON.stringify(t.manifest_version)}, and target ${n.id} is Manifest V${n.manifestVersion}. gjsify does not convert keys between versions — branch on \`ctx.manifestVersion\` in the manifest.`);for(let N of manifestFileReferences(t))existsSync(zn(S,N))||C.push(`the manifest names "${N}", which the build did not write into ${n.id}/.`);let N=existsSync(zn(S,`_locales`)),F=t.default_locale;return N&&typeof F!=`string`?C.push(`_locales/ exists but the manifest sets no default_locale; the browser refuses to load it.`):!N&&F!==void 0?C.push(`the manifest sets default_locale "${String(F)}" but there is no _locales/ directory.`):typeof F==`string`&&!existsSync(zn(S,`_locales`,F,`messages.json`))&&C.push(`default_locale is "${F}" but _locales/${F}/messages.json does not exist.`),C}var _Y,vY=__esmMin(()=>{rf(),Xn(),cr(),N_(),__name$1(isRecord$1,`isRecord`),_Y=0});function planPage(t,n,S){let C=Hn(n),N=[],F=[],local=t=>{if(TY.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return Rn(n)?n:In(C,n)},I=S.replace(yY,n=>{let S=xY.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!EY.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:CY.test(n)?`esm`:`iife`,output:F}),n.replace(xY,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(bY,t=>{if(!wY.test(t))return t;let n=SY.exec(t);if(!n)return t;let S=local(n[2]);if(S===null)return t;let C=Un(S);return F.push({source:S,output:C}),t.replace(SY,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var yY,bY,xY,SY,CY,wY,TY,EY,DY=__esmMin(()=>{Xn(),yY=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,bY=/<link\b[^>]*>/gi,xY=/\bsrc\s*=\s*(["'])([^"']+)\1/i,SY=/\bhref\s*=\s*(["'])([^"']+)\1/i,CY=/\btype\s*=\s*["']module["']/i,wY=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,TY=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,EY=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=OY?n:OY}function zipEntriesOf(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0})){let N=zn(S,C.name);C.isDirectory()?walk(N):n.push({path:Bn(t,N).split(/[\\/]/).join(`/`),mode:420,data:readFileSync(N)})}};return walk(t),n}async function buildWebext(t){let{config:n,targets:S,outDir:C,define:N}=t,F=t.log??(t=>ge.log(t)),I=t.mode===`production`&&n.minify,H=zn(C,`.stage`);rmSync(H,{recursive:!0,force:!0}),mkdirSync(H,{recursive:!0});try{for(let[S,C]of n.scripts)await t.bundle({entry:C,outfile:zn(H,`${S}.js`),format:`iife`,define:N,minify:I});let W=new Map;for(let[S,C]of n.pages){let n=planPage(S,C,readFileSync(C,`utf8`));for(let S of n.scripts)await t.bundle({entry:S.entry,outfile:zn(H,S.output),format:S.format,define:N,minify:I});for(let t of n.stylesheets){let n=W.get(t.output);if(n!==void 0&&n!==t.source)throw Error(`gjsify webext: pages link ${n} and ${t.source}, which would both be written as ${t.output}. Rename one.`);W.set(t.output,t.source),cpSync(t.source,zn(H,t.output))}writeFileSync(zn(H,`${S}.html`),n.html)}let q=n.icons,Y=q?await renderWebextIcons(q,S,t.rasterize):null,X=await loadManifestTemplate(n.manifest),Z={folders:new Map,zips:new Map};for(let I of S){let S=zn(C,I.id);t.inPlace||rmSync(S,{recursive:!0,force:!0}),mkdirSync(S,{recursive:!0}),n.publicDir&&cpSync(n.publicDir,S,{recursive:!0}),n.localesDir&&cpSync(n.localesDir,zn(S,`_locales`),{recursive:!0}),cpSync(H,S,{recursive:!0}),q&&Y&&writeWebextIcons(Y,q,I,S);let W=await composeManifest(X,{target:I.id,browser:I.browser,manifestVersion:I.manifestVersion,mode:t.mode,version:n.version,define:N,icons:t=>{if(!q)throw Error(`gjsify webext: the manifest asks for icon "${t}" and \`gjsify.webext.icons\` is not declared.`);return webextIconPaths(q,t,I)}});writeFileSync(zn(S,`manifest.json`),`${JSON.stringify(W,null,2)}\n`);let te=checkManifest(W,I,S);if(te.length>0)throw Error(`gjsify webext: ${I.id} would not load:\n - ${te.join(`
1952
+ - `)}`);if(Z.folders.set(I.id,S),F(`built ${Bn(process.cwd(),S)||S}`),t.zip){let t=zn(C,`${n.name}-${n.version}-${I.id}.zip`);writeFileSync(t,buildZip(zipEntriesOf(S),zipTimestamp())),Z.zips.set(I.id,t),F(`zipped ${Bn(process.cwd(),t)||t} (${Math.round(statSync(t).size/1024)} KiB)`)}}return Z}finally{rmSync(H,{recursive:!0,force:!0})}}var OY,kY=__esmMin(()=>{_e(),rf(),Xn(),WW(),gY(),vY(),DY(),OY=315532800});function parseWebextTarget(t){let n=/^([a-z]+)-mv([23])$/.exec(t),S=n?.[1];if(!n||S===void 0||!AY.includes(S))throw Error(`gjsify webext: unknown target "${t}". A target is <browser>-mv<2|3> with browser one of ${AY.join(`, `)} (e.g. chrome-mv3, firefox-mv2).`);let C=n[2]===`2`?2:3,N=C===2?MY.get(S):void 0;if(N!==void 0)throw Error(`gjsify webext: target "${t}" does not exist any more: ${N}. Use ${S}-mv3.`);return{id:t,browser:S,manifestVersion:C}}function webExtRunTarget(t){return t.browser===`firefox`?`firefox-desktop`:t.browser===`chrome`||t.browser===`edge`||t.browser===`opera`?`chromium`:null}var AY,jY,MY,NY=__esmMin(()=>{AY=[`chrome`,`edge`,`firefox`,`opera`,`safari`],jY=[`chrome-mv3`,`firefox-mv3`],MY=new Map([[`chrome`,`chrome has removed Manifest V2`],[`edge`,`edge has removed Manifest V2`],[`opera`,`opera's extension store accepts Manifest V3 only`]])});function isRecord(t){return typeof t==`object`&&!!t&&!Array.isArray(t)}function defaultArtifactName(t){let n=(t??`extension`).replace(/^@[^/]+\//,``);return n===``?`extension`:n}function iconSourceForSize(t,n){if(typeof t==`string`)return t;let S=Object.keys(t).filter(t=>/^\d+$/.test(t)).map(Number).sort((t,n)=>t-n).find(t=>n<=t);return S===void 0?t.default:t[String(S)]}function resolveWebextConfig(t,n,S=defaultExists){let C=[],N=t.gjsify?.webext;if(N===void 0)throw Error("gjsify webext: this package declares no `gjsify.webext` block in package.json. Add one naming at least the manifest and one script or page — see `gjsify webext build --help`.");if(!isRecord(N))throw Error("gjsify webext: `gjsify.webext` must be an object.");let F=N,abs=t=>Rn(t)?t:In(n,t),need=(t,n,N)=>{let F=abs(n);return S(F,N)||C.push(`${t} "${n}" is not a ${N===`dir`?`directory`:`file`}.`),F},I=[],H=F.targets??[...jY];if(!Array.isArray(H)||H.length===0)C.push("`targets` must be a non-empty array of target names.");else for(let t of H)try{I.some(n=>n.id===t)?C.push(`target "${t}" is listed twice.`):I.push(parseWebextTarget(String(t)))}catch(t){C.push(t.message.replace(/^gjsify webext: /,``))}let W=``;if(F.manifest!==void 0)W=need("`manifest`",F.manifest,`file`);else{let t=FY.find(t=>S(zn(n,t),`file`));t===void 0?C.push(`no \`manifest\` declared and none of ${FY.join(`, `)} exists.`):W=zn(n,t)}let q=new Map,claim=(t,n)=>{let S=q.get(t);S===void 0?q.set(t,n):C.push(`${n} and ${S} both write ${t}.`)},readEntries=t=>{let n=new Map,S=F[t];if(S===void 0)return n;if(!isRecord(S))return C.push(`\`${t}\` must map an output name to a source file.`),n;for(let[N,F]of Object.entries(S)){if(!IY.test(N)){C.push(`\`${t}.${N}\`: an output name is a plain file name (letters, digits, . _ -).`);continue}if(typeof F!=`string`){C.push(`\`${t}.${N}\` must be a path.`);continue}n.set(N,need(`\`${t}.${N}\``,F,`file`)),t===`scripts`?claim(`${N}.js`,`\`scripts.${N}\``):claim(`${N}.html`,`\`pages.${N}\``)}return n},Y=readEntries(`scripts`),X=readEntries(`pages`);Y.size===0&&X.size===0&&C.push("declare at least one entry under `scripts` or `pages`; there is nothing to build.");for(let t of X.keys())Y.has(t)&&C.push(`\`scripts.${t}\` and the script of \`pages.${t}\` both write ${t}.js.`);let Z=null;if(F.icons!==void 0)if(!isRecord(F.icons)||!isRecord(F.icons.sources))C.push("`icons` must be an object with a `sources` map (icon name → SVG).");else{let t=F.icons.sizes??PY;(!Array.isArray(t)||t.length===0||t.some(t=>!Number.isInteger(t)||t<=0))&&C.push("`icons.sizes` must be a non-empty list of positive integers.");let n=new Set(F.icons.svg??[]);for(let t of n)I.some(n=>n.id===t)||C.push(`\`icons.svg\` names "${t}", which is not one of this package's targets.`);let N=new Map;for(let[n,I]of Object.entries(F.icons.sources)){if(!IY.test(n)){C.push(`\`icons.sources.${n}\`: an icon name is a plain file name.`);continue}if(typeof I!=`string`&&!isRecord(I)){C.push(`\`icons.sources.${n}\` must be an SVG path or a map of size ceilings to SVGs.`);continue}let F=new Map;for(let S of t){let t=iconSourceForSize(I,S);if(t===void 0){C.push(`\`icons.sources.${n}\` has no SVG for ${S} px — add a "default".`);continue}/\.svg$/i.test(t)||C.push(`\`icons.sources.${n}\`: "${t}" is not an .svg file.`),F.set(S,abs(t))}for(let t of new Set(F.values()))S(t,`file`)||C.push(`\`icons.sources.${n}\`: "${t}" does not exist.`);N.set(n,F)}Z={sizes:t,sources:N,svgTargets:n}}let optionalDir=(t,C)=>{let N=F[t];if(N!==void 0)return need(`\`${t}\``,N,`dir`);let I=zn(n,C);return S(I,`dir`)?I:null},te=optionalDir(`public`,`public`),ne=optionalDir(`locales`,`_locales`),re=F.define??{};(!isRecord(re)||Object.values(re).some(t=>typeof t!=`string`))&&C.push("`define` must map identifiers to JS expressions given as strings.");let ie=F.watch??[];if((!Array.isArray(ie)||ie.some(t=>typeof t!=`string`))&&C.push("`watch` must be a list of directories."),C.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${zn(n,`package.json`)}:\n - ${C.join(`
1953
+ - `)}`);return{root:n,name:F.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,manifest:W,scripts:Y,pages:X,icons:Z,publicDir:te,localesDir:ne,outDir:abs(F.outDir??`.output`),define:re,watch:ie.map(abs),minify:F.minify??!0}}function defaultExists(t,n){if(!existsSync(t))return!1;let S=statSync(t);return n===`dir`?S.isDirectory():S.isFile()}function selectTargets(t,n){return n===void 0||n.length===0?t.targets:n.map(n=>{let S=t.targets.find(t=>t.id===n);if(S)return S;throw parseWebextTarget(n),Error(`gjsify webext: target "${n}" is not in \`gjsify.webext.targets\` (${t.targets.map(t=>t.id).join(`, `)}).`)})}var PY,FY,IY,LY=__esmMin(()=>{rf(),Xn(),NY(),PY=[16,32,48,128],FY=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],IY=/^[A-Za-z0-9][A-Za-z0-9._-]*$/});function webExtRunArgs(t){let n=webExtRunTarget(t.target);if(n===null)throw Error(`gjsify webext dev: web-ext cannot launch ${t.target.browser}. Build with \`gjsify webext build --target ${t.target.id}\` and load the folder by hand, or pass \`--no-launch\`.`);let S=[`run`,`--source-dir`,t.sourceDir,`--target`,n,`--no-input`,`--profile-create-if-missing`];return n===`firefox-desktop`?(S.push(`--firefox-profile`,t.profile,`--keep-profile-changes`),t.browserBinary&&S.push(`--firefox`,t.browserBinary),t.headless&&S.push(`--arg=-headless`)):(S.push(`--chromium-profile`,t.profile),t.browserBinary&&S.push(`--chromium-binary`,t.browserBinary),t.headless&&S.push(`--arg=--headless=new`)),S}function defaultDevProfile(t,n,S=process.env){return zn(S.XDG_CACHE_HOME||zn(homedir(),`.cache`),`gjsify`,`webext`,t,n.id)}function resolveWebExt(t,n=process.platform,S=process.env){let C=n===`win32`?`web-ext.cmd`:`web-ext`;for(let n=t;;n=Hn(n)){let t=zn(n,`node_modules`,`.bin`);if(existsSync(zn(t,C)))return{cmd:`web-ext`,env:{...S,PATH:[t,S.PATH].filter(Boolean).join(Jn)}};if(Hn(n)===n)break}return isOnPath(`web-ext`)?{cmd:`web-ext`,env:S}:null}var RY,zY=__esmMin(()=>{rf(),a_(),Xn(),sL(),NY(),RY="gjsify webext dev: `web-ext` is not installed. Add it to the project (`gjsify install --save-dev web-ext`) or install it globally, or pass `--no-launch` to rebuild without a browser."});function loadConfig(t){let n=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveWebextConfig(JSON.parse(readFileSync(n,`utf8`)),t)}function effectiveDefines(t,n){let S={...t.define};for(let t of n){let n=t.indexOf(`=`);if(n<=0)throw Error(`gjsify webext: --define "${t}" is not KEY=VALUE.`);S[t.slice(0,n)]=t.slice(n+1)}return S}async function bundleInProcess(t){let{runCli:n}=await Promise.resolve().then(()=>(aX(),iX)),S=[`build`,t.entry,`--app`,`browser`,`--format`,t.format,`--outfile`,t.outfile];for(let[n,C]of Object.entries(t.define))S.push(`--define`,`${n}=${C}`);t.minify||S.push(`--no-minify`),await n(S)}async function runBuild(t,n){let S=process.cwd(),C=loadConfig(S),N=t.mode===`development`?`development`:`production`;await buildWebext({config:C,targets:selectTargets(C,t.target),outDir:t.outDir?In(S,t.outDir):C.outDir,mode:N,define:effectiveDefines(C,t.define),inPlace:!1,zip:n,bundle:bundleInProcess})}function devTarget(t,n){if(n&&n.length>1)throw Error(`gjsify webext dev: pass one --target.`);let[S]=selectTargets(t,n);return n&&n.length===1?S:t.targets.find(t=>t.browser===`firefox`)??S}function devWatchTargets(t,n){let skip=t=>t===`node_modules`||t.startsWith(`.`),S=[{path:t.root,recursive:!1}];for(let C of readdirSync(t.root,{withFileTypes:!0})){let N=zn(t.root,C.name);!C.isDirectory()||skip(C.name)||N===n||n.startsWith(N+qn)||S.push({path:N,recursive:!0})}for(let n of t.watch)S.push({path:n,recursive:!0});return S}var BY,VY,HY,UY,WY,GY,KY,qY,JY=__esmMin(()=>{_e(),rf(),Xn(),AJ(),hY(),kY(),LY(),zY(),BY={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},VY={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},HY={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},UY={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,BY).option(`out-dir`,VY).option(`define`,HY).option(`mode`,{description:`Passed to the manifest as ctx.mode; development also skips minification.`,type:`string`,choices:[`production`,`development`],default:`production`}),handler:t=>runBuild(t,!1)},WY={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,BY).option(`out-dir`,VY).option(`define`,HY),handler:t=>runBuild(t,!0)},GY={command:`dev`,description:`Build one target in development mode, launch it in a browser via web-ext, and rebuild in place on change.`,builder:t=>t.option(`target`,{...BY,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,HY).option(`launch`,{description:`Start a browser with the extension (--no-launch only rebuilds).`,type:`boolean`,default:!0}).option(`browser-binary`,{description:`Browser executable web-ext should start.`,type:`string`}).option(`profile`,{description:`Browser profile directory (default: $XDG_CACHE_HOME/gjsify/webext/<name>/<target>).`,type:`string`}).option(`headless`,{description:`Start the browser without a window.`,type:`boolean`,default:!1}).option(`debounce`,{description:`Quiet window in ms before a rebuild.`,type:`number`,default:200}),handler:async t=>{let n=process.cwd(),S=loadConfig(n),C=devTarget(S,t.target),N=t.outDir?In(n,t.outDir):`${S.outDir}-dev`,F=effectiveDefines(S,t.define),I=zn(N,C.id),H=null;if(t.launch&&(H=resolveWebExt(n),H===null))throw Error(RY);let W=null,stopBrowser=()=>{W?.kill()};process.on(`SIGINT`,stopBrowser),process.on(`SIGTERM`,stopBrowser);let launch=async()=>{if(H===null||W!==null)return;let N=t.profile?In(n,t.profile):defaultDevProfile(S.name,C);mkdirSync(Hn(N),{recursive:!0});let F=webExtRunArgs({sourceDir:I,target:C,profile:N,browserBinary:t.browserBinary,headless:t.headless});ge.log(`[webext] launching ${C.id} with profile ${N}`);let{spawnSupervised:q}=await Promise.resolve().then(()=>(DJ(),EJ));W=await q(H.cmd,F,H.env),W.on(`exit`,t=>{ge.log(`[webext] browser closed (${t??0}) — stopping`),process.exit(0)})},{runWatchLoop:q}=await Promise.resolve().then(()=>(DJ(),EJ));await q({dir:n,dirLabel:`.`,label:`webext`,watch:devWatchTargets(S,N),ignore:t=>t===N||t.startsWith(N+qn),build:async()=>{await buildWebext({config:S,targets:[C],outDir:N,mode:`development`,define:F,inPlace:!0,zip:!1,bundle:bundleInProcess}),await launch()},spawnChild:null,debounceMs:t.debounce})}},KY={command:`listing`,description:`Derive the store listings (Chrome Web Store, Edge Add-ons, Firefox AMO) from the AppStream metainfo, the gettext catalogues and the screenshots: texts, permission justifications and exact-size images.`,builder:t=>t.option(`store`,{description:`Which store to write (default: all).`,type:`string`,choices:[`cws`,`edge`,`amo`,`all`],default:`all`}).option(`stores`,{description:`Several stores at once, comma separated (cws,edge,amo) or all; wins over --store.`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: dist/listing).`,type:`string`}).option(`check`,{description:`Validate against the store limits; write nothing.`,type:`boolean`,default:!1}).option(`metainfo`,{description:`AppStream metainfo (default: gjsify.webext.listing.metainfo, else gjsify.site.metainfo).`,type:`string`}).option(`config`,{description:`JSON file that overrides the gjsify.webext.listing block of package.json.`,type:`string`}).option(`pot`,{description:`Also write the config strings as a gettext template.`,type:`string`}).option(`root`,{description:`Project root (default: the working directory).`,type:`string`}).option(`offline`,{description:`Skip downloading screenshots hosted elsewhere.`,type:`boolean`,default:!1}).option(`runtime`,{description:`Runtime to run on: gjs | node | bun | deno (default: the host runtime).`,type:`string`,choices:[`gjs`,`node`,`bun`,`deno`]}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto).",type:`string`}),handler:async t=>{let n=process.cwd(),S=[`listing`,`--store`,t.stores??t.store];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.check&&S.push(`--check`),t.metainfo&&S.push(`--metainfo`,t.metainfo),t.config&&S.push(`--config`,In(n,t.config)),t.pot&&S.push(`--pot`,In(n,t.pot)),t.offline&&S.push(`--offline`),await dispatchSite({invokedAs:`gjsify webext listing`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:!1})}},qY={command:`submit`,description:`Upload the built zip to the Chrome Web Store or Edge Add-ons as a draft; --submit also asks for review (tags only).`,builder:t=>t.option(`store`,{description:`Which store (amo is not implemented: Firefox is distributed by the project itself).`,type:`string`,choices:[`chrome`,`edge`,`amo`],demandOption:!0}).option(`zip`,{description:"The zip to upload (default: what `webext zip` writes for the store's target).",type:`string`}).option(`dry-run`,{description:`Check the credentials with one read call; upload nothing.`,type:`boolean`,default:!1}).option(`submit`,{description:`Ask for review after the upload. Refused unless $GITHUB_REF is a tag.`,type:`boolean`,default:!1}).option(`timeout`,{description:`Seconds to wait for the store to resolve an upload or submission (default: 600).`,type:`number`}).option(`listing-dir`,{description:"Where `webext listing` wrote store.json (default: dist/listing).",type:`string`}).epilog(`Credentials come from the environment only (see ADR 0077 § Amendment 1). Exit codes: 0 done or nothing to do, 1 rejected or failed, 3 accepted but unresolved (run again), 4 unverifiable. A submission stuck in review is cancelled in the Chrome dashboard (:cancelSubmission); this command never does.`),handler:async t=>{let n=process.cwd(),S=await runSubmit({store:t.store,zip:t.zip?In(n,t.zip):void 0,dryRun:t.dryRun,submit:t.submit,timeoutSeconds:t.timeout,listingDir:t.listingDir,project:loadConfig(n),env:process.env,out:t=>ge.log(t),err:t=>ge.error(t)});S!==0&&(process.exitCode=S)}}}),YY,XY=__esmMin(()=>{JY(),YY={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(UY.command,UY.description,UY.builder,UY.handler).command(WY.command,WY.description,WY.builder,WY.handler).command(GY.command,GY.description,GY.builder,GY.handler).command(KY.command,KY.description,KY.builder,KY.handler).command(qY.command,qY.description,qY.builder,qY.handler).demandCommand(1).strict()}});function blueprintsUnder(t,n){let S;try{S=statSync(t)}catch{return n}if(!S.isDirectory())return t.endsWith(`.blp`)&&n.push(t),n;for(let S of readdirSync(t).sort())ZY.has(S)||S.startsWith(`.`)||blueprintsUnder(zn(t,S),n);return n}var ZY,QY,formatFor,$Y,eX=__esmMin(()=>{_e(),rf(),Xn(),_A(),wA(),ZY=new Set([`node_modules`,`dist`,`lib`,`.git`]),QY=new Map,formatFor=t=>{let n=QY.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return QY.set(t,S),S},$Y={command:`types [paths..]`,description:"Generate the `<name>.d.blp.ts` type sidecar for each .blp (ADR 0088), so `import { build }` / `import { GTypeName }` type-check before anything is built. Defaults to the current directory.",builder:t=>t.positional(`paths`,{description:`Files or directories to scan for .blp (default: the current directory)`,type:`string`,array:!0,normalize:!0,default:[]}).option(`check`,{description:`Write nothing; exit non-zero when a sidecar is missing or stale`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print every file considered, not only the ones that changed`,type:`boolean`,default:!1}),handler:async t=>{let n=t.paths??[],S=(n.length>0?n:[`.`]).map(t=>Rn(t)?t:In(process.cwd(),t)),C=[];for(let t of S)blueprintsUnder(t,C);let N=[],F=0;for(let n of C){let S=sidecarPathFor(n),C=emitTypedSidecar(parseBlueprint(readFileSync(n,`utf8`),n),Un(n),formatFor(Hn(n))),I;try{I=readFileSync(S,`utf8`)}catch{I=void 0}if(I===C){t.verbose&&ge.log(`[gjsify blueprint types] current: ${S}`);continue}if(t.check){N.push(S);continue}writeFileSync(S,C,`utf8`),F+=1,ge.log(`[gjsify blueprint types] wrote ${S}`)}if(t.check){if(N.length===0){ge.log(`[gjsify blueprint types] ${C.length} .blp checked, every sidecar current.`);return}for(let t of N)ge.error(`[gjsify blueprint types] missing or stale: ${t}`);ge.error(`[gjsify blueprint types] run without --check to regenerate.`),process.exitCode=1;return}ge.log(`[gjsify blueprint types] ${C.length} .blp scanned, ${F} sidecar(s) written, ${C.length-F} already current.`)}}}),tX,nX=__esmMin(()=>{eX(),tX={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command($Y.command,$Y.description,$Y.builder,$Y.handler).demandCommand(1).strict()}}),rX=__esmMin(()=>{hR(),_R(),bR(),wR(),VR(),WR(),$z(),tB(),rB(),pB(),EB(),GB(),JB(),QB(),tV(),QV(),CG(),AG(),SB(),IG(),zG(),GG(),dB(),XG(),MK(),LK(),GK(),rq(),aq(),cq(),uq(),gq(),Sq(),Aq(),Nq(),Fq(),Lq(),Kq(),Jq(),Xq(),rJ(),cJ(),uJ(),TJ(),kJ(),MJ(),FJ(),LJ(),zJ(),VJ(),XY(),nX()}),iX=__exportAll$5({runCli:()=>runCli});function runtimeLabel(){let t=gjsSystemVersion();if(t!==void 0){let n=Number(t);return`GJS ${Math.floor(n/1e4)}.${Math.floor(n%1e4/100)}.${n%100} (SpiderMonkey)`}return isBun()?`Bun ${globalThis.Bun?.version??process.versions.bun??``}`.trim():isDeno()?`Deno ${globalThis.Deno?.version?.deno??``}`.trim():isNode()?`Node.js ${process.version}`:`unknown runtime`}async function runCli(t){ensureGjsifyShimOnPath();let n=sh(t);await n.scriptName(Ch).version(cliVersion()).strict().fail((t,S)=>{let C=classifyCliFailure(t,S);if(C.kind===`usage`)throw n.showHelp(`error`),Error(C.message,{cause:S})}).wrap(n.terminalWidth()).command(WB.command,WB.description,WB.builder,WB.handler).command(PG.command,PG.description,PG.builder,PG.handler).command(LG.command,LG.description,LG.builder,LG.handler).command(RG.command,RG.description,RG.builder,RG.handler).command(mR.command,mR.description,mR.builder,mR.handler).command(gR.command,gR.description,gR.builder,gR.handler).command(yR.command,yR.description,yR.builder,yR.handler).command(CR.command,CR.description,CR.builder,CR.handler).command(BR.command,BR.description,BR.builder,BR.handler).command(UR.command,UR.description,UR.builder,UR.handler).command(Qz.command,Qz.description,Qz.builder,Qz.handler).command(xB.command,xB.description,xB.builder,xB.handler).command(eB.command,eB.description,eB.builder,eB.handler).command(nB.command,nB.description,nB.builder,nB.handler).command(fB.command,fB.description,fB.builder,fB.handler).command(TB.command,TB.description,TB.builder,TB.handler).command(qB.command,qB.description,qB.builder,qB.handler).command(ZB.command,ZB.description,ZB.builder,ZB.handler).command(eV.command,eV.description,eV.builder,eV.handler).command(ZV.command,ZV.description,ZV.builder,ZV.handler).command(xG.command,xG.description,xG.builder,xG.handler).command(kG.command,kG.description,kG.builder,kG.handler).command(WG.command,WG.description,WG.builder,WG.handler).command(uB.command,uB.description,uB.builder,uB.handler).command(qG.command,qG.description,qG.builder,qG.handler).command(jK.command,jK.description,jK.builder,jK.handler).command(iq.command,iq.description,iq.builder,iq.handler).command(IK.command,IK.description,IK.builder,IK.handler).command(WK.command,WK.description,WK.builder,WK.handler).command(nq.command,nq.description,nq.builder,nq.handler).command(sq.command,sq.description,sq.builder,sq.handler).command(lq.command,lq.description,lq.builder,lq.handler).command(hq.command,hq.description,hq.builder,hq.handler).command(xq.command,xq.description,xq.builder,xq.handler).command(Oq.command,Oq.description,Oq.builder,Oq.handler).command(Mq.command,Mq.description,Mq.builder,Mq.handler).command(Iq.command,Iq.description,Iq.builder,Iq.handler).command(Pq.command,Pq.description,Pq.builder,Pq.handler).command($q.command,$q.description,$q.builder,$q.handler).command(Gq.command,Gq.description,Gq.builder,Gq.handler).command(qq.command,qq.description,qq.builder,qq.handler).command(Yq.command,Yq.description,Yq.builder,Yq.handler).command(sJ.command,sJ.description,sJ.builder,sJ.handler).command(lJ.command,lJ.description,lJ.builder,lJ.handler).command(CJ.command,CJ.description,CJ.builder,CJ.handler).command(OJ.command,OJ.description,OJ.builder,OJ.handler).command(jJ.command,jJ.description,jJ.builder,jJ.handler).command(PJ.command,PJ.description,PJ.builder,PJ.handler).command(IJ.command,IJ.description,IJ.builder,IJ.handler).command(RJ.command,RJ.description,RJ.builder,RJ.handler).command(BJ.command,BJ.description,BJ.builder,BJ.handler).command(YY.command,YY.description,YY.builder,YY.handler).command(tX.command,tX.description,tX.builder,tX.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var aX=__esmMin(()=>{ch(),lh(),Sh(),rX(),wh(),N_(),Yz()});aX(),N_(),Zz();function pendingFailureCode(t,n){if(n||t==null)return null;let S=Number(t);return Number.isFinite(S)&&S!==0?S:null}function exitOnReportedFailure(){let t=pendingFailureCode(process.exitCode,isDaemonCommand());t!==null&&gjsExit(t)}_e(),N_();try{await runCli(hideBin(process.argv))}catch(t){let n=typeof t==`object`&&t&&typeof t.code==`string`?t.code:``,S=t instanceof Error?t.message:String(t);ge.error(n&&!S.includes(n)?`${n}: ${S}`:S),process.env.GJSIFY_DEBUG&&t instanceof Error&&t.stack&&ge.error(t.stack),process.exitCode=1,gjsExit(1)}exitOnReportedFailure();const oX=globalThis.process,sX=Number(oX?.exitCode);Number.isInteger(sX)&&sX!==0&&oX.exit(sX);