@gjsify/cli 0.64.45 → 0.64.46

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.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(`
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.46`,"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.46`),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=`
@@ -973,9 +973,9 @@ No install command available for your package manager. Install manually.`),proce
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
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
- `),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(`
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 scalableAppIconCleanup(t){return`/share/icons/hicolor/scalable/apps/${t}.svg`}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`?[scalableAppIconCleanup(t.appId)]:[]])]},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=__esmMin(()=>{oV(),sV=`1.0.0`,cV=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return uV}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,...(t.desktopExecArgs??[]).map(n=>quoteExecArg(n,t.configKey))].join(` `)+execFieldCode(N),APP_ID:t.appId,CATEGORIES_LINE:S,KEYWORDS_LINE:C,MIMETYPES_LINE:F})}function quoteExecArg(t,n){if(/[\r\n]/.test(t))throw Error(`${n}.desktopExecArgs contains ${JSON.stringify(t)}: a newline cannot appear in a desktop entry's Exec= line.`);let S=t.replace(/%/g,`%%`);return S===``?`""`:dV.test(S)?`"${S.replace(/(["`$\\])/g,`\\$1`).replace(/\\/g,`\\\\`)}"`:S}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
- `}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]
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 uV,dV,fV=__esmMin(()=>{Oh(),uV=`[Desktop Entry]
979
979
  Name={{NAME}}
980
980
  Comment={{SUMMARY}}
981
981
  Exec={{COMMAND}}
@@ -985,11 +985,11 @@ Type=Application
985
985
  Categories={{CATEGORIES_LINE}}
986
986
  {{KEYWORDS_LINE}}{{MIMETYPES_LINE}}StartupNotify=true
987
987
  StartupWMClass={{APP_ID}}
988
- `,__name$1(renderMetainfoApp$1,`renderMetainfoApp`),__name$1(renderMetainfoCli$1,`renderMetainfoCli`)});function loadFlathubAppTemplate(){return`{}
988
+ `,__name$1(renderMetainfoApp$1,`renderMetainfoApp`),__name$1(renderMetainfoCli$1,`renderMetainfoCli`),dV=/[\s"'\\><~|&;$*?#()`]/});function loadFlathubAppTemplate(){return`{}
989
989
  `}function loadFlathubCliTemplate(){return`{
990
990
  "skip-icons-check": true
991
991
  }
992
- `}function toMetadataInputs(t){return{appId:t.appId,name:t.name,command:t.command,kind:t.kind,metadata:t.flatpak,channel:`flathub`,configKey:`gjsify.flatpak`}}function validateScaffoldInputs(t){return validateAppMetadata(toMetadataInputs(t))}function renderMetainfoApp(t){return renderMetainfoApp$1(toMetadataInputs(t))}function renderMetainfoCli(t){return renderMetainfoCli$1(toMetadataInputs(t))}function renderDesktop(t){return renderDesktopEntry(toMetadataInputs(t))}function renderFlathubJson(t){return t===`cli`?loadFlathubCliTemplate():loadFlathubAppTemplate()}var pV=__esmMin(()=>{fV()});function oxcBindingSuffix(){let t=process.platform,n=process.arch,S;if(t===`linux`)S=`linux`;else if(t===`darwin`)S=`darwin`;else if(t===`win32`)S=`win32`;else throw Error(`[gjsify oxc] Unsupported platform: ${t}`);let C;if(n===`x64`)C=`x64`;else if(n===`arm64`)C=`arm64`;else throw Error(`[gjsify oxc] Unsupported arch on ${S}: ${n}`);if(S===`linux`){let t=hostLibc(`linux`)===`musl`?`musl`:`gnu`;return`${S}-${C}-${t}`}return S===`win32`?`${S}-${C}-msvc`:`${S}-${C}`}function bindingPackageName(t){return`${t===`oxlint`?`@oxlint`:`@oxfmt`}/binding-${oxcBindingSuffix()}`}function probeNodeModules(t,n,S){let C=zn(t,`node_modules`,n,S);return existsSync(C)?C:null}function findOxcLauncher(t,n=process.cwd()){let S=zn(`bin`,t),C=probeNodeModules(n,t,S);if(C)return C;let N=findWorkspaceRoot(n);if(N&&N!==n){let n=probeNodeModules(N,t,S);if(n)return n}let F=In(n,`..`);for(let n=0;n<6;n++){let n=probeNodeModules(F,t,S);if(n)return n;let C=In(F,`..`);if(C===F)break;F=C}throw new OxcNotFoundError(t,n)}function findOxlintConfig(t=process.cwd()){return findConfigFile(t,[`.oxlintrc.json`])}function findOxfmtConfig(t=process.cwd()){return findConfigFile(t,[`.oxfmtrc`,`.oxfmtrc.json`])}function findConfigFile(t,n){let S=t;for(let t=0;t<12;t++){for(let t of n){let n=zn(S,t);if(existsSync(n))return n}let t=In(S,`..`);if(t===S)break;S=t}return null}async function tryLoadNativeOxfmt(){return mV||(mV=(async()=>{if(!isGjs())return null;try{activateNativePrebuilds();let t=`@gjsify/oxfmt-native`,n=await import(pathToFileURL(resolveNpmPackage(t,{bundleUrl:import.meta.url})??createRequire(import.meta.url).resolve(t)).href);if(!n.hasNativeOxfmt())return null;let S;try{let t=pathToFileURL(resolveNpmPackage(`@gjsify/utils/native-library`,{bundleUrl:import.meta.url})??createRequire(import.meta.url).resolve(`@gjsify/utils/native-library`)).href;({openNativeLibrary:S}=await import(t))}catch(t){return hV=t instanceof Error?t:Error(String(t)),null}return hV=S(`GjsifyOxfmt`),hV?null:n}catch{return null}})(),mV)}function decideOxfmtEngine(t){let{isGjs:n,nativeLoadable:S,embeddedVersion:C,projectVersion:N,override:F}=t,I=C!==void 0&&N!==void 0&&normalizeVersion(C)!==normalizeVersion(N);return F===`npm`?{engine:`npm`}:F===`native`?S?I?{engine:`native`,warning:`GJSIFY_OXFMT=native: @gjsify/oxfmt-native embeds oxfmt ${C} but this project pins oxfmt ${N}; output can differ from the project's own oxfmt (and from CI).`}:{engine:`native`}:{engine:`native`,error:`GJSIFY_OXFMT=native but @gjsify/oxfmt-native is not loadable (no prebuild for this architecture, or not running under GJS).`}:!n||!S?{engine:`npm`}:{engine:I?`npm`:`native`}}function findProjectOxfmtVersion(t=process.cwd()){try{let n=findOxcLauncher(`oxfmt`,t),S=JSON.parse(readFileSync(zn(Hn(n),`..`,`package.json`),`utf-8`));return typeof S?.version==`string`?S.version:void 0}catch{return}}async function shouldUseNativeOxfmt(t=process.cwd()){let n=(globalThis.process?.env??{}).GJSIFY_OXFMT;if(n===`npm`||!isGjs()&&n!==`native`)return!1;let S=await tryLoadNativeOxfmt(),C=decideOxfmtEngine({isGjs:isGjs(),nativeLoadable:S!==null,embeddedVersion:S?.EMBEDDED_OXFMT_VERSION,projectVersion:findProjectOxfmtVersion(t),override:n});if(C.error)throw Error(C.error+(hV?`\n${hV.message}`:``));return C.warning&&!gV&&(gV=!0,ge.warn(`[gjsify oxc] ${C.warning}`)),!S&&hV&&C.engine===`npm`&&ge.debug(hV.message),C.engine===`native`}async function runOxc(t,n,S={}){if(t===`oxfmt`&&await shouldUseNativeOxfmt()){let t=await tryLoadNativeOxfmt();if(!t)throw Error(`@gjsify/oxfmt-native not loadable`);return S.verbose&&ge.log(`[gjsify oxc] @gjsify/oxfmt-native (in-process) ${n.join(` `)}`),t.runOxfmt(n)}return spawnOxcLauncher(t,n,S)}function spawnOxcLauncher(t,n,S={}){let C=S.cwd??process.cwd(),N=findOxcLauncher(t,C),F=nodeBinary();return S.verbose&&ge.log(`[gjsify oxc] ${F} ${N} ${n.join(` `)}`),spawnToCompletion(F,[N,...n],{completion:`return`,cwd:C,notFound:()=>new OxcNotFoundError(t,C,F)}).then(({code:n,signal:S})=>S===null?n??0:(ge.error(`[gjsify oxc] ${t} terminated by signal ${S}`),1))}function runOxlint(t,n={}){return runOxc(`oxlint`,t,n)}function runOxfmt(t,n={}){return runOxc(`oxfmt`,t,n)}function loadOxlintTemplate(){return`{
992
+ `}function toMetadataInputs(t){return{appId:t.appId,name:t.name,command:t.command,kind:t.kind,metadata:t.flatpak,desktopExecArgs:t.desktopExecArgs,channel:`flathub`,configKey:`gjsify.flatpak`}}function validateScaffoldInputs(t){return validateAppMetadata(toMetadataInputs(t))}function renderMetainfoApp(t){return renderMetainfoApp$1(toMetadataInputs(t))}function renderMetainfoCli(t){return renderMetainfoCli$1(toMetadataInputs(t))}function renderDesktop(t){return renderDesktopEntry(toMetadataInputs(t))}function renderFlathubJson(t){return t===`cli`?loadFlathubCliTemplate():loadFlathubAppTemplate()}var pV=__esmMin(()=>{fV()});function oxcBindingSuffix(){let t=process.platform,n=process.arch,S;if(t===`linux`)S=`linux`;else if(t===`darwin`)S=`darwin`;else if(t===`win32`)S=`win32`;else throw Error(`[gjsify oxc] Unsupported platform: ${t}`);let C;if(n===`x64`)C=`x64`;else if(n===`arm64`)C=`arm64`;else throw Error(`[gjsify oxc] Unsupported arch on ${S}: ${n}`);if(S===`linux`){let t=hostLibc(`linux`)===`musl`?`musl`:`gnu`;return`${S}-${C}-${t}`}return S===`win32`?`${S}-${C}-msvc`:`${S}-${C}`}function bindingPackageName(t){return`${t===`oxlint`?`@oxlint`:`@oxfmt`}/binding-${oxcBindingSuffix()}`}function probeNodeModules(t,n,S){let C=zn(t,`node_modules`,n,S);return existsSync(C)?C:null}function findOxcLauncher(t,n=process.cwd()){let S=zn(`bin`,t),C=probeNodeModules(n,t,S);if(C)return C;let N=findWorkspaceRoot(n);if(N&&N!==n){let n=probeNodeModules(N,t,S);if(n)return n}let F=In(n,`..`);for(let n=0;n<6;n++){let n=probeNodeModules(F,t,S);if(n)return n;let C=In(F,`..`);if(C===F)break;F=C}throw new OxcNotFoundError(t,n)}function findOxlintConfig(t=process.cwd()){return findConfigFile(t,[`.oxlintrc.json`])}function findOxfmtConfig(t=process.cwd()){return findConfigFile(t,[`.oxfmtrc`,`.oxfmtrc.json`])}function findConfigFile(t,n){let S=t;for(let t=0;t<12;t++){for(let t of n){let n=zn(S,t);if(existsSync(n))return n}let t=In(S,`..`);if(t===S)break;S=t}return null}async function tryLoadNativeOxfmt(){return mV||(mV=(async()=>{if(!isGjs())return null;try{activateNativePrebuilds();let t=`@gjsify/oxfmt-native`,n=await import(pathToFileURL(resolveNpmPackage(t,{bundleUrl:import.meta.url})??createRequire(import.meta.url).resolve(t)).href);if(!n.hasNativeOxfmt())return null;let S;try{let t=pathToFileURL(resolveNpmPackage(`@gjsify/utils/native-library`,{bundleUrl:import.meta.url})??createRequire(import.meta.url).resolve(`@gjsify/utils/native-library`)).href;({openNativeLibrary:S}=await import(t))}catch(t){return hV=t instanceof Error?t:Error(String(t)),null}return hV=S(`GjsifyOxfmt`),hV?null:n}catch{return null}})(),mV)}function decideOxfmtEngine(t){let{isGjs:n,nativeLoadable:S,embeddedVersion:C,projectVersion:N,override:F}=t,I=C!==void 0&&N!==void 0&&normalizeVersion(C)!==normalizeVersion(N);return F===`npm`?{engine:`npm`}:F===`native`?S?I?{engine:`native`,warning:`GJSIFY_OXFMT=native: @gjsify/oxfmt-native embeds oxfmt ${C} but this project pins oxfmt ${N}; output can differ from the project's own oxfmt (and from CI).`}:{engine:`native`}:{engine:`native`,error:`GJSIFY_OXFMT=native but @gjsify/oxfmt-native is not loadable (no prebuild for this architecture, or not running under GJS).`}:!n||!S?{engine:`npm`}:{engine:I?`npm`:`native`}}function findProjectOxfmtVersion(t=process.cwd()){try{let n=findOxcLauncher(`oxfmt`,t),S=JSON.parse(readFileSync(zn(Hn(n),`..`,`package.json`),`utf-8`));return typeof S?.version==`string`?S.version:void 0}catch{return}}async function shouldUseNativeOxfmt(t=process.cwd()){let n=(globalThis.process?.env??{}).GJSIFY_OXFMT;if(n===`npm`||!isGjs()&&n!==`native`)return!1;let S=await tryLoadNativeOxfmt(),C=decideOxfmtEngine({isGjs:isGjs(),nativeLoadable:S!==null,embeddedVersion:S?.EMBEDDED_OXFMT_VERSION,projectVersion:findProjectOxfmtVersion(t),override:n});if(C.error)throw Error(C.error+(hV?`\n${hV.message}`:``));return C.warning&&!gV&&(gV=!0,ge.warn(`[gjsify oxc] ${C.warning}`)),!S&&hV&&C.engine===`npm`&&ge.debug(hV.message),C.engine===`native`}async function runOxc(t,n,S={}){if(t===`oxfmt`&&await shouldUseNativeOxfmt()){let t=await tryLoadNativeOxfmt();if(!t)throw Error(`@gjsify/oxfmt-native not loadable`);return S.verbose&&ge.log(`[gjsify oxc] @gjsify/oxfmt-native (in-process) ${n.join(` `)}`),t.runOxfmt(n)}return spawnOxcLauncher(t,n,S)}function spawnOxcLauncher(t,n,S={}){let C=S.cwd??process.cwd(),N=findOxcLauncher(t,C),F=nodeBinary();return S.verbose&&ge.log(`[gjsify oxc] ${F} ${N} ${n.join(` `)}`),spawnToCompletion(F,[N,...n],{completion:`return`,cwd:C,notFound:()=>new OxcNotFoundError(t,C,F)}).then(({code:n,signal:S})=>S===null?n??0:(ge.error(`[gjsify oxc] ${t} terminated by signal ${S}`),1))}function runOxlint(t,n={}){return runOxc(`oxlint`,t,n)}function runOxfmt(t,n={}){return runOxc(`oxfmt`,t,n)}function loadOxlintTemplate(){return`{
993
993
  "$schema": "./node_modules/oxlint/configuration_schema.json",
994
994
  "categories": {
995
995
  "correctness": "error"
@@ -1078,8 +1078,8 @@ StartupWMClass={{APP_ID}}
1078
1078
  "**/*.metainfo.xml"
1079
1079
  ]
1080
1080
  }
1081
- `}function printOxcNotFound(t){ge.error(t.message)}function setOxcExitCode(t){process.exitCode=t,t!==0&&gjsExit(t)}function hasOxcDevDep(t=process.cwd(),n=`oxfmt`){let S=zn(t,`package.json`);if(!existsSync(S))return!1;try{let t=JSON.parse(readFileSync(S,`utf-8`));return!!(t?.devDependencies?.[n]||t?.dependencies?.[n])}catch{return!1}}var OxcNotFoundError,mV,hV,normalizeVersion,gV,_V=__esmMin(()=>{_e(),rf(),Xn(),$l(),cr(),Ez(),HI(),GI(),mL(),zR(),mv(),N_(),OxcNotFoundError=class extends Error{tool;cwd;missingInterpreter;constructor(t,n,S){let C=(()=>{try{return bindingPackageName(t)}catch{return`@${t===`oxlint`?`oxlint`:`oxfmt`}/binding-<platform>`}})();super(S===void 0?`[gjsify oxc] ${t} not found.\n Expected: ${t}/bin/${t} in node_modules of ${n} or any workspace root above it.\n Install it via: gjsify install -D ${t}\n (this adds ${t} to devDependencies; the matching ${C} napi binding lands automatically as an optionalDependency.)`:`[gjsify oxc] cannot run ${t}: no \`${S}\` binary on PATH.\n ${t} IS installed — its launcher was found. What is missing is the\n interpreter that runs it: ${t}'s launcher is a Node ESM script.\n`+(t===`oxfmt`?" For a Node-free formatter install the GI bridge:\n gjsify install -D @gjsify/oxfmt-native\n (`gjsify format`/`fix` then run oxfmt in-process under GJS.)":" oxlint has no native GJS bridge yet — its JS-plugin host lives in the\n Node launcher — so `gjsify lint` needs Node on the host for now.")),this.tool=t,this.cwd=n,this.missingInterpreter=S,this.name=`OxcNotFoundError`}},mV=null,hV=null,normalizeVersion=t=>t.trim().replace(/^v/,``),gV=!1});function writeIfFresh(t,n,S,C){return existsSync(t)&&!S?(ge.log(`[gjsify flatpak init] skipped ${C}: ${t} (exists; --force to overwrite)`),null):(mkdirSync(Hn(t),{recursive:!0}),writeFileSync(t,n,`utf-8`),ge.log(`[gjsify flatpak init] wrote ${C}: ${t}`),t)}function friendlyName(t,n){if(t.startsWith(`@`))return t.slice(t.indexOf(`/`)+1);if(t===n){let t=n.split(`.`);return t[t.length-1]??n}return t}function mergeArrays(t,n){if(!(!t?.length&&!n?.length))return[...t??[],...n??[]]}function deriveModuleName(t){let n=t.split(`.`);return n[n.length-1]||t}var vV,yV=__esmMin(()=>{_e(),rf(),Xn(),rV(),oV(),uV(),pV(),pR(),_V(),vV={command:`init`,description:"Generate Flatpak manifest + MetaInfo XML + .desktop + flathub.json from `gjsify.flatpak` config.",builder:t=>t.option(`app-id`,{description:"Reverse-DNS app id (default: `gjsify.flatpak.appId` or package.json#name)",type:`string`}).option(`runtime`,{description:`Runtime family`,choices:[`gnome`,`freedesktop`]}).option(`runtime-version`,{description:`Runtime version (default: gnome -> 50, freedesktop -> 24.08)`,type:`string`}).option(`kind`,{description:`App kind: "app" (default, desktop) or "cli" (console-application MetaInfo, no .desktop)`,choices:[`app`,`cli`]}).option(`cli-only`,{description:"(Deprecated) Alias for `--kind cli`. Use --kind instead.",type:`boolean`,default:!1}).option(`manifest`,{description:"Output path for the manifest. Default: `<app-id>.json` in cwd.",type:`string`,normalize:!0}).option(`metainfo`,{description:"Output path for the MetaInfo XML. Default: `data/<app-id>.metainfo.xml.in` in cwd.",type:`string`,normalize:!0}).option(`desktop`,{description:"Output path for the .desktop entry (app kind only). Default: `data/<app-id>.desktop.in`.",type:`string`,normalize:!0}).option(`flathub-json`,{description:"Output path for the flathub.json policy stub. Default: `flathub.json` in cwd.",type:`string`,normalize:!0}).option(`command`,{description:`Binary name in /app/bin (default: app id)`,type:`string`}).option(`sdk-extension`,{description:`Extra SDK extension (repeatable)`,type:`string`,array:!0}).option(`finish-arg`,{description:`Extra finish-arg (repeatable). Override defaults entirely with multiple --finish-arg.`,type:`string`,array:!0}).option(`force`,{description:`Overwrite existing output files (manifest, metainfo, desktop, flathub.json)`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print the resolved manifest fields before writing`,type:`boolean`,default:!1}).option(`format`,{description:"Run `oxfmt --write` on the generated JS/TS files when `oxfmt` is detected in the project. Default: true. Pass --no-format to skip. Note: oxfmt formats JS/TS only — the JSON/XML/.desktop manifests generated here are not reformatted (CSS/JSON formatting was dropped in the oxc migration).",type:`boolean`,default:!0}),handler:async t=>{let n=await new Config().forCommand().catch(()=>({})),S=n.flatpak??{},C=process.cwd(),N=readPackageJson(C),F=t.appId??S.appId??(looksLikeAppId(N.name)?N.name:void 0);if(!F)throw Error(`gjsify flatpak init: no app id available. Pass --app-id, set gjsify.flatpak.appId in package.json, or rename the package to a reverse-DNS id like org.example.MyApp.`);let I=t.kind??S.kind??(t.cliOnly?`cli`:`app`),H=pickFlatpakBuildKeys(n.ship?.flatpak,S).values,{runtime:W,runtimeId:q,sdk:Y,runtimeVersion:X}=resolveRuntime(H,{runtime:t.runtime,runtimeVersion:t.runtimeVersion}),Z=mergeArrays(H.sdkExtensions,t.sdkExtension),te=H.appendPath??(Z?.length?deriveAppendPath(Z):void 0),ne=t.command??S.command??F,re=t.finishArg,ie=re===void 0?H.finishArgs??(I===`cli`?aV:iV):re,ae={id:F,runtime:q,"runtime-version":X,sdk:Y};Z?.length&&(ae[`sdk-extensions`]=Z),te?.length&&(ae[`build-options`]={"append-path":te.join(`:`)}),ae.command=ne,ae[`finish-args`]=ie;let oe=H.cleanup;oe?.length&&(ae.cleanup=oe);let Q=[];S.modules?.length?Q.push(...S.modules):(S.extraModules?.length&&Q.push(...S.extraModules),Q.push({name:deriveModuleName(F),buildsystem:`meson`,sources:[{type:`dir`,path:`.`}]})),ae.modules=Q;let se=[],trackWrite=t=>{t&&se.push(t)};trackWrite(writeIfFresh(In(C,t.manifest??`${F}.json`),JSON.stringify(ae,null,2)+`
1082
- `,t.force??!1,`manifest`));let ce=N.name??F,le={appId:F,name:S.name??friendlyName(ce,F),command:ne,kind:I,flatpak:S},ue=validateScaffoldInputs(le);if(ue.length>0){ge.warn(`[gjsify flatpak init] Manifest written, but MetaInfo / .desktop are skipped — config gaps:`);for(let t of ue)ge.warn(` - ${t.field}: ${t.hint}`);ge.warn(`
1081
+ `}function printOxcNotFound(t){ge.error(t.message)}function setOxcExitCode(t){process.exitCode=t,t!==0&&gjsExit(t)}function hasOxcDevDep(t=process.cwd(),n=`oxfmt`){let S=zn(t,`package.json`);if(!existsSync(S))return!1;try{let t=JSON.parse(readFileSync(S,`utf-8`));return!!(t?.devDependencies?.[n]||t?.dependencies?.[n])}catch{return!1}}var OxcNotFoundError,mV,hV,normalizeVersion,gV,_V=__esmMin(()=>{_e(),rf(),Xn(),$l(),cr(),Ez(),HI(),GI(),mL(),zR(),mv(),N_(),OxcNotFoundError=class extends Error{tool;cwd;missingInterpreter;constructor(t,n,S){let C=(()=>{try{return bindingPackageName(t)}catch{return`@${t===`oxlint`?`oxlint`:`oxfmt`}/binding-<platform>`}})();super(S===void 0?`[gjsify oxc] ${t} not found.\n Expected: ${t}/bin/${t} in node_modules of ${n} or any workspace root above it.\n Install it via: gjsify install -D ${t}\n (this adds ${t} to devDependencies; the matching ${C} napi binding lands automatically as an optionalDependency.)`:`[gjsify oxc] cannot run ${t}: no \`${S}\` binary on PATH.\n ${t} IS installed — its launcher was found. What is missing is the\n interpreter that runs it: ${t}'s launcher is a Node ESM script.\n`+(t===`oxfmt`?" For a Node-free formatter install the GI bridge:\n gjsify install -D @gjsify/oxfmt-native\n (`gjsify format`/`fix` then run oxfmt in-process under GJS.)":" oxlint has no native GJS bridge yet — its JS-plugin host lives in the\n Node launcher — so `gjsify lint` needs Node on the host for now.")),this.tool=t,this.cwd=n,this.missingInterpreter=S,this.name=`OxcNotFoundError`}},mV=null,hV=null,normalizeVersion=t=>t.trim().replace(/^v/,``),gV=!1});function writeIfFresh(t,n,S,C){return existsSync(t)&&!S?(ge.log(`[gjsify flatpak init] skipped ${C}: ${t} (exists; --force to overwrite)`),null):(mkdirSync(Hn(t),{recursive:!0}),writeFileSync(t,n,`utf-8`),ge.log(`[gjsify flatpak init] wrote ${C}: ${t}`),t)}function friendlyName(t,n){if(t.startsWith(`@`))return t.slice(t.indexOf(`/`)+1);if(t===n){let t=n.split(`.`);return t[t.length-1]??n}return t}function mergeArrays(t,n){if(!(!t?.length&&!n?.length))return[...t??[],...n??[]]}function deriveModuleName(t){let n=t.split(`.`);return n[n.length-1]||t}var vV,yV=__esmMin(()=>{_e(),rf(),Xn(),rV(),oV(),lV(),pV(),pR(),_V(),vV={command:`init`,description:"Generate Flatpak manifest + MetaInfo XML + .desktop + flathub.json from `gjsify.flatpak` config.",builder:t=>t.option(`app-id`,{description:"Reverse-DNS app id (default: `gjsify.flatpak.appId` or package.json#name)",type:`string`}).option(`runtime`,{description:`Runtime family`,choices:[`gnome`,`freedesktop`]}).option(`runtime-version`,{description:`Runtime version (default: gnome -> 50, freedesktop -> 24.08)`,type:`string`}).option(`kind`,{description:`App kind: "app" (default, desktop) or "cli" (console-application MetaInfo, no .desktop)`,choices:[`app`,`cli`]}).option(`cli-only`,{description:"(Deprecated) Alias for `--kind cli`. Use --kind instead.",type:`boolean`,default:!1}).option(`manifest`,{description:"Output path for the manifest. Default: `<app-id>.json` in cwd.",type:`string`,normalize:!0}).option(`metainfo`,{description:"Output path for the MetaInfo XML. Default: `data/<app-id>.metainfo.xml.in` in cwd.",type:`string`,normalize:!0}).option(`desktop`,{description:"Output path for the .desktop entry (app kind only). Default: `data/<app-id>.desktop.in`.",type:`string`,normalize:!0}).option(`flathub-json`,{description:"Output path for the flathub.json policy stub. Default: `flathub.json` in cwd.",type:`string`,normalize:!0}).option(`command`,{description:`Binary name in /app/bin (default: app id)`,type:`string`}).option(`sdk-extension`,{description:`Extra SDK extension (repeatable)`,type:`string`,array:!0}).option(`finish-arg`,{description:`Extra finish-arg (repeatable). Override defaults entirely with multiple --finish-arg.`,type:`string`,array:!0}).option(`force`,{description:`Overwrite existing output files (manifest, metainfo, desktop, flathub.json)`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print the resolved manifest fields before writing`,type:`boolean`,default:!1}).option(`format`,{description:"Run `oxfmt --write` on the generated JS/TS files when `oxfmt` is detected in the project. Default: true. Pass --no-format to skip. Note: oxfmt formats JS/TS only — the JSON/XML/.desktop manifests generated here are not reformatted (CSS/JSON formatting was dropped in the oxc migration).",type:`boolean`,default:!0}),handler:async t=>{let n=await new Config().forCommand().catch(()=>({})),S=n.flatpak??{},C=process.cwd(),N=readPackageJson(C),F=t.appId??S.appId??(looksLikeAppId(N.name)?N.name:void 0);if(!F)throw Error(`gjsify flatpak init: no app id available. Pass --app-id, set gjsify.flatpak.appId in package.json, or rename the package to a reverse-DNS id like org.example.MyApp.`);let I=t.kind??S.kind??(t.cliOnly?`cli`:`app`),H=pickFlatpakBuildKeys(n.ship?.flatpak,S).values,{runtime:W,runtimeId:q,sdk:Y,runtimeVersion:X}=resolveRuntime(H,{runtime:t.runtime,runtimeVersion:t.runtimeVersion}),Z=mergeArrays(H.sdkExtensions,t.sdkExtension),te=H.appendPath??(Z?.length?deriveAppendPath(Z):void 0),ne=t.command??S.command??F,re=t.finishArg,ie=re===void 0?H.finishArgs??(I===`cli`?aV:iV):re,ae={id:F,runtime:q,"runtime-version":X,sdk:Y};Z?.length&&(ae[`sdk-extensions`]=Z),te?.length&&(ae[`build-options`]={"append-path":te.join(`:`)}),ae.command=ne,ae[`finish-args`]=ie;let oe=H.cleanup;oe?.length&&(ae.cleanup=oe);let Q=[];S.modules?.length?Q.push(...S.modules):(S.extraModules?.length&&Q.push(...S.extraModules),Q.push({name:deriveModuleName(F),buildsystem:`meson`,sources:[{type:`dir`,path:`.`}]})),ae.modules=Q;let se=[],trackWrite=t=>{t&&se.push(t)};trackWrite(writeIfFresh(In(C,t.manifest??`${F}.json`),JSON.stringify(ae,null,2)+`
1082
+ `,t.force??!1,`manifest`));let ce=N.name??F,le={appId:F,name:S.name??friendlyName(ce,F),command:ne,kind:I,flatpak:S,desktopExecArgs:n.ship?.desktopExecArgs},ue=validateScaffoldInputs(le);if(ue.length>0){ge.warn(`[gjsify flatpak init] Manifest written, but MetaInfo / .desktop are skipped — config gaps:`);for(let t of ue)ge.warn(` - ${t.field}: ${t.hint}`);ge.warn(`
1083
1083
  Fill these fields in package.json#gjsify.flatpak (or .gjsifyrc.*) and re-run with --force.`)}else{let n=I===`cli`?renderMetainfoCli(le):renderMetainfoApp(le);trackWrite(writeIfFresh(In(C,t.metainfo??`data/${F}.metainfo.xml.in`),n,t.force??!1,`metainfo`)),I===`app`&&(trackWrite(writeIfFresh(In(C,t.desktop??`data/${F}.desktop.in`),renderDesktop(le),t.force??!1,`desktop`)),S.icon||ge.warn(`[gjsify flatpak init] No gjsify.flatpak.icon set. Flathub requires a scalable SVG at\n data/icons/hicolor/scalable/apps/${F}.svg`)),trackWrite(writeIfFresh(In(C,t.flathubJson??`flathub.json`),renderFlathubJson(I),t.force??!1,`flathub.json`))}let de=se.filter(t=>/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(t));if(de.length>0&&t.format!==!1&&hasOxcDevDep(C))try{await runOxfmt([`--write`,...de],{cwd:C})}catch(t){if(t instanceof OxcNotFoundError)ge.warn("[gjsify flatpak init] post-format skipped: oxfmt declared but binding not installed. Run `gjsify install` then re-run with --force, or pass --no-format.");else throw t}t.verbose&&(ge.log(`[gjsify flatpak init] kind=${I} runtime=${q} ${X} sdk=${Y}`),ge.log(`[gjsify flatpak init] command=${ne} finish-args=${JSON.stringify(ie)}`))}}});function findDefaultManifest(t){return scanForManifest(t)??`flatpak.json`}function scanForManifest(t){let n=[];try{n=readdirSync(t)}catch{return}for(let S of n)if(S.endsWith(`.json`)&&!(S===`package.json`||S===`tsconfig.json`||S.startsWith(`.`)))try{let n=JSON.parse(readFileSync(In(t,S),`utf-8`));if(typeof n.id==`string`&&typeof n.runtime==`string`&&Array.isArray(n.modules))return S}catch{}}function readManifestAppId(t){let n=readFileSync(t,`utf-8`),S=JSON.parse(n);if(typeof S.id!=`string`)throw Error(`gjsify flatpak build: ${t} has no string "id" field`);return S.id}async function runFlatpakBuilder(t,n){return runProc(`flatpak-builder`,t,n,{notFoundHint:"flatpak-builder not found. Install via your distro (Fedora: `sudo dnf install flatpak-builder`)."})}async function runFlatpak(t,n){return runProc(`flatpak`,t,n,{notFoundHint:`flatpak not found. Install via your distro and add Flathub: see https://flathub.org/setup.`})}async function runTar(t,n){return runProc(`tar`,t,n,{notFoundHint:`tar not found.`})}async function runProc(t,n,S,C){S.verbose&&ge.log(`[gjsify flatpak] ${t} ${n.join(` `)}`);let{code:N}=await spawnToCompletion(t,n,{completion:`exit`,notFound:()=>Error(`gjsify flatpak: ${C.notFoundHint}`)});if(N!==0)throw Error(`gjsify flatpak: ${t} exited with status ${N}`)}var bV,xV=__esmMin(()=>{_e(),rf(),Xn(),mv(),bV={command:`build [manifest]`,description:"Build the Flatpak via `flatpak-builder`. Wraps a typical install + export + bundle + tarball pipeline.",builder:t=>t.positional(`manifest`,{description:`Path to the Flatpak manifest (default: first *.json that looks like a manifest in cwd)`,type:`string`,normalize:!0}).option(`build-dir`,{description:`flatpak-builder working directory`,type:`string`,default:`flatpak-build`,normalize:!0}).option(`install`,{description:"After build, run `flatpak-builder --user --install` to install locally",type:`boolean`,default:!1}).option(`repo`,{description:"Export the build into the given OSTree repo (passes `--repo=<dir>` to flatpak-builder)",type:`string`,normalize:!0}).option(`bundle`,{description:"After --repo export, build a single-file bundle (`flatpak build-bundle`) at this path",type:`string`,normalize:!0}).option(`tarball`,{description:`Create a tarball of the build dir (parity with the legacy build-flatpak.sh tarball step)`,type:`string`,normalize:!0}).option(`force-clean`,{description:`Pass --force-clean to flatpak-builder (default true)`,type:`boolean`,default:!0}).option(`sandbox`,{description:`Pass --sandbox to flatpak-builder (default true)`,type:`boolean`,default:!0}).option(`delete-build-dirs`,{description:`Pass --delete-build-dirs to flatpak-builder (default true)`,type:`boolean`,default:!0}).option(`install-deps-from`,{description:"Pass --install-deps-from to flatpak-builder (e.g. `flathub`)",type:`string`}).option(`verbose`,{description:`Print the underlying flatpak-builder invocations`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=In(n,t.manifest??findDefaultManifest(n));if(!existsSync(S))throw Error(`gjsify flatpak build: manifest ${S} not found`);let C=In(n,t.buildDir??`flatpak-build`),N=[];if(t.forceClean!==!1&&N.push(`--force-clean`),t.sandbox!==!1&&N.push(`--sandbox`),t.deleteBuildDirs!==!1&&N.push(`--delete-build-dirs`),t.installDepsFrom&&N.push(`--install-deps-from=${t.installDepsFrom}`),existsSync(C)&&rmSync(C,{recursive:!0,force:!0}),await runFlatpakBuilder([...N,C,S],{verbose:t.verbose}),t.install&&await runFlatpakBuilder([`--user`,`--install`,`--force-clean`,C,S],{verbose:t.verbose}),t.repo){let N=In(n,t.repo);mkdirSync(Hn(N),{recursive:!0}),await runFlatpakBuilder([`--repo=${N}`,`--force-clean`,C,S],{verbose:t.verbose})}if(t.bundle){if(!t.repo)throw Error(`gjsify flatpak build: --bundle requires --repo (the bundle is built from the OSTree repo).`);let C=In(n,t.bundle);mkdirSync(Hn(C),{recursive:!0}),await runFlatpak([`build-bundle`,In(n,t.repo),C,readManifestAppId(S)],{verbose:t.verbose})}if(t.tarball){let S=In(n,t.tarball);mkdirSync(Hn(S),{recursive:!0}),await runTar([`-czf`,S,`-C`,C,`.`],{verbose:t.verbose})}return ge.log(`[gjsify flatpak build] done (${C})`),process.exit(0)}}});function detectLockfile(t){return existsSync(In(t,`yarn.lock`))?`yarn.lock`:existsSync(In(t,`package-lock.json`))?`package-lock.json`:`yarn.lock`}var SV,CV=__esmMin(()=>{_e(),mv(),rf(),Xn(),SV={command:`deps`,description:"Generate Flatpak offline-cache sources from a yarn.lock / package-lock.json (wraps `flatpak-node-generator`).",builder:t=>t.option(`lockfile`,{description:`Path to lockfile (default: yarn.lock or package-lock.json in cwd)`,type:`string`,normalize:!0}).option(`type`,{description:`Lockfile type. Default: detected from filename.`,choices:[`yarn`,`npm`]}).option(`out`,{description:`Output JSON sources file`,type:`string`,default:`flatpak-node-sources.json`,normalize:!0}).option(`xdg-layout`,{description:`Pass --xdg-layout (recommended for Yarn Berry / PnP setups)`,type:`boolean`,default:!0}).option(`electron-node-headers`,{description:`Pass --electron-node-headers`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print the underlying flatpak-node-generator invocation`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=In(n,t.lockfile??detectLockfile(n));if(!existsSync(S))throw Error(`gjsify flatpak deps: lockfile ${S} not found (use --lockfile to override)`);let C=t.type??(S.endsWith(`package-lock.json`)?`npm`:`yarn`),N=In(n,t.out??`flatpak-node-sources.json`);mkdirSync(Hn(N),{recursive:!0});let F=[C,S,`-o`,N];t.xdgLayout!==!1&&F.push(`--xdg-layout`),t.electronNodeHeaders&&F.push(`--electron-node-headers`),t.verbose&&ge.log(`[gjsify flatpak deps] flatpak-node-generator ${F.join(` `)}`);let I=await spawnToCompletion(`flatpak-node-generator`,F,{completion:`return`,notFound:()=>Error("gjsify flatpak deps: flatpak-node-generator not found. Install via `pipx install flatpak-node-generator` (see https://github.com/flatpak/flatpak-builder-tools/tree/master/node).")});if(I.code!==0)throw Error(`gjsify flatpak deps: flatpak-node-generator exited with ${describeExit(I)}`);ge.log(`[gjsify flatpak deps] wrote ${N}`)}}});function classifyDependency(t,n,S){let C=S.get(t);return C&&!TV.test(n)?{kind:`workspace`,target:C}:n.startsWith(`workspace:`)?{kind:`missing-workspace`}:TV.test(n)?{kind:`ignored`}:{kind:`external`}}function planFocus(t,n,S){let C=new Map(t.map(t=>[t.name,t])),N=[...new Set(n)].filter(t=>!C.has(t));if(N.length>0){let t=[...C.keys()].sort(),n=t.slice(0,EV).join(`, `),F=t.length>EV?`, … (${t.length-EV} more)`:``;throw Error(`${S}: --focus names unknown workspace(s): ${N.join(`, `)}. Pass a package name from a workspace's package.json. Known workspaces: ${n}${F}.`)}let F=new Set(n.map(t=>C.get(t))),I=new Set;for(let t of F)for(let n of wV)for(let[S,N]of Object.entries(t.manifest[n]??{})){if(typeof N!=`string`)continue;let t=classifyDependency(S,N,C);t.kind===`workspace`?F.add(t.target):t.kind===`external`&&I.add(`${S}@${N}`)}return{workspaces:t.filter(t=>F.has(t)),specs:[...I]}}var wV,TV,EV,DV=__esmMin(()=>{wV=[`dependencies`,`devDependencies`,`optionalDependencies`],TV=/^(link|file|portal|git\+|https?):/,EV=20});function parseSri(t){if(!t)return null;let n=t.indexOf(`-`);if(n<=0||n===t.length-1)return null;let S=t.slice(0,n),C=t.slice(n+1).replace(/=+$/,``),N=ot.from(C,`base64`).toString(`hex`);return N.length<4?null:{algorithm:S,hex:N}}function parseNpmLike(t){let n=[],S=t,C=S.packages;if(C&&typeof C==`object`){for(let t of Object.values(C))t?.resolved&&t.integrity&&n.push({url:t.resolved,integrity:t.integrity});if(n.length>0)return n}return S.dependencies&&typeof S.dependencies==`object`&&collectV1Deps(S.dependencies,n),n}function collectV1Deps(t,n){for(let S of Object.values(t))S?.resolved&&S.integrity&&n.push({url:S.resolved,integrity:S.integrity}),S?.dependencies&&collectV1Deps(S.dependencies,n)}function parseYarnClassic(t){if(/^__metadata:/m.test(t))throw Error("gjsify flatpak sources: Yarn Berry (v2+) yarn.lock is not supported — its `checksum` is a cache hash, not a tarball SRI. Run `gjsify install` to produce a gjsify-lock.json, or use a classic (v1) yarn.lock.");let n=[],S=0;for(let C of t.split(/\n\s*\n/)){let t=C.match(/^\s+resolved\s+"([^"]+)"/m);if(!t)continue;let N=t[1].replace(/#.*$/,``),F=C.match(/^\s+integrity\s+(\S+)/m);if(!F){S++;continue}n.push({url:N,integrity:F[1]})}return S>0&&ge.warn(`[gjsify flatpak sources] ${S} yarn.lock entr(y/ies) had no integrity (pre-1.x format) and were skipped — re-lock with a modern yarn or use \`gjsify install\`.`),n}function parsePnpm(t){let n=[],S=!1,C=null;for(let N of t.split(`
1084
1084
  `)){let t=N.replace(/\r$/,``);if(/^packages:\s*$/.test(t)){S=!0;continue}if(S&&/^[^\s#]/.test(t)&&(S=!1),!S)continue;let F=t.match(/^ {2}(?:'([^']+)'|"([^"]+)"|([^\s#][^:]*)):\s*$/);if(F){C=F[1]??F[2]??F[3]??null;continue}let I=t.match(/resolution:\s*\{([^}]*)\}/);if(I&&C){let t=I[1].match(/integrity:\s*(sha\d+-[A-Za-z0-9+/=]+)/);if(!t)continue;let S=I[1].match(/tarball:\s*([^\s,}]+)/),N=S?S[1]:reconstructNpmTarballUrl(C);N&&n.push({url:N,integrity:t[1]})}}return n}function reconstructNpmTarballUrl(t){let n,S;if(t.startsWith(`/`)){let C=t.slice(1).replace(/_.*$/,``),N=C.lastIndexOf(`/`);if(N<=0)return null;n=C.slice(0,N),S=C.slice(N+1)}else{let C=t.replace(/\(.*\)$/,``),N=C.lastIndexOf(`@`);if(N<=0)return null;n=C.slice(0,N),S=C.slice(N+1)}if(!n||!S||/[@:/]/.test(S))return null;let C=n.slice(n.lastIndexOf(`/`)+1);return`https://registry.npmjs.org/${n}/-/${C}-${S}.tgz`}function detectType(t){let n=t.toLowerCase();return n.endsWith(`pnpm-lock.yaml`)?`pnpm`:n.endsWith(`yarn.lock`)?`yarn`:n.endsWith(`package-lock.json`)?`npm`:`gjsify`}function defaultLockfile(t){for(let n of[`gjsify-lock.json`,`package-lock.json`,`yarn.lock`,`pnpm-lock.yaml`])if(existsSync(zn(t,n)))return n;return`gjsify-lock.json`}function focusedTarballs(t,n){let S=discoverWorkspaces(Hn(t),{includeRoot:!0}),C=planFocus(S,n,`gjsify flatpak sources`),N=readLockfileNodes(t);if(!N)throw Error(`gjsify flatpak sources: ${t} is not a readable gjsify-lock.json.`);let F=reachableInstallPaths(N,C.specs.map(parseSpecName)),I=new Set(S.map(t=>t.name));return N.filter(t=>F.has(t.installPath)&&!I.has(t.name)).flatMap(t=>t.tarballUrl&&t.integrity?[{url:t.tarballUrl,integrity:t.integrity}]:[])}function parseLockfile(t,n){let S=readFileSync(t,`utf-8`);if(n===`yarn`)return parseYarnClassic(S);if(n===`pnpm`)return parsePnpm(S);let C;try{C=JSON.parse(S)}catch(n){throw Error(`gjsify flatpak sources: ${t} is not valid JSON: ${n.message}`)}return parseNpmLike(C)}function buildModuleSnippet(t,n){return[``,`# Add the generated sources to your app module and point XDG_CACHE_HOME`,`# at the vendored cache before running gjsify offline. Example module:`,`#`,`# {`,`# "name": "my-app",`,`# "buildsystem": "simple",`,`# "build-commands": [`,`# "export XDG_CACHE_HOME=\\"$(pwd)/${n}\\"",`,`# "gjsify install --immutable",`,`# "gjsify build src/main.ts --app gjs --outfile /app/bin/my-app"`,`# ],`,`# "sources": [`,`# { "type": "dir", "path": "." },`,`# "${t}"`,`# ]`,`# }`,``].join(`
1085
1085
  `)}var OV,kV,AV=__esmMin(()=>{_e(),rf(),Xn(),ht(),BI(),DV(),Rz(),rV(),OV=new Set([`sha256`,`sha512`]),kV={command:`sources`,description:"Generate an offline flatpak-builder `sources` array from any lockfile (gjsify-lock.json / package-lock.json / yarn.lock / pnpm-lock.yaml) for a no-network Flathub build.",builder:t=>t.option(`lockfile`,{description:`Path to the lockfile. Default: the first of gjsify-lock.json / package-lock.json / yarn.lock / pnpm-lock.yaml found in cwd.`,type:`string`,normalize:!0}).option(`type`,{description:`Lockfile format. Default: detected from the filename.`,choices:[`gjsify`,`npm`,`yarn`,`pnpm`]}).option(`out`,{description:`Output JSON sources file`,type:`string`,default:nV,normalize:!0}).option(`cache-root`,{description:`Relative dir the tarballs download into; point XDG_CACHE_HOME here in the build. Tarballs land at <cache-root>/gjsify/tarballs/v1/<algo>/<shard>/<hex>.tgz.`,type:`string`,default:`flatpak-gjsify-cache`}).option(`focus`,{description:"Only the tarballs the named workspaces (package names), the workspaces they depend on, and their external dependencies need, as `gjsify install --focus` installs them. gjsify-lock.json only.",type:`string`,array:!0}).option(`print-module`,{description:`Also print a ready-to-paste flatpak manifest module snippet to stderr`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=In(n,t.lockfile??defaultLockfile(n));if(!existsSync(S))throw Error(`gjsify flatpak sources: lockfile ${S} not found. Run \`gjsify install\` (or npm/yarn/pnpm) first, or pass --lockfile.`);let C=t.type??detectType(S),N=t.focus;if(N&&N.length>0&&C!==`gjsify`)throw Error(`gjsify flatpak sources: --focus reads the per-package edges of gjsify-lock.json; ${C} lockfiles are not supported with it.`);let F=N&&N.length>0?focusedTarballs(S,N):parseLockfile(S,C),I=t.cacheRoot??`flatpak-gjsify-cache`,H=new Map,W=0,q=0;for(let{url:t,integrity:n}of F){let S=parseSri(n);if(!S){W++;continue}if(!OV.has(S.algorithm)){q++;continue}let C=`${S.algorithm}:${S.hex}`;if(H.has(C))continue;let N={type:`file`,url:t,dest:`${I}/gjsify/tarballs/v1/${S.algorithm}/${S.hex.slice(0,2)}`,"dest-filename":`${S.hex}.tgz`};S.algorithm===`sha512`?N.sha512=S.hex:N.sha256=S.hex,H.set(C,N)}let Y=[...H.values()].sort((t,n)=>t.url<n.url?-1:+(t.url>n.url)),X=In(n,t.out??`gjsify-sources.json`);mkdirSync(Hn(X),{recursive:!0}),writeFileSync(X,JSON.stringify(Y,null,2)+`
@@ -1111,7 +1111,7 @@ jobs:
1111
1111
  manifest-path: ${t.manifest}
1112
1112
  bundle: ${t.bundle}
1113
1113
  cache-key: ${t.cacheKey}
1114
- `}var jV,MV=__esmMin(()=>{_e(),rf(),Xn(),pR(),rV(),oV(),uV(),jV={command:`ci`,description:`Scaffold .github/workflows/flatpak.yml using the flathub-infra container + flatpak-builder@v6 action.`,builder:t=>t.option(`manifest`,{description:`Manifest path the workflow points at (default: <app-id>.json)`,type:`string`,normalize:!0}).option(`bundle`,{description:`Bundle filename produced by the action (default: <app-id>.flatpak)`,type:`string`,normalize:!0}).option(`runtime-image`,{description:"Container image override. Default derived from gjsify.flatpak.runtime + runtimeVersion (e.g. `ghcr.io/flathub-infra/flatpak-github-actions:gnome-50`).",type:`string`}).option(`branches`,{description:`Branches the workflow runs on push for (default: main)`,type:`string`,array:!0}).option(`out`,{description:`Output path`,type:`string`,default:`.github/workflows/flatpak.yml`,normalize:!0}).option(`cache-key`,{description:"Override the action `cache-key` (default: `flatpak-builder-${{ github.sha }}`)",type:`string`}).option(`force`,{description:`Overwrite an existing workflow file`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print resolved fields`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=await new Config().forCommand().catch(()=>({})),C=S.flatpak??{},N=readPackageJson(n),F=C.appId??(looksLikeAppId(N.name)?N.name:void 0);if(!F)throw Error(`gjsify flatpak ci: no app id available. Set gjsify.flatpak.appId in package.json or rename the package to a reverse-DNS id.`);let I=t.manifest??`${F}.json`,H=t.bundle??`${F}.flatpak`,W=pickFlatpakBuildKeys(S.ship?.flatpak,C).values,{runtime:q,runtimeVersion:Y}=resolveRuntime(W,{}),X=t.runtimeImage??C.ciContainer??defaultCiContainer(q,Y),Z=t.branches??C.ciBranches??[`main`],te=t.cacheKey??"flatpak-builder-${{ github.sha }}",ne=In(n,t.out??`.github/workflows/flatpak.yml`);if(existsSync(ne)&&!t.force){if(readFileSync(ne,`utf-8`)===renderWorkflow({manifest:I,bundle:H,runtimeImage:X,branches:Z,cacheKey:te})){ge.log(`[gjsify flatpak ci] ${ne} already up to date`);return}throw Error(`gjsify flatpak ci: ${ne} exists with different content. Pass --force to overwrite.`)}let re=renderWorkflow({manifest:I,bundle:H,runtimeImage:X,branches:Z,cacheKey:te});mkdirSync(Hn(ne),{recursive:!0}),writeFileSync(ne,re,`utf-8`),t.verbose&&ge.log(`[gjsify flatpak ci] runtime-image=${X} manifest=${I} bundle=${H}`),ge.log(`[gjsify flatpak ci] wrote ${ne}`)}}});function buildTree$1(t){let n={name:`#root`,attrs:{},children:[],text:``},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)for(let t of S)t.text+=n.text;else if(n.kind===`open`){let C={name:LV(n.name),attrs:n.attributes,children:[],text:``};t.children.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function localized(t,n){let S=new Map;for(let C of kids(t,n)){let t=RV(C.text);t!==``&&!S.has(lang(C))&&S.set(lang(C),t)}return S}function parseHex(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];S.length===3&&(S=S.replace(/./g,t=>t+t));let C=Number.parseInt(S.slice(0,2),16)/255,N=Number.parseInt(S.slice(2,4),16)/255,F=Number.parseInt(S.slice(4,6),16)/255,I=Math.max(C,N,F),H=Math.min(C,N,F),W=(I+H)/2,q=I-H;return{s:q===0?0:q/(1-Math.abs(2*W-1)),l:W}}function readImageInfo(t){if(t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){let u32=n=>(t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3])>>>0;return{kind:`raster`,width:u32(16),height:u32(20)}}if(t.length>=4&&t[0]===255&&t[1]===216){let n=2;for(;n+9<t.length;){if(t[n]!==255){n++;continue}let S=t[n+1];if(S===255){n++;continue}if(S>=192&&S<=207&&S!==196&&S!==200&&S!==204)return{kind:`raster`,height:t[n+5]<<8|t[n+6],width:t[n+7]<<8|t[n+8]};n+=2+(t[n+2]<<8|t[n+3])}return null}let n=``;for(let S=0;S<Math.min(t.length,1024);S++)n+=String.fromCharCode(t[S]);return/<svg[\s>]/.test(n)?{kind:`svg`}:null}function termPattern(t,n=`iu`){let S=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\s+/g,`\\s+`);return RegExp(`(^|[^\\p{L}\\p{N}])${S}($|[^\\p{L}\\p{N}])`,n)}async function lintMetainfo(t,n={}){let S=[],add=(t,n,C,N,F)=>{S.push({rule:t,severity:n,message:F,location:N,url:`${NV}#${C}`})},C=child(buildTree$1(t),`component`);if(C===void 0)return add(`no-component`,`error`,`app-name`,`document`,`no <component> element found`),S;let loc=(t,n)=>n===``?t:`${t}[${n}]`,N=localized(C,`name`),F=localized(C,`summary`);for(let[t,n]of N){let S=loc(`name`,t),C=[...n].length;if(C>=20?add(`name-too-long`,`error`,`not-too-long`,S,`"${n}" is ${C} characters; a name must be shorter than 20`):C>15&&add(`name-long`,`warning`,`not-too-long`,S,`"${n}" is ${C} characters; ideally at most 15`),/\s[-–—:]\s|:\s|\(.+\)/.test(n)||/\b(web browser|editor|client|viewer|player)$/i.test(n)&&n.includes(` `))add(`name-extra-info`,`warning`,`just-the-name`,S,`"${n}" carries a description; keep just the name and put the rest in the summary`);else if(/[.-]/.test(n))add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" contains a dot or dash; avoid punctuation in names`);else if(/\p{L}/u.test(n)){let t=n.replace(/[^\p{L}]/gu,``);n===n.toLowerCase()?add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is all lowercase`):t.length>1&&n===n.toUpperCase()?add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is all uppercase (exempt only for an established brand such as VLC)`):!/\s/.test(n)&&/\p{Ll}\p{Lu}/u.test(n)&&add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is camel/pascal case`)}}let I=(n.technicalTerms??[...PV]).map(t=>({term:t,re:termPattern(t)}));for(let[t,n]of F){let S=loc(`summary`,t),C=[...n].length;C>35?add(`summary-too-long`,`error`,`not-too-long-1`,S,`"${n}" is ${C} characters; at most 35 allowed`):(C>25||C<10)&&add(`summary-length`,`warning`,`not-too-long-1`,S,`"${n}" is ${C} characters; ideal is 10 to 25`),/[.。]$/.test(n)&&add(`summary-full-stop`,`warning`,`no-weird-formatting-1`,S,`a summary does not end with a full stop`);let F=n.split(/\s+/).filter(t=>/^\p{L}/u.test(t)),H=F.filter(t=>/^\p{Lu}/u.test(t)).length;F.length>=3&&H/F.length>=.75&&add(`summary-title-case`,`warning`,`no-weird-formatting-1`,S,`use sentence case, not Title Case`);let W=IV[langBase(t===``?`en`:t)],q=n.split(/\s+/)[0]?.toLowerCase();W?.includes(q)&&add(`summary-article`,`warning`,`dont-start-with-an-article`,S,`starts with the article "${q}"; omit it or phrase it with a verb`);let Y=N.get(t)??N.get(``);Y!==void 0&&[...Y].length>=3&&termPattern(Y,`u`).test(n)&&add(`summary-repeats-name`,`warning`,`dont-repeat-the-name`,S,`repeats the app name "${Y}"`);let X=I.find(({re:t})=>t.test(n));X!==void 0&&add(`summary-technical`,`warning`,`not-technical`,S,`mentions "${X.term}"; say what the app does for people, not how it is built`)}let H=kids(C,`description`).find(t=>lang(t)===``)??child(C,`description`);if(H!==void 0){let t=F.get(``)??``,n=kids(H,`p`).filter(t=>lang(t)===``).map(t=>RV(t.text)),S=n.join(` `);t!==``&&n.length>0&&n[0].replace(/[.!]$/,``).toLowerCase()===t.toLowerCase()&&add(`description-repeats-summary`,`warning`,`dont-repeat-the-summary`,`description`,`the first paragraph repeats the summary`),t!==``&&[...S].length<Math.max(80,3*[...t].length)&&add(`description-short`,`warning`,`not-too-short`,`description`,`${[...S].length} characters; it should be substantially longer than the summary`);for(let t of[...kids(H,`ul`),...kids(H,`ol`)]){let n=kids(t,`li`).filter(t=>lang(t)===``).length;n>10&&add(`description-long-list`,`warning`,`no-super-long-lists`,`description`,`a list with ${n} items; group them or use paragraphs (max 10)`)}}let W=kids(child(C,`branding`),`color`).filter(t=>t.attrs.type===`primary`),q=W.find(t=>t.attrs.scheme_preference===`light`),Y=W.find(t=>t.attrs.scheme_preference===`dark`);if(q===void 0||Y===void 0)add(`branding-missing`,`warning`,`has-primary-brand-colors`,`branding`,`set two primary brand colors, scheme_preference="light" and "dark"`);else{let t=RV(q.text).toLowerCase(),n=RV(Y.text).toLowerCase();t===n&&add(`branding-identical`,`warning`,`good-brand-colors`,`branding`,`light and dark primary colors are the same`);let S=parseHex(t),C=parseHex(n);for(let[N,F,I]of[[`light`,S,t],[`dark`,C,n]])F!==null&&(F.s<.15||F.l>.93||F.l<.07)&&add(`branding-dull`,`warning`,`good-brand-colors`,`branding/${N}`,`${I} is near white, black or gray; brand colors should be colorful`);S!==null&&C!==null&&t!==n&&C.l>=S.l&&add(`branding-dark-not-darker`,`warning`,`good-brand-colors`,`branding/dark`,`the dark variant should be darker than the light one`)}if(n.probeImage!==void 0)for(let t of n.iconRefs??[]){let S=await n.probeImage(t);if(S!==null){S.kind===`raster`&&(S.width===S.height?S.width<256&&add(`icon-too-small`,`error`,`icon-size`,`icon`,`${t} is ${S.width}×${S.height}; use SVG or at least 256×256`):add(`icon-not-square`,`error`,`icon-size`,`icon`,`${t} is ${S.width}×${S.height}; the icon has to be square`));break}}let X=kids(child(C,`screenshots`),`screenshot`);if(X.length===0)add(`screenshot-missing`,`warning`,`at-least-one-screenshot`,`screenshots`,`at least one screenshot is expected`);else{let englishTag=t=>t===``||langBase(t)===`en`,isEnglish=t=>{let n=kids(t,`image`).map(lang);return englishTag(lang(t))&&(n.length===0||n.some(englishTag))};X.some(isEnglish)||add(`screenshot-no-english`,`warning`,`at-least-one-screenshot`,`screenshots`,`no screenshot without xml:lang (or in English)`),X[0].attrs.type!=="default"&&add(`screenshot-default-not-first`,`warning`,`at-least-one-screenshot`,`screenshot[1]`,`the first screenshot should be type="default" — it is the one users see first`);for(let t=0;t<X.length;t++){let S=X[t],C=`screenshot[${t+1}]`,N=kids(S,`caption`);N.length===0&&add(`screenshot-caption-missing`,`warning`,`image-captions`,C,`no <caption>`);for(let t of N){let n=RV(t.text),S=`${C}/${loc(`caption`,lang(t))}`;/[.。]$/.test(n)&&add(`caption-full-stop`,`warning`,`image-captions`,S,`a caption does not end with a full stop`),/^\d/.test(n)&&add(`caption-starts-with-number`,`warning`,`image-captions`,S,`a caption does not start with a number`),/[.!?]\s+\p{Lu}/u.test(n)&&add(`caption-multiple-sentences`,`warning`,`image-captions`,S,`a caption is one sentence`)}if(n.probeImage!==void 0){let t=kids(S,`image`).find(t=>(t.attrs.type??`source`)===`source`),N=t===void 0?``:RV(t.text),F=N===``?null:await n.probeImage(N);F?.kind===`raster`&&(F.width>2e3||F.height>1400)&&add(`screenshot-too-large`,`warning`,`reasonable-window-size`,C,`${F.width}×${F.height}; keep the window at most 1000×700 (2000×1400 on HiDPI)`)}}}for(let t of kids(child(C,`releases`),`release`)){let n=`release ${t.attrs.version??`?`}`,S=child(t,`description`),C=S===void 0?``:RV(S.text);if(C===``){add(`release-notes-missing`,`warning`,`release-notes-for-every-release`,n,`no release notes`);continue}FV.some(t=>t.test(C.replace(/[.!]+$/,``)))?add(`release-notes-generic`,`warning`,`no-bug-fixes-and-performance-improvements`,n,`"${C}" says nothing about what changed`):([...C].length>600||kids(child(S,`ul`),`li`).length>10)&&add(`release-notes-long`,`warning`,`short-but-informative`,n,`release notes are long; summarise what changed for users`)}return S}function summarizeFindings(t,n){let S=0,C=0;for(let N of t)N.severity===`error`||n?S++:C++;return{errors:S,warnings:C}}function formatFinding(t,n){return`${(n?`error`:t.severity).padEnd(7)} ${t.rule} ${t.location}: ${t.message}\n ${t.url}`}var NV,PV,FV,IV,LV,child,kids,RV,lang,langBase,zV=__esmMin(()=>{Ye(),NV=`https://docs.flathub.org/docs/for-app-authors/metainfo-guidelines/quality-guidelines`,PV=`GTK.GTK3.GTK4.Qt.Qt5.Qt6.libadwaita.Electron.Rust.Python.JavaScript.TypeScript.GJS.Flatpak.written in.open source.open-source.free software.FOSS.app.application.tool.client.wrapper.App.Anwendung.Werkzeug`.split(`.`),FV=[/^(minor |various |general |misc(ellaneous)? )?bug ?fix(es)?( (and|&) (minor )?(performance )?(improvements?|fixes|tweaks))?$/i,/^(minor |various |general )?(performance )?improvements?( (and|&) (bug ?fix(es)?|fixes))?$/i,/^bug ?fix(es)?,? (and )?(performance|stability) improvements?$/i,/^(performance|stability) (improvements?|fixes)( (and|&) bug ?fix(es)?)?$/i,/^(fehlerbehebungen?|fehlerkorrekturen?|verbesserungen)( (und|&) (fehlerbehebungen?|verbesserungen|leistungsverbesserungen))?$/i,/^(kleinere )?(fehlerbehebungen|verbesserungen)$/i],IV={en:[`a`,`an`,`the`],de:[`ein`,`eine`,`einen`,`einem`,`einer`,`der`,`die`,`das`,`den`,`dem`]},LV=__name$1(t=>t.startsWith(`_`)?t.slice(1):t,`normName`),__name$1(buildTree$1,`buildTree`),child=(t,n)=>t?.children.find(t=>t.name===n),kids=(t,n)=>t?.children.filter(t=>t.name===n)??[],RV=__name$1(t=>t.replace(/\s+/g,` `).trim(),`clean`),lang=t=>t.attrs[`xml:lang`]??``,langBase=t=>t.split(/[_\-.@]/)[0].toLowerCase()});function appstreamValidateArgs(t,n=!1){return[`validate`,`--strict`,...n?[]:[`--no-net`],t]}async function runQuality(t,n,S){let C=Hn(t),probeImage=async t=>{if(/^https?:\/\//.test(t)){if(!S.qualityNetwork)return null;try{let n=await fetch(t);return n.ok?readImageInfo(new Uint8Array(await n.arrayBuffer())):null}catch{return null}}let n=In(C,t);return existsSync(n)?readImageInfo(new Uint8Array(readFileSync(n))):null},N=n??``,F=N?[`icons/hicolor/scalable/apps/${N}.svg`,`icons/${N}.svg`,`${N}.svg`,`${N}.png`,`../data/icons/hicolor/scalable/apps/${N}.svg`]:[],I=await lintMetainfo(readFileSync(t,`utf-8`),{probeImage,iconRefs:F}),H=S.strict===!0,{errors:W,warnings:q}=summarizeFindings(I,H);if(S.json)ge.log(JSON.stringify({file:t,errors:W,warnings:q,findings:I.map(t=>({...t,severity:H?`error`:t.severity}))},null,2));else{for(let t of I)ge.log(formatFinding(t,H));ge.log(`[gjsify flatpak check] ${W===0?`OK`:`FAIL`}: quality ${t} — ${W} error(s), ${q} warning(s)`)}return W===0}function resolveAppId(t,n,S){if(n.appId)return n.appId;try{let t=readPackageJson(S);if(looksLikeAppId(t.name))return t.name}catch{}if(t)return t.replace(/\.json$/,``)}function resolveManifestPath(t,n,S){if(t)return In(S,t);if(n)return In(S,`${n}.json`);let C=readdirSync(S).filter(t=>t.endsWith(`.json`)&&!t.startsWith(`package`));if(C.length===1)return In(S,C[0]);throw Error(`gjsify flatpak check: no manifest path given and could not auto-detect. Pass the manifest as a positional argument.`)}async function runLinter(t,n,S){let C;try{C=await spawnToCompletion(t,n,{completion:`return`,stdio:S?`inherit`:`capture`})}catch(n){let S=n;return S.code===`ENOENT`?ge.error(`[gjsify flatpak check] ${t} not found in PATH.\nInstall via:\n flatpak install -y flathub org.flatpak.Builder\n alias ${t}="flatpak run --command=${t} org.flatpak.Builder"`):ge.error(`[gjsify flatpak check] ${t} failed to spawn: ${S.message}`),!1}let N=C.code===0;return ge.log(`[gjsify flatpak check] ${N?`OK`:`FAIL`}: ${t} ${n.join(` `)}`),!N&&!S&&(C.stdout?.trim()&&ge.log(C.stdout.trimEnd()),C.stderr?.trim()&&ge.error(C.stderr.trimEnd())),N}var BV,VV=__esmMin(()=>{_e(),rf(),Xn(),mv(),rV(),pR(),zV(),BV={command:`check [manifest]`,description:`Run Flathub pre-submission linters: appstreamcli validate + flatpak-builder-lint.`,builder:t=>t.positional(`manifest`,{description:"Path to the Flatpak manifest. Auto-detects `<app-id>.json` if omitted.",type:`string`,normalize:!0}).option(`repo`,{description:"Built ostree-repo path. If given, also runs `flatpak-builder-lint repo`.",type:`string`,normalize:!0}).option(`metainfo`,{description:"MetaInfo XML path. Default: `data/<app-id>.metainfo.xml.in`.",type:`string`,normalize:!0}).option(`appstream`,{description:"Run `appstreamcli validate --strict --no-net` (default: true).",type:`boolean`,default:!0}).option(`quality`,{description:`Run Flathub's quality guidelines (name, summary, branding, screenshots, release notes) on the MetaInfo (default: true).`,type:`boolean`,default:!0}).option(`strict`,{description:`Treat quality warnings as errors.`,type:`boolean`,default:!1}).option(`json`,{description:`Print the quality findings as JSON (and nothing else on stdout).`,type:`boolean`,default:!1}).option(`quality-network`,{description:`Let the quality check fetch http(s) screenshot/icon URLs to measure their size.`,type:`boolean`,default:!1}).option(`appstream-network`,{description:"Let `appstreamcli` fetch the MetaInfo URLs to check they are reachable.",type:`boolean`,default:!1}).option(`builder-lint`,{description:"Run `flatpak-builder-lint manifest` (default: true).",type:`boolean`,default:!0}).option(`verbose`,{description:`Stream linter stdout/stderr verbatim.`,type:`boolean`,default:!1}),handler:async t=>{let n=(await new Config().forCommand().catch(()=>({}))).flatpak??{},S=process.cwd(),C=resolveAppId(t.manifest,n,S),N=resolveManifestPath(t.manifest,C,S),F=In(S,t.metainfo??`data/${C??`unknown`}.metainfo.xml.in`),I=0;if(t.appstream!==!1&&(existsSync(F)?await runLinter(`appstreamcli`,appstreamValidateArgs(F,t.appstreamNetwork===!0),t.verbose??!1)||I++:ge.warn(`[gjsify flatpak check] skipping appstreamcli — ${F} not found`)),t.quality!==!1&&(existsSync(F)?await runQuality(F,C,t)||I++:ge.warn(`[gjsify flatpak check] skipping quality check — ${F} not found`)),t.builderLint!==!1&&!t.json){if(!existsSync(N))return ge.error(`[gjsify flatpak check] manifest not found: ${N}`),process.exit(1);await runLinter(`flatpak-builder-lint`,[`manifest`,N],t.verbose??!1)||I++,t.repo&&(await runLinter(`flatpak-builder-lint`,[`repo`,In(S,t.repo)],t.verbose??!1)||I++)}if(I>0)return ge.error(`\n[gjsify flatpak check] ${I} check(s) failed.`),process.exit(1);ge.log(`[gjsify flatpak check] all checks passed.`)}}});async function readSourceListAtTag(t,n,S,C){let N;try{let{stdout:C}=await HV(`git`,[`show`,`${n}:${S}`],{cwd:t,maxBuffer:64*1024*1024});N=C}catch(N){return await assertGitMeantAbsent(t,n,S,N),C&&ge.log(`[gjsify flatpak sync-flathub] ${S} not present at ${n} — skipping`),null}if(N.trim()===``)return C&&ge.log(`[gjsify flatpak sync-flathub] ${S} is empty at ${n} — skipping`),null;let F;try{F=JSON.parse(N)}catch(t){throw Error(`[gjsify flatpak sync-flathub] ${S} at ${n} is not JSON: `+(t instanceof Error?t.message:String(t)))}if(!Array.isArray(F)||F.length===0)throw Error(`[gjsify flatpak sync-flathub] ${S} at ${n} is not a non-empty array of flatpak sources`);return N}async function assertGitMeantAbsent(t,n,S,C){if(typeof C?.code!=`number`)throw Error(`[gjsify flatpak sync-flathub] could not run \`git show ${n}:${S}\` — `+(C instanceof Error?C.message:String(C)));if(!await HV(`git`,[`rev-parse`,`--verify`,`--quiet`,`${n}^{commit}`],{cwd:t}).then(({stdout:t})=>t.trim()).catch(()=>``))throw Error(`[gjsify flatpak sync-flathub] ${n} does not resolve in ${t}, so whether it carries ${S} is unanswered. Run \`git fetch --tags\`, pass --version <an existing tag>, or run from the app checkout.`)}async function resolveLatestTag$1(t,n){try{let{stdout:S}=await HV(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:t});return n&&ge.log(`[gjsify flatpak sync-flathub] resolved latest tag → ${S.trim()}`),S.trim()||null}catch{return null}}async function resolveCommitForTag(t,n,S){try{let{stdout:C}=await HV(`git`,[`rev-list`,`-n`,`1`,n],{cwd:t}),N=C.trim();if(!N)throw Error(`empty rev-list output`);return S&&ge.log(`[gjsify flatpak sync-flathub] resolved ${n} → ${N}`),N}catch(t){throw Error(`[gjsify flatpak sync-flathub] tag ${n} not found locally. Run \`git fetch --tags\` or pass --commit <sha>.\n underlying error: ${t instanceof Error?t.message:String(t)}`)}}function normaliseBranchSegment(t){return t.replace(/^v/,``).replace(/[^A-Za-z0-9._-]/g,`-`)}function flathubCacheRoot(){return zn(process.env.XDG_CACHE_HOME||zn(homedir(),`.cache`),`gjsify`,`flathub-sync`)}async function ensureClone(t,n,S){if(existsSync(zn(t,`.git`))){S&&ge.log(`[gjsify flatpak sync-flathub] reusing clone at ${t}`),await gitInRepo(t,[`fetch`,`origin`],S);let n=await detectDefaultBranch(t,S);await gitInRepo(t,[`checkout`,n],S),await gitInRepo(t,[`reset`,`--hard`,`origin/${n}`],S);return}mkdirSync(In(t,`..`),{recursive:!0});let C=`https://github.com/${n}.git`;S&&ge.log(`[gjsify flatpak sync-flathub] git clone ${C} ${t}`);try{await HV(`git`,[`clone`,C,t])}catch(t){throw t?.code===`ENOENT`?Error("[gjsify flatpak sync-flathub] `git` not found. Install git from your distro (Fedora: `dnf install git`, Debian: `apt install git`)."):t}}async function detectDefaultBranch(t,n){try{let{stdout:S}=await HV(`git`,[`remote`,`show`,`origin`],{cwd:t}),C=S.match(/HEAD branch: (\S+)/);if(C&&C[1]&&C[1]!==`(unknown)`)return n&&ge.log(`[gjsify flatpak sync-flathub] default branch → ${C[1]}`),C[1]}catch{}return`master`}async function gitInRepo(t,n,S){S&&ge.log(`[gjsify flatpak sync-flathub] git ${n.join(` `)} (in ${t})`);let C=await spawnToCompletion(`git`,n,{completion:`return`,cwd:t,notFound:()=>Error("[gjsify flatpak sync-flathub] `git` not found. Install it from your distro.")});if(C.code!==0)throw Error(`git ${n[0]} exited ${describeExit(C)}`)}async function ghCreate(t,n,S,C,N,F){let I=[`pr`,`create`,`--repo`,n,`--head`,S,`--title`,`Update to ${C}`,`--body`,N];F&&ge.log(`[gjsify flatpak sync-flathub] gh ${I.join(` `)} (in ${t})`);let H=await spawnToCompletion(`gh`,I,{completion:`return`,cwd:t,notFound:()=>Error("[gjsify flatpak sync-flathub] `gh` (GitHub CLI) not found. Install via `dnf install gh` (Fedora), `apt install gh` (Debian/Ubuntu), or `flatpak install -y flathub com.github.cli`.")});if(H.code!==0)throw Error(`gh pr create exited ${describeExit(H)}`)}function editManifest(t,n){let S=JSON.parse(t),C=S.modules??[];if(C.length===0)throw Error(`[gjsify flatpak sync-flathub] manifest has no modules`);let N=C[0].sources??[];if(N.length===0)throw Error(`[gjsify flatpak sync-flathub] modules[0] has no sources`);let isObject=t=>typeof t==`object`,F=n.sourceIndex??N.findIndex(t=>isObject(t)&&t.type===`git`);if(F<0||F>=N.length)throw Error(`[gjsify flatpak sync-flathub] no git source found in modules[0].sources (use --source-index <n>)`);let I=N[F];if(!isObject(I)||I.type!==`git`){let t=isObject(I)?`type is "${I.type}"`:`is the file reference "${I}"`;throw Error(`[gjsify flatpak sync-flathub] modules[0].sources[${F}] ${t}, expected a git source`)}let H=I;H.tag=n.tag,H.commit=n.commit,H[`x-checker-data`]||={type:`git`,"tag-pattern":`^v(\\d+\\.\\d+\\.\\d+)$`,"version-scheme":`semantic`},n.sourcesFile&&!namesFile(N,n.sourcesFile)&&N.push(n.sourcesFile);let W=detectIndent$1(t);return JSON.stringify(S,null,W)+(t.endsWith(`
1114
+ `}var jV,MV=__esmMin(()=>{_e(),rf(),Xn(),pR(),rV(),oV(),lV(),jV={command:`ci`,description:`Scaffold .github/workflows/flatpak.yml using the flathub-infra container + flatpak-builder@v6 action.`,builder:t=>t.option(`manifest`,{description:`Manifest path the workflow points at (default: <app-id>.json)`,type:`string`,normalize:!0}).option(`bundle`,{description:`Bundle filename produced by the action (default: <app-id>.flatpak)`,type:`string`,normalize:!0}).option(`runtime-image`,{description:"Container image override. Default derived from gjsify.flatpak.runtime + runtimeVersion (e.g. `ghcr.io/flathub-infra/flatpak-github-actions:gnome-50`).",type:`string`}).option(`branches`,{description:`Branches the workflow runs on push for (default: main)`,type:`string`,array:!0}).option(`out`,{description:`Output path`,type:`string`,default:`.github/workflows/flatpak.yml`,normalize:!0}).option(`cache-key`,{description:"Override the action `cache-key` (default: `flatpak-builder-${{ github.sha }}`)",type:`string`}).option(`force`,{description:`Overwrite an existing workflow file`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print resolved fields`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=await new Config().forCommand().catch(()=>({})),C=S.flatpak??{},N=readPackageJson(n),F=C.appId??(looksLikeAppId(N.name)?N.name:void 0);if(!F)throw Error(`gjsify flatpak ci: no app id available. Set gjsify.flatpak.appId in package.json or rename the package to a reverse-DNS id.`);let I=t.manifest??`${F}.json`,H=t.bundle??`${F}.flatpak`,W=pickFlatpakBuildKeys(S.ship?.flatpak,C).values,{runtime:q,runtimeVersion:Y}=resolveRuntime(W,{}),X=t.runtimeImage??C.ciContainer??defaultCiContainer(q,Y),Z=t.branches??C.ciBranches??[`main`],te=t.cacheKey??"flatpak-builder-${{ github.sha }}",ne=In(n,t.out??`.github/workflows/flatpak.yml`);if(existsSync(ne)&&!t.force){if(readFileSync(ne,`utf-8`)===renderWorkflow({manifest:I,bundle:H,runtimeImage:X,branches:Z,cacheKey:te})){ge.log(`[gjsify flatpak ci] ${ne} already up to date`);return}throw Error(`gjsify flatpak ci: ${ne} exists with different content. Pass --force to overwrite.`)}let re=renderWorkflow({manifest:I,bundle:H,runtimeImage:X,branches:Z,cacheKey:te});mkdirSync(Hn(ne),{recursive:!0}),writeFileSync(ne,re,`utf-8`),t.verbose&&ge.log(`[gjsify flatpak ci] runtime-image=${X} manifest=${I} bundle=${H}`),ge.log(`[gjsify flatpak ci] wrote ${ne}`)}}});function buildTree$1(t){let n={name:`#root`,attrs:{},children:[],text:``},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)for(let t of S)t.text+=n.text;else if(n.kind===`open`){let C={name:LV(n.name),attrs:n.attributes,children:[],text:``};t.children.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function localized(t,n){let S=new Map;for(let C of kids(t,n)){let t=RV(C.text);t!==``&&!S.has(lang(C))&&S.set(lang(C),t)}return S}function parseHex(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];S.length===3&&(S=S.replace(/./g,t=>t+t));let C=Number.parseInt(S.slice(0,2),16)/255,N=Number.parseInt(S.slice(2,4),16)/255,F=Number.parseInt(S.slice(4,6),16)/255,I=Math.max(C,N,F),H=Math.min(C,N,F),W=(I+H)/2,q=I-H;return{s:q===0?0:q/(1-Math.abs(2*W-1)),l:W}}function readImageInfo(t){if(t.length>=24&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){let u32=n=>(t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3])>>>0;return{kind:`raster`,width:u32(16),height:u32(20)}}if(t.length>=4&&t[0]===255&&t[1]===216){let n=2;for(;n+9<t.length;){if(t[n]!==255){n++;continue}let S=t[n+1];if(S===255){n++;continue}if(S>=192&&S<=207&&S!==196&&S!==200&&S!==204)return{kind:`raster`,height:t[n+5]<<8|t[n+6],width:t[n+7]<<8|t[n+8]};n+=2+(t[n+2]<<8|t[n+3])}return null}let n=``;for(let S=0;S<Math.min(t.length,1024);S++)n+=String.fromCharCode(t[S]);return/<svg[\s>]/.test(n)?{kind:`svg`}:null}function termPattern(t,n=`iu`){let S=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`).replace(/\s+/g,`\\s+`);return RegExp(`(^|[^\\p{L}\\p{N}])${S}($|[^\\p{L}\\p{N}])`,n)}async function lintMetainfo(t,n={}){let S=[],add=(t,n,C,N,F)=>{S.push({rule:t,severity:n,message:F,location:N,url:`${NV}#${C}`})},C=child(buildTree$1(t),`component`);if(C===void 0)return add(`no-component`,`error`,`app-name`,`document`,`no <component> element found`),S;let loc=(t,n)=>n===``?t:`${t}[${n}]`,N=localized(C,`name`),F=localized(C,`summary`);for(let[t,n]of N){let S=loc(`name`,t),C=[...n].length;if(C>=20?add(`name-too-long`,`error`,`not-too-long`,S,`"${n}" is ${C} characters; a name must be shorter than 20`):C>15&&add(`name-long`,`warning`,`not-too-long`,S,`"${n}" is ${C} characters; ideally at most 15`),/\s[-–—:]\s|:\s|\(.+\)/.test(n)||/\b(web browser|editor|client|viewer|player)$/i.test(n)&&n.includes(` `))add(`name-extra-info`,`warning`,`just-the-name`,S,`"${n}" carries a description; keep just the name and put the rest in the summary`);else if(/[.-]/.test(n))add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" contains a dot or dash; avoid punctuation in names`);else if(/\p{L}/u.test(n)){let t=n.replace(/[^\p{L}]/gu,``);n===n.toLowerCase()?add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is all lowercase`):t.length>1&&n===n.toUpperCase()?add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is all uppercase (exempt only for an established brand such as VLC)`):!/\s/.test(n)&&/\p{Ll}\p{Lu}/u.test(n)&&add(`name-formatting`,`warning`,`no-weird-formatting`,S,`"${n}" is camel/pascal case`)}}let I=(n.technicalTerms??[...PV]).map(t=>({term:t,re:termPattern(t)}));for(let[t,n]of F){let S=loc(`summary`,t),C=[...n].length;C>35?add(`summary-too-long`,`error`,`not-too-long-1`,S,`"${n}" is ${C} characters; at most 35 allowed`):(C>25||C<10)&&add(`summary-length`,`warning`,`not-too-long-1`,S,`"${n}" is ${C} characters; ideal is 10 to 25`),/[.。]$/.test(n)&&add(`summary-full-stop`,`warning`,`no-weird-formatting-1`,S,`a summary does not end with a full stop`);let F=n.split(/\s+/).filter(t=>/^\p{L}/u.test(t)),H=F.filter(t=>/^\p{Lu}/u.test(t)).length;F.length>=3&&H/F.length>=.75&&add(`summary-title-case`,`warning`,`no-weird-formatting-1`,S,`use sentence case, not Title Case`);let W=IV[langBase(t===``?`en`:t)],q=n.split(/\s+/)[0]?.toLowerCase();W?.includes(q)&&add(`summary-article`,`warning`,`dont-start-with-an-article`,S,`starts with the article "${q}"; omit it or phrase it with a verb`);let Y=N.get(t)??N.get(``);Y!==void 0&&[...Y].length>=3&&termPattern(Y,`u`).test(n)&&add(`summary-repeats-name`,`warning`,`dont-repeat-the-name`,S,`repeats the app name "${Y}"`);let X=I.find(({re:t})=>t.test(n));X!==void 0&&add(`summary-technical`,`warning`,`not-technical`,S,`mentions "${X.term}"; say what the app does for people, not how it is built`)}let H=kids(C,`description`).find(t=>lang(t)===``)??child(C,`description`);if(H!==void 0){let t=F.get(``)??``,n=kids(H,`p`).filter(t=>lang(t)===``).map(t=>RV(t.text)),S=n.join(` `);t!==``&&n.length>0&&n[0].replace(/[.!]$/,``).toLowerCase()===t.toLowerCase()&&add(`description-repeats-summary`,`warning`,`dont-repeat-the-summary`,`description`,`the first paragraph repeats the summary`),t!==``&&[...S].length<Math.max(80,3*[...t].length)&&add(`description-short`,`warning`,`not-too-short`,`description`,`${[...S].length} characters; it should be substantially longer than the summary`);for(let t of[...kids(H,`ul`),...kids(H,`ol`)]){let n=kids(t,`li`).filter(t=>lang(t)===``).length;n>10&&add(`description-long-list`,`warning`,`no-super-long-lists`,`description`,`a list with ${n} items; group them or use paragraphs (max 10)`)}}let W=kids(child(C,`branding`),`color`).filter(t=>t.attrs.type===`primary`),q=W.find(t=>t.attrs.scheme_preference===`light`),Y=W.find(t=>t.attrs.scheme_preference===`dark`);if(q===void 0||Y===void 0)add(`branding-missing`,`warning`,`has-primary-brand-colors`,`branding`,`set two primary brand colors, scheme_preference="light" and "dark"`);else{let t=RV(q.text).toLowerCase(),n=RV(Y.text).toLowerCase();t===n&&add(`branding-identical`,`warning`,`good-brand-colors`,`branding`,`light and dark primary colors are the same`);let S=parseHex(t),C=parseHex(n);for(let[N,F,I]of[[`light`,S,t],[`dark`,C,n]])F!==null&&(F.s<.15||F.l>.93||F.l<.07)&&add(`branding-dull`,`warning`,`good-brand-colors`,`branding/${N}`,`${I} is near white, black or gray; brand colors should be colorful`);S!==null&&C!==null&&t!==n&&C.l>=S.l&&add(`branding-dark-not-darker`,`warning`,`good-brand-colors`,`branding/dark`,`the dark variant should be darker than the light one`)}if(n.probeImage!==void 0)for(let t of n.iconRefs??[]){let S=await n.probeImage(t);if(S!==null){S.kind===`raster`&&(S.width===S.height?S.width<256&&add(`icon-too-small`,`error`,`icon-size`,`icon`,`${t} is ${S.width}×${S.height}; use SVG or at least 256×256`):add(`icon-not-square`,`error`,`icon-size`,`icon`,`${t} is ${S.width}×${S.height}; the icon has to be square`));break}}let X=kids(child(C,`screenshots`),`screenshot`);if(X.length===0)add(`screenshot-missing`,`warning`,`at-least-one-screenshot`,`screenshots`,`at least one screenshot is expected`);else{let englishTag=t=>t===``||langBase(t)===`en`,isEnglish=t=>{let n=kids(t,`image`).map(lang);return englishTag(lang(t))&&(n.length===0||n.some(englishTag))};X.some(isEnglish)||add(`screenshot-no-english`,`warning`,`at-least-one-screenshot`,`screenshots`,`no screenshot without xml:lang (or in English)`),X[0].attrs.type!=="default"&&add(`screenshot-default-not-first`,`warning`,`at-least-one-screenshot`,`screenshot[1]`,`the first screenshot should be type="default" — it is the one users see first`);for(let t=0;t<X.length;t++){let S=X[t],C=`screenshot[${t+1}]`,N=kids(S,`caption`);N.length===0&&add(`screenshot-caption-missing`,`warning`,`image-captions`,C,`no <caption>`);for(let t of N){let n=RV(t.text),S=`${C}/${loc(`caption`,lang(t))}`;/[.。]$/.test(n)&&add(`caption-full-stop`,`warning`,`image-captions`,S,`a caption does not end with a full stop`),/^\d/.test(n)&&add(`caption-starts-with-number`,`warning`,`image-captions`,S,`a caption does not start with a number`),/[.!?]\s+\p{Lu}/u.test(n)&&add(`caption-multiple-sentences`,`warning`,`image-captions`,S,`a caption is one sentence`)}if(n.probeImage!==void 0){let t=kids(S,`image`).find(t=>(t.attrs.type??`source`)===`source`),N=t===void 0?``:RV(t.text),F=N===``?null:await n.probeImage(N);F?.kind===`raster`&&(F.width>2e3||F.height>1400)&&add(`screenshot-too-large`,`warning`,`reasonable-window-size`,C,`${F.width}×${F.height}; keep the window at most 1000×700 (2000×1400 on HiDPI)`)}}}for(let t of kids(child(C,`releases`),`release`)){let n=`release ${t.attrs.version??`?`}`,S=child(t,`description`),C=S===void 0?``:RV(S.text);if(C===``){add(`release-notes-missing`,`warning`,`release-notes-for-every-release`,n,`no release notes`);continue}FV.some(t=>t.test(C.replace(/[.!]+$/,``)))?add(`release-notes-generic`,`warning`,`no-bug-fixes-and-performance-improvements`,n,`"${C}" says nothing about what changed`):([...C].length>600||kids(child(S,`ul`),`li`).length>10)&&add(`release-notes-long`,`warning`,`short-but-informative`,n,`release notes are long; summarise what changed for users`)}return S}function summarizeFindings(t,n){let S=0,C=0;for(let N of t)N.severity===`error`||n?S++:C++;return{errors:S,warnings:C}}function formatFinding(t,n){return`${(n?`error`:t.severity).padEnd(7)} ${t.rule} ${t.location}: ${t.message}\n ${t.url}`}var NV,PV,FV,IV,LV,child,kids,RV,lang,langBase,zV=__esmMin(()=>{Ye(),NV=`https://docs.flathub.org/docs/for-app-authors/metainfo-guidelines/quality-guidelines`,PV=`GTK.GTK3.GTK4.Qt.Qt5.Qt6.libadwaita.Electron.Rust.Python.JavaScript.TypeScript.GJS.Flatpak.written in.open source.open-source.free software.FOSS.app.application.tool.client.wrapper.App.Anwendung.Werkzeug`.split(`.`),FV=[/^(minor |various |general |misc(ellaneous)? )?bug ?fix(es)?( (and|&) (minor )?(performance )?(improvements?|fixes|tweaks))?$/i,/^(minor |various |general )?(performance )?improvements?( (and|&) (bug ?fix(es)?|fixes))?$/i,/^bug ?fix(es)?,? (and )?(performance|stability) improvements?$/i,/^(performance|stability) (improvements?|fixes)( (and|&) bug ?fix(es)?)?$/i,/^(fehlerbehebungen?|fehlerkorrekturen?|verbesserungen)( (und|&) (fehlerbehebungen?|verbesserungen|leistungsverbesserungen))?$/i,/^(kleinere )?(fehlerbehebungen|verbesserungen)$/i],IV={en:[`a`,`an`,`the`],de:[`ein`,`eine`,`einen`,`einem`,`einer`,`der`,`die`,`das`,`den`,`dem`]},LV=__name$1(t=>t.startsWith(`_`)?t.slice(1):t,`normName`),__name$1(buildTree$1,`buildTree`),child=(t,n)=>t?.children.find(t=>t.name===n),kids=(t,n)=>t?.children.filter(t=>t.name===n)??[],RV=__name$1(t=>t.replace(/\s+/g,` `).trim(),`clean`),lang=t=>t.attrs[`xml:lang`]??``,langBase=t=>t.split(/[_\-.@]/)[0].toLowerCase()});function appstreamValidateArgs(t,n=!1){return[`validate`,`--strict`,...n?[]:[`--no-net`],t]}async function runQuality(t,n,S){let C=Hn(t),probeImage=async t=>{if(/^https?:\/\//.test(t)){if(!S.qualityNetwork)return null;try{let n=await fetch(t);return n.ok?readImageInfo(new Uint8Array(await n.arrayBuffer())):null}catch{return null}}let n=In(C,t);return existsSync(n)?readImageInfo(new Uint8Array(readFileSync(n))):null},N=n??``,F=N?[`icons/hicolor/scalable/apps/${N}.svg`,`icons/${N}.svg`,`${N}.svg`,`${N}.png`,`../data/icons/hicolor/scalable/apps/${N}.svg`]:[],I=await lintMetainfo(readFileSync(t,`utf-8`),{probeImage,iconRefs:F}),H=S.strict===!0,{errors:W,warnings:q}=summarizeFindings(I,H);if(S.json)ge.log(JSON.stringify({file:t,errors:W,warnings:q,findings:I.map(t=>({...t,severity:H?`error`:t.severity}))},null,2));else{for(let t of I)ge.log(formatFinding(t,H));ge.log(`[gjsify flatpak check] ${W===0?`OK`:`FAIL`}: quality ${t} — ${W} error(s), ${q} warning(s)`)}return W===0}function resolveAppId(t,n,S){if(n.appId)return n.appId;try{let t=readPackageJson(S);if(looksLikeAppId(t.name))return t.name}catch{}if(t)return t.replace(/\.json$/,``)}function resolveManifestPath(t,n,S){if(t)return In(S,t);if(n)return In(S,`${n}.json`);let C=readdirSync(S).filter(t=>t.endsWith(`.json`)&&!t.startsWith(`package`));if(C.length===1)return In(S,C[0]);throw Error(`gjsify flatpak check: no manifest path given and could not auto-detect. Pass the manifest as a positional argument.`)}async function runLinter(t,n,S){let C;try{C=await spawnToCompletion(t,n,{completion:`return`,stdio:S?`inherit`:`capture`})}catch(n){let S=n;return S.code===`ENOENT`?ge.error(`[gjsify flatpak check] ${t} not found in PATH.\nInstall via:\n flatpak install -y flathub org.flatpak.Builder\n alias ${t}="flatpak run --command=${t} org.flatpak.Builder"`):ge.error(`[gjsify flatpak check] ${t} failed to spawn: ${S.message}`),!1}let N=C.code===0;return ge.log(`[gjsify flatpak check] ${N?`OK`:`FAIL`}: ${t} ${n.join(` `)}`),!N&&!S&&(C.stdout?.trim()&&ge.log(C.stdout.trimEnd()),C.stderr?.trim()&&ge.error(C.stderr.trimEnd())),N}var BV,VV=__esmMin(()=>{_e(),rf(),Xn(),mv(),rV(),pR(),zV(),BV={command:`check [manifest]`,description:`Run Flathub pre-submission linters: appstreamcli validate + flatpak-builder-lint.`,builder:t=>t.positional(`manifest`,{description:"Path to the Flatpak manifest. Auto-detects `<app-id>.json` if omitted.",type:`string`,normalize:!0}).option(`repo`,{description:"Built ostree-repo path. If given, also runs `flatpak-builder-lint repo`.",type:`string`,normalize:!0}).option(`metainfo`,{description:"MetaInfo XML path. Default: `data/<app-id>.metainfo.xml.in`.",type:`string`,normalize:!0}).option(`appstream`,{description:"Run `appstreamcli validate --strict --no-net` (default: true).",type:`boolean`,default:!0}).option(`quality`,{description:`Run Flathub's quality guidelines (name, summary, branding, screenshots, release notes) on the MetaInfo (default: true).`,type:`boolean`,default:!0}).option(`strict`,{description:`Treat quality warnings as errors.`,type:`boolean`,default:!1}).option(`json`,{description:`Print the quality findings as JSON (and nothing else on stdout).`,type:`boolean`,default:!1}).option(`quality-network`,{description:`Let the quality check fetch http(s) screenshot/icon URLs to measure their size.`,type:`boolean`,default:!1}).option(`appstream-network`,{description:"Let `appstreamcli` fetch the MetaInfo URLs to check they are reachable.",type:`boolean`,default:!1}).option(`builder-lint`,{description:"Run `flatpak-builder-lint manifest` (default: true).",type:`boolean`,default:!0}).option(`verbose`,{description:`Stream linter stdout/stderr verbatim.`,type:`boolean`,default:!1}),handler:async t=>{let n=(await new Config().forCommand().catch(()=>({}))).flatpak??{},S=process.cwd(),C=resolveAppId(t.manifest,n,S),N=resolveManifestPath(t.manifest,C,S),F=In(S,t.metainfo??`data/${C??`unknown`}.metainfo.xml.in`),I=0;if(t.appstream!==!1&&(existsSync(F)?await runLinter(`appstreamcli`,appstreamValidateArgs(F,t.appstreamNetwork===!0),t.verbose??!1)||I++:ge.warn(`[gjsify flatpak check] skipping appstreamcli — ${F} not found`)),t.quality!==!1&&(existsSync(F)?await runQuality(F,C,t)||I++:ge.warn(`[gjsify flatpak check] skipping quality check — ${F} not found`)),t.builderLint!==!1&&!t.json){if(!existsSync(N))return ge.error(`[gjsify flatpak check] manifest not found: ${N}`),process.exit(1);await runLinter(`flatpak-builder-lint`,[`manifest`,N],t.verbose??!1)||I++,t.repo&&(await runLinter(`flatpak-builder-lint`,[`repo`,In(S,t.repo)],t.verbose??!1)||I++)}if(I>0)return ge.error(`\n[gjsify flatpak check] ${I} check(s) failed.`),process.exit(1);ge.log(`[gjsify flatpak check] all checks passed.`)}}});async function readSourceListAtTag(t,n,S,C){let N;try{let{stdout:C}=await HV(`git`,[`show`,`${n}:${S}`],{cwd:t,maxBuffer:64*1024*1024});N=C}catch(N){return await assertGitMeantAbsent(t,n,S,N),C&&ge.log(`[gjsify flatpak sync-flathub] ${S} not present at ${n} — skipping`),null}if(N.trim()===``)return C&&ge.log(`[gjsify flatpak sync-flathub] ${S} is empty at ${n} — skipping`),null;let F;try{F=JSON.parse(N)}catch(t){throw Error(`[gjsify flatpak sync-flathub] ${S} at ${n} is not JSON: `+(t instanceof Error?t.message:String(t)))}if(!Array.isArray(F)||F.length===0)throw Error(`[gjsify flatpak sync-flathub] ${S} at ${n} is not a non-empty array of flatpak sources`);return N}async function assertGitMeantAbsent(t,n,S,C){if(typeof C?.code!=`number`)throw Error(`[gjsify flatpak sync-flathub] could not run \`git show ${n}:${S}\` — `+(C instanceof Error?C.message:String(C)));if(!await HV(`git`,[`rev-parse`,`--verify`,`--quiet`,`${n}^{commit}`],{cwd:t}).then(({stdout:t})=>t.trim()).catch(()=>``))throw Error(`[gjsify flatpak sync-flathub] ${n} does not resolve in ${t}, so whether it carries ${S} is unanswered. Run \`git fetch --tags\`, pass --version <an existing tag>, or run from the app checkout.`)}async function resolveLatestTag$1(t,n){try{let{stdout:S}=await HV(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:t});return n&&ge.log(`[gjsify flatpak sync-flathub] resolved latest tag → ${S.trim()}`),S.trim()||null}catch{return null}}async function resolveCommitForTag(t,n,S){try{let{stdout:C}=await HV(`git`,[`rev-list`,`-n`,`1`,n],{cwd:t}),N=C.trim();if(!N)throw Error(`empty rev-list output`);return S&&ge.log(`[gjsify flatpak sync-flathub] resolved ${n} → ${N}`),N}catch(t){throw Error(`[gjsify flatpak sync-flathub] tag ${n} not found locally. Run \`git fetch --tags\` or pass --commit <sha>.\n underlying error: ${t instanceof Error?t.message:String(t)}`)}}function normaliseBranchSegment(t){return t.replace(/^v/,``).replace(/[^A-Za-z0-9._-]/g,`-`)}function flathubCacheRoot(){return zn(process.env.XDG_CACHE_HOME||zn(homedir(),`.cache`),`gjsify`,`flathub-sync`)}async function ensureClone(t,n,S){if(existsSync(zn(t,`.git`))){S&&ge.log(`[gjsify flatpak sync-flathub] reusing clone at ${t}`),await gitInRepo(t,[`fetch`,`origin`],S);let n=await detectDefaultBranch(t,S);await gitInRepo(t,[`checkout`,n],S),await gitInRepo(t,[`reset`,`--hard`,`origin/${n}`],S);return}mkdirSync(In(t,`..`),{recursive:!0});let C=`https://github.com/${n}.git`;S&&ge.log(`[gjsify flatpak sync-flathub] git clone ${C} ${t}`);try{await HV(`git`,[`clone`,C,t])}catch(t){throw t?.code===`ENOENT`?Error("[gjsify flatpak sync-flathub] `git` not found. Install git from your distro (Fedora: `dnf install git`, Debian: `apt install git`)."):t}}async function detectDefaultBranch(t,n){try{let{stdout:S}=await HV(`git`,[`remote`,`show`,`origin`],{cwd:t}),C=S.match(/HEAD branch: (\S+)/);if(C&&C[1]&&C[1]!==`(unknown)`)return n&&ge.log(`[gjsify flatpak sync-flathub] default branch → ${C[1]}`),C[1]}catch{}return`master`}async function gitInRepo(t,n,S){S&&ge.log(`[gjsify flatpak sync-flathub] git ${n.join(` `)} (in ${t})`);let C=await spawnToCompletion(`git`,n,{completion:`return`,cwd:t,notFound:()=>Error("[gjsify flatpak sync-flathub] `git` not found. Install it from your distro.")});if(C.code!==0)throw Error(`git ${n[0]} exited ${describeExit(C)}`)}async function ghCreate(t,n,S,C,N,F){let I=[`pr`,`create`,`--repo`,n,`--head`,S,`--title`,`Update to ${C}`,`--body`,N];F&&ge.log(`[gjsify flatpak sync-flathub] gh ${I.join(` `)} (in ${t})`);let H=await spawnToCompletion(`gh`,I,{completion:`return`,cwd:t,notFound:()=>Error("[gjsify flatpak sync-flathub] `gh` (GitHub CLI) not found. Install via `dnf install gh` (Fedora), `apt install gh` (Debian/Ubuntu), or `flatpak install -y flathub com.github.cli`.")});if(H.code!==0)throw Error(`gh pr create exited ${describeExit(H)}`)}function editManifest(t,n){let S=JSON.parse(t),C=S.modules??[];if(C.length===0)throw Error(`[gjsify flatpak sync-flathub] manifest has no modules`);let N=C[0].sources??[];if(N.length===0)throw Error(`[gjsify flatpak sync-flathub] modules[0] has no sources`);let isObject=t=>typeof t==`object`,F=n.sourceIndex??N.findIndex(t=>isObject(t)&&t.type===`git`);if(F<0||F>=N.length)throw Error(`[gjsify flatpak sync-flathub] no git source found in modules[0].sources (use --source-index <n>)`);let I=N[F];if(!isObject(I)||I.type!==`git`){let t=isObject(I)?`type is "${I.type}"`:`is the file reference "${I}"`;throw Error(`[gjsify flatpak sync-flathub] modules[0].sources[${F}] ${t}, expected a git source`)}let H=I;H.tag=n.tag,H.commit=n.commit,H[`x-checker-data`]||={type:`git`,"tag-pattern":`^v(\\d+\\.\\d+\\.\\d+)$`,"version-scheme":`semantic`},n.sourcesFile&&!namesFile(N,n.sourcesFile)&&N.push(n.sourcesFile);let W=detectIndent$1(t);return JSON.stringify(S,null,W)+(t.endsWith(`
1115
1115
  `)?`
1116
1116
  `:``)}function namesFile(t,n){let S=stripDotSlash(n);return t.some(t=>typeof t==`string`&&stripDotSlash(t)===S)}function stripDotSlash(t){return t.replace(/^\.\//,``)}function detectIndent$1(t){let n=t.match(/^\{\n( +)/);return n?n[1].length:2}var HV,UV,WV=__esmMin(()=>{_e(),rf(),Xn(),a_(),sv(),mv(),Hu(),pR(),rV(),HV=promisify(execFile),UV={command:`sync-flathub`,description:`Update the per-app Flathub tracking-repo manifest to a new git tag + commit. Clones, edits, commits, optionally opens a PR.`,builder:t=>t.version(!1).option(`version`,{description:"Git tag to sync to. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `flathub/<appId>`.",type:`string`}).option(`commit`,{description:"Commit SHA to pin. Default: resolved via `git rev-list -n 1 <version>` in cwd.",type:`string`}).option(`branch`,{description:"Branch name in the flathub-repo. Default: `update-to-<version>`.",type:`string`}).option(`sources-file`,{description:`Generated offline tarball list to carry into the Flathub repo and name in the manifest. Default: \`${nV}\`. Skipped when the tag does not carry it.`,type:`string`,default:nV}).option(`source-index`,{description:"Index into modules[0].sources[] to update (when manifest has multiple sources). Default: first `type: git` source.",type:`number`}).option(`pr`,{description:"After commit + push, open a PR via `gh pr create`. Pass `--no-pr` to skip and stop after push.",type:`boolean`,default:!0}).option(`dry-run`,{description:`Show what would be edited; touch no files, run no git commands.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every git / gh invocation before running.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=(await new Config().forCommand().catch(()=>({}))).flatpak??{},C=t.appId??S.appId??readPackageJson(n).name;if(!C)throw Error(`[gjsify flatpak sync-flathub] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let N=t.flathubRepo??S.flathubRepo??`flathub/${C}`,F=t.version??await resolveLatestTag$1(n,t.verbose);if(!F)throw Error(`[gjsify flatpak sync-flathub] no version resolved — pass --version vX.Y.Z or create a git tag locally.`);let I=t.commit??await resolveCommitForTag(n,F,t.verbose),H=t.branch??`update-to-${normaliseBranchSegment(F)}`;if(ge.log(`[gjsify flatpak sync-flathub] appId=${C}`),ge.log(`[gjsify flatpak sync-flathub] flathubRepo=${N}`),ge.log(`[gjsify flatpak sync-flathub] version=${F}`),ge.log(`[gjsify flatpak sync-flathub] commit=${I}`),ge.log(`[gjsify flatpak sync-flathub] branch=${H}`),t.dryRun){ge.log(`[gjsify flatpak sync-flathub] --dry-run set; not cloning / writing / pushing.`);return}let W=flathubCacheRoot(),q=zn(W,N.replace(`/`,`__`));mkdirSync(W,{recursive:!0}),await ensureClone(q,N,t.verbose);let Y=zn(q,`${C}.json`);if(!existsSync(Y))throw Error(`[gjsify flatpak sync-flathub] Flathub manifest not found at ${Y} — wrong appId / wrong flathub-repo?`);let X=t.sourcesFile??`gjsify-sources.json`,Z=await readSourceListAtTag(n,F,X,t.verbose),te=!1;if(Z!==null){let t=zn(q,X);te=!existsSync(t)||readFileSync(t,`utf-8`)!==Z,te&&(writeFileSync(t,Z,`utf-8`),ge.log(`[gjsify flatpak sync-flathub] ${X} copied from ${F}`))}let ne=readFileSync(Y,`utf-8`),re=editManifest(ne,{tag:F,commit:I,sourceIndex:t.sourceIndex,sourcesFile:Z===null?void 0:X});if(re===ne&&!te){ge.log(`[gjsify flatpak sync-flathub] manifest already at ${F} — nothing to do.`);return}if(writeFileSync(Y,re,`utf-8`),ge.log(`[gjsify flatpak sync-flathub] manifest patched at ${Y}`),await gitInRepo(q,[`checkout`,`-B`,H],t.verbose),await gitInRepo(q,[`add`,`.`],t.verbose),await gitInRepo(q,[`commit`,`-m`,`Update to ${F}`],t.verbose),t.pr===!1){ge.log(`[gjsify flatpak sync-flathub] --no-pr set; branch ${H} committed locally in ${q}.`);return}await gitInRepo(q,[`push`,`-u`,`origin`,H,`--force-with-lease`],t.verbose),await ghCreate(q,N,H,F,`Auto-generated by \`gjsify flatpak sync-flathub\`.\n\n- Version: \`${F}\`\n- Commit: \`${I}\`\n`,t.verbose)}},__name$1(resolveLatestTag$1,`resolveLatestTag`),__name$1(detectIndent$1,`detectIndent`)});async function loadFlathubSource(t,n){let S;if(t.against){if(!existsSync(t.against))throw Error(`[gjsify flatpak diff] --against path ${t.against} does not exist`);S=readFileSync(t.against,`utf-8`)}else S=await fetchFlathubManifest(t.flathubRepo,t.appId,t.verbose);let C;try{C=JSON.parse(S)}catch(t){throw Error(`[gjsify flatpak diff] failed to parse Flathub manifest as JSON: ${t.message}`)}let N=(C.modules??[])[0]?.sources??[];if(N.length===0)return null;let F=n??N.findIndex(t=>isSourceObject(t)&&t.type===`git`);if(F<0||F>=N.length)return null;let I=N[F];return isSourceObject(I)?I:null}function isSourceObject(t){return typeof t==`object`&&!!t}async function fetchFlathubManifest(t,n,S){for(let C of[`master`,`main`]){let N=`https://raw.githubusercontent.com/${t}/${C}/${n}.json`;S&&ge.log(`[gjsify flatpak diff] fetch ${N}`);try{let t=await fetch(N);if(t.ok)return await t.text();S&&ge.log(`[gjsify flatpak diff] ${C} → HTTP ${t.status}`)}catch(t){S&&ge.log(`[gjsify flatpak diff] ${C} fetch error: ${t.message}`)}}throw Error(`[gjsify flatpak diff] could not fetch flathub manifest from ${t} on master or main`)}async function resolveLatestTag(t,n){try{let{stdout:S}=await GV(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:t}),C=S.trim();return n&&ge.log(`[gjsify flatpak diff] local latest tag → ${C}`),C||null}catch{return null}}var GV,KV,qV=__esmMin(()=>{_e(),rf(),sv(),Hu(),pR(),rV(),GV=promisify(execFile),KV={command:`diff`,description:`Compare the per-app Flathub tracking-repo manifest against the local git state and report version / commit drift.`,builder:t=>t.version(!1).option(`version`,{description:"Local version to compare against. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `gjsify.flatpak.flathubRepo` or `flathub/<appId>`.",type:`string`}).option(`against`,{description:`Read the Flathub manifest from a local file instead of fetching it. Useful in CI or offline.`,type:`string`}).option(`detail`,{description:`Also print the full Flathub manifest source entry alongside the resolved local version.`,type:`boolean`,default:!1}).option(`source-index`,{description:`Index into modules[0].sources[] to inspect (when the manifest has multiple sources).`,type:`number`}).option(`verbose`,{description:`Echo fetch URL + resolved values.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=(await new Config().forCommand().catch(()=>({}))).flatpak??{},C=t.appId??S.appId??readPackageJson(n).name;if(!C)throw Error(`[gjsify flatpak diff] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let N=t.flathubRepo??S.flathubRepo??`flathub/${C}`,F=t.version??await resolveLatestTag(n,t.verbose),I=await loadFlathubSource({appId:C,flathubRepo:N,against:t.against,verbose:t.verbose},t.sourceIndex),H=I?.tag,W=I?.commit;if(ge.log(`[gjsify flatpak diff] appId=${C}`),ge.log(`[gjsify flatpak diff] flathubRepo=${N}`),ge.log(`[gjsify flatpak diff] flathub: tag=${H??`(missing)`} commit=${W??`(missing)`}`),ge.log(`[gjsify flatpak diff] local: tag=${F??`(none)`}`),t.detail&&I&&(ge.log(`[gjsify flatpak diff] flathub manifest source:`),ge.log(JSON.stringify(I,null,2))),!F){ge.warn("[gjsify flatpak diff] no local git tag found — cut a release (`git tag vX.Y.Z`) or pass --version vX.Y.Z to compare against an explicit value.");return}if(!H)return ge.warn("[gjsify flatpak diff] flathub manifest has no `tag` field on the inspected source."),process.exit(1);if(H===F){ge.log(`✅ in sync (${F})`);return}ge.log(`❌ drift detected — flathub=${H} vs local=${F}`),ge.log(` run \`gjsify flatpak sync-flathub --version ${F}\` to update the Flathub manifest.`),process.exit(1)}}});function resolveCliEntry(){return In(In(Hn(fileURLToPath(import.meta.url)),`..`,`..`),`index.js`)}async function runNode(t,n){let S=await spawnToCompletion(`node`,t,{completion:`return`,cwd:n});if(S.code!==0)throw Error(`sub-command exited with ${describeExit(S)}: node ${t.join(` `)}`)}var JV,YV,XV=__esmMin(()=>{_e(),sv(),mv(),Hu(),cr(),Xn(),JV=promisify(execFile),YV={command:`release <version>`,description:"Cut a release end-to-end: regenerate Flathub assets, run linters, create + push the git tag, then open the Flathub PR. Each step delegates to the equivalent `gjsify flatpak <sub>` command.",builder:t=>t.version(!1).positional(`version`,{description:"Release tag, e.g. `v0.6.6`.",type:`string`,demandOption:!0}).option(`skip-init`,{description:"Skip the `flatpak init --force` regen step.",type:`boolean`,default:!1}).option(`skip-check`,{description:"Skip the `flatpak check` linter step.",type:`boolean`,default:!1}).option(`skip-tag`,{description:"Skip the `git tag` + `git push --tags` step (use when the tag was already created out-of-band).",type:`boolean`,default:!1}).option(`push-tag`,{description:`Push the created tag after creating it. Default: true.`,type:`boolean`,default:!0}).option(`flathub-repo`,{description:`Flathub tracking-repo override forwarded to sync-flathub.`,type:`string`}).option(`dry-run`,{description:`Print each step that would run without executing any of them.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every sub-command invocation.`,type:`boolean`,default:!1}),handler:async t=>{let n=typeof t.version==`string`?t.version.trim():``;if(!n)throw Error(`[gjsify flatpak release] missing <version> positional`);let S=resolveCliEntry(),C=process.cwd(),N=[];t.skipInit||N.push({name:`init`,args:[S,`flatpak`,`init`,`--force`]}),t.skipCheck||N.push({name:`check`,args:[S,`flatpak`,`check`]});let F=[S,`flatpak`,`sync-flathub`,`--version`,n];if(t.flathubRepo&&F.push(`--flathub-repo`,t.flathubRepo),t.verbose&&F.push(`--verbose`),ge.log(`[gjsify flatpak release] starting release of ${n}`),t.dryRun){ge.log(`[gjsify flatpak release] --dry-run set; printing plan only:`);for(let t of N)ge.log(` · ${t.name}: node ${t.args.join(` `)}`);t.skipTag||ge.log(` · tag: git tag ${n}${t.pushTag===!1?``:` && git push origin `+n}`),ge.log(` · sync: node ${F.join(` `)}`);return}for(let n of N)t.verbose&&ge.log(`[gjsify flatpak release] step ${n.name}: node ${n.args.join(` `)}`),await runNode(n.args,C),ge.log(`[gjsify flatpak release] ${n.name} ✔`);if(!t.skipTag){t.verbose&&ge.log(`[gjsify flatpak release] git tag ${n}`);try{await JV(`git`,[`tag`,n],{cwd:C}),ge.log(`[gjsify flatpak release] tag ${n} created`)}catch(t){throw Error(`[gjsify flatpak release] git tag failed (${t.message}). If the tag already exists, re-run with --skip-tag.`)}t.pushTag!==!1&&(t.verbose&&ge.log(`[gjsify flatpak release] git push origin ${n}`),await JV(`git`,[`push`,`origin`,n],{cwd:C}),ge.log(`[gjsify flatpak release] tag pushed`))}t.verbose&&ge.log(`[gjsify flatpak release] sync: node ${F.join(` `)}`),await runNode(F,C),ge.log(`[gjsify flatpak release] ✅ release ${n} complete`)}}}),ZV,QV=__esmMin(()=>{yV(),xV(),CV(),AV(),MV(),VV(),WV(),qV(),XV(),ZV={command:`flatpak <subcommand>`,description:`Flatpak toolchain: init/build/deps/sources/ci/check/sync-flathub/diff/release subcommands for shipping GJS apps and CLIs as Flatpaks.`,builder:t=>t.command(vV.command,vV.description,vV.builder,vV.handler).command(bV.command,bV.description,bV.builder,bV.handler).command(SV.command,SV.description,SV.builder,SV.handler).command(kV.command,kV.description,kV.builder,kV.handler).command(jV.command,jV.description,jV.builder,jV.handler).command(BV.command,BV.description,BV.builder,BV.handler).command(UV.command,UV.description,UV.builder,UV.handler).command(KV.command,KV.description,KV.builder,KV.handler).command(YV.command,YV.description,YV.builder,YV.handler).demandCommand(1).strict()}});function concatBytes(t){let n=0;for(let S of t)n+=S.byteLength;let S=new Uint8Array(n),C=0;for(let n of t)S.set(n,C),C+=n.byteLength;return S}function encodeUtf8(t){return new TextEncoder().encode(t)}var $V=__esmMin(()=>{});function createArArchive(t){let n=[encodeUtf8(eH)];for(let S of t)n.push(buildMemberHeader(S)),n.push(S.data),S.data.byteLength%2==1&&n.push(encodeUtf8(`
1117
1117
  `));return concatBytes(n)}function buildMemberHeader(t){let n=pad(t.name,16)+pad(String(t.mtime??0),12)+pad(`0`,6)+pad(`0`,6)+pad((t.mode??33188).toString(8),8)+pad(String(t.data.byteLength),10)+`\`
@@ -1165,7 +1165,7 @@ ${t.map(t=>{let n=[` <mime-type type="${xmlEscape(t.type)}">`,` <comment>${x
1165
1165
  `)}).join(`
1166
1166
  `)}
1167
1167
  </mime-info>
1168
- `}var bU,xU=__esmMin(()=>{yU(),bU=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/});function normaliseVersion(t){let n=[],S=t.trim();S.startsWith(`v`)&&(S=S.slice(1));let C=S.indexOf(`+`);C!==-1&&(n.push(`gjsify ship: dropped the build metadata "${S.slice(C)}" from version ${t} — neither dpkg nor rpm has a field for it. Set \`gjsify.ship.version\` to pin an exact package version.`),S=S.slice(0,C));let N=S.indexOf(`-`);if(N!==-1){let t=S.slice(N+1).replace(/-/g,`.`);S=`${S.slice(0,N)}~${t}`}if(!SU.test(S))throw Error(`gjsify ship: "${t}" is not a usable package version (normalised to "${S}"). It must start with a digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.version\` in package.json to override it.`);return{version:S,warnings:n}}function assertRelease(t){if(!CU.test(t))throw Error(`gjsify ship: "${t}" is not a usable package release. It must start with a letter or digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.release\` in package.json.`);return t}var SU,CU,wU=__esmMin(()=>{SU=/^\d[A-Za-z0-9.+~]*$/,CU=/^[A-Za-z0-9][A-Za-z0-9.+~]*$/});function resolveShipApp(t){let n=t.perTarget??{};for(let t of Object.keys(n))if(!Object.hasOwn(TU,t))throw Error(`gjsify ship: \`gjsify.ship.app.${t}\` is not an OS this command assembles for. Known: ${Object.keys(TU).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. A runtime under a key nothing reads leaves that target on \`gjsify.app\` with nothing to say so.`);let S=n[t.layoutOs],C=S!==void 0,N=C?`gjsify.ship.app.${t.layoutOs}`:`gjsify.app`,F=C?S:t.project;if(F!==void 0&&F!==`gjs`&&F!==`node`)throw Error(`gjsify ship: \`${N}\` is "${F}", and only \`gjs\` and \`node\` can be packaged. A browser bundle has no process to launch, and a NativeScript app ships as an APK/IPA through a different pipeline. ADR 0024 § 4 has the runtime-per-OS table.`);return{app:F===`node`?`node`:`gjs`,key:N,overridden:C}}function resolveShipKind(t,n){return t.kind??n.kind??`app`}function resolveShipSettings(t){let n=[],{pkg:S,ship:C,flatpak:N,discovered:F}=t,I={...N,...definedOnly(C)},H=C.mimeTypes??[];if(H.length>0){validateMimeTypes(H);let t=new Set([...I.provides?.mimetypes??[],...H.map(t=>t.type)]);I.provides={...I.provides,mimetypes:[...t]}}let W=C.binaryName??deriveBinaryName(S.name),q=C.appId??N.appId??reverseDnsOrThrow(S.name,W),Y=I.name??titleCase(W),X=resolveShipKind(C,N),Z=t.app,te=C.version??S.version;if(!te)throw Error("gjsify ship: no version — set `version` in package.json or `gjsify.ship.version`.");let ne=normaliseVersion(te);n.push(...ne.warnings);let re=I.license?.project??S.license;if(!re)throw Error('gjsify ship: no licence — set `license` in package.json (an SPDX id, e.g. "MIT") or `gjsify.ship.license.project`. Both deb and rpm carry it as a required field.');I.license={...I.license,project:re};let ie=C.maintainer??formatAuthor(S.author)??formatDeveloper(I);if(!ie)throw Error('gjsify ship: no maintainer — set `author` in package.json ("Name <you@example.com>"), `gjsify.ship.maintainer`, or `gjsify.ship.developer`. dpkg refuses a package without one.');let ae=I.summary??S.description??Y,oe=descriptionParagraphs(I.description)??[ae],Q=sectionsFor(I.categories);X===`app`&&F.iconFiles.length===0&&n.push("gjsify ship: no icon found — the installed app will show a placeholder in menus on Linux, the Flatpak will carry no catalogue icon for an app store to show, and the darwin and windows layouts refuse to stage without one. Point `gjsify.ship.icon` at an SVG (or a directory of sized PNGs).");let se=resolveShipFlatpakSettings({ship:C,flatpak:N,kind:X});n.push(...se.warnings);let ce=resolveShipNestedBundles({declared:C.nestedBundles,projectDir:t.projectDir,layoutOs:t.cli.layoutOs}),le=resolveShipHelperExecutables({declared:C.helperExecutables,projectDir:t.projectDir,layoutOs:t.cli.layoutOs}),ue=resolveShipMainExecutable({declared:C.mainExecutable,projectDir:t.projectDir,layoutOs:t.cli.layoutOs});if(t.cli.layoutOs!==`darwin`){let S=[...Array.isArray(C.nestedBundles)&&C.nestedBundles.length>0?[`nestedBundles`]:[],...Array.isArray(C.helperExecutables)&&C.helperExecutables.length>0?[`helperExecutables`]:[],...C.mainExecutable===void 0?[]:[`mainExecutable`]];S.length>0&&n.push(`gjsify ship: ${S.join(`/`)} apply to darwin only — not staged for ${t.cli.layoutOs}`)}return{settings:{projectDir:t.projectDir,appId:q,name:Y,binaryName:W,version:ne.version,release:assertRelease(C.release??`1`),maintainer:ie,summary:ae,description:oe,license:re,licenseFile:F.licenseFile,changelogFile:F.changelogFile,homepage:I.homepageUrl??S.homepage,section:C.section??Q.section,group:C.group??Q.group,kind:X,mimeTypes:H,extraDepends:{deb:C.depends?.deb??[],rpm:C.depends?.rpm??[]},typelibPackages:C.typelibPackages??{},bundlePath:F.bundlePath,bundleDir:F.bundleDir,iconFiles:F.iconFiles,schemaFiles:F.schemaFiles,typelibFiles:F.typelibFiles,formatFiles:F.formatFiles,localeFiles:F.localeFiles,fontFiles:F.fontFiles,extraFiles:C.extraFiles??{},execArgs:C.execArgs??[],executables:resolveShipExecutables({declared:C.executables,binaryName:W,projectDir:t.projectDir,bundleDir:F.bundleDir}),nestedBundles:ce,helperExecutables:le,...ue===void 0?{}:{mainExecutableSource:ue,hasMainExecutable:!0},outDir:t.cli.outDir??C.outDir??`ship`,arch:t.cli.arch??process.arch,app:Z,layoutOs:t.cli.layoutOs,minGjsVersion:C.minGjsVersion??`1.86`,minNodeVersion:C.minNodeVersion??`24`,flatpak:se.settings},metadata:I,warnings:n}}function resolveShipExecutables(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.executables` must be a list of `{ "name", "entry", "gui"? }` objects.');let S=new Set([t.binaryName]);return n.map((n,C)=>{let N=`gjsify.ship.executables[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`name\` and \`entry\`.`);let{name:F,entry:I,gui:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: name, entry, gui.`);if(typeof F!=`string`||!DU.test(F))throw Error(`gjsify ship: \`${N}.name\` must match ${DU} — it becomes \`bin/<name>\`, \`Contents/MacOS/<name>\` and \`<name>.cmd\`, so it is lower-case with no path separator or space.`);if(S.has(F))throw Error(`gjsify ship: \`${N}.name\` "${F}" is already taken — by the package's own \`binaryName\` or by an earlier entry. Two launchers cannot share one file name.`);if(S.add(F),typeof I!=`string`||I===``)throw Error(`gjsify ship: \`${N}.entry\` must be the project-relative path of a built bundle.`);if(H!==void 0&&typeof H!=`boolean`)throw Error(`gjsify ship: \`${N}.gui\` must be a boolean.`);let Y=Rn(I)?I:In(t.projectDir,I),X=Bn(t.bundleDir,Y);if(X===``||X.startsWith(`..`)||Rn(X))throw Error(`gjsify ship: \`${N}.entry\` ${I} is outside ${t.bundleDir}, the directory \`gjsify.main\` lives in — only that directory is staged, so the launcher would point at a file the package does not carry. Build the entries into one directory.`);return{name:F,entry:X.split(qn).join(On.sep),gui:H===!0}})}function assertUsableBundleLeaf(t,n,S){if(t===``||t===`.`||t===`..`||t.includes(`/`)||t.includes(`\\`)||t.includes(`\0`))throw Error(`gjsify ship: \`${n}.name\` "${t}" is not usable as a leaf under \`${S}\` — empty and ".", "..", and anything containing "/", "\\" or a NUL byte are refused.`);return t}function resolveShipNestedBundles(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.nestedBundles` must be a list of `{ "source", "name", "entitlements"? }` objects.');let S=new Set,C=n.map((n,C)=>{let N=`gjsify.ship.nestedBundles[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`source\` and \`name\`.`);let{source:F,name:I,entitlements:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: source, name, entitlements.`);if(typeof F!=`string`||F===``)throw Error(`gjsify ship: \`${N}.source\` must be the project-relative directory of a built bundle.`);if(typeof I!=`string`)throw Error(`gjsify ship: \`${N}.name\` must be a string — the leaf under \`Contents/PlugIns/\`.`);if(assertUsableBundleLeaf(I,N,`Contents/PlugIns`),S.has(I))throw Error(`gjsify ship: \`${N}.name\` "${I}" is already taken by an earlier nested bundle.`);S.add(I);let Y=Rn(F)?F:In(t.projectDir,F);if(t.layoutOs===`darwin`&&!existsSync(Y))throw Error(`gjsify ship: \`${N}.source\` ${F} does not exist.`);if(H!==void 0&&!Array.isArray(H))throw Error(`gjsify ship: \`${N}.entitlements\` must be a list of strings.`);return{source:Y,name:I,entitlements:(H??[]).map((t,n)=>{if(typeof t!=`string`)throw Error(`gjsify ship: \`${N}.entitlements[${n}]\` must be a string.`);return t})}});return t.layoutOs===`darwin`?C:[]}function resolveShipHelperExecutables(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.helperExecutables` must be a list of `{ "source", "name", "entitlements"? }` objects.');let S=new Set,C=n.map((n,C)=>{let N=`gjsify.ship.helperExecutables[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`source\` and \`name\`.`);let{source:F,name:I,entitlements:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: source, name, entitlements.`);if(typeof F!=`string`||F===``)throw Error(`gjsify ship: \`${N}.source\` must be the project-relative path of a prebuilt executable.`);if(typeof I!=`string`)throw Error(`gjsify ship: \`${N}.name\` must be a string — the leaf under \`Contents/Helpers/\`.`);if(assertUsableBundleLeaf(I,N,`Contents/Helpers`),S.has(I))throw Error(`gjsify ship: \`${N}.name\` "${I}" is already taken by an earlier helper executable.`);S.add(I);let Y=Rn(F)?F:In(t.projectDir,F);if(t.layoutOs===`darwin`&&!existsSync(Y))throw Error(`gjsify ship: \`${N}.source\` ${F} does not exist.`);if(H!==void 0&&!Array.isArray(H))throw Error(`gjsify ship: \`${N}.entitlements\` must be a list of strings.`);return{source:Y,name:I,entitlements:(H??[]).map((t,n)=>{if(typeof t!=`string`)throw Error(`gjsify ship: \`${N}.entitlements[${n}]\` must be a string.`);return t})}});return t.layoutOs===`darwin`?C:[]}function resolveShipMainExecutable(t){let{declared:n}=t;if(n===void 0)return;if(typeof n!=`object`||!n||Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.mainExecutable` must be an object `{ "source" }`.');let{source:S,...C}=n,N=Object.keys(C);if(N.length>0)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable\` has unknown key(s) ${N.join(`, `)}; known: source.`);if(typeof S!=`string`||S===``)throw Error("gjsify ship: `gjsify.ship.mainExecutable.source` must be the project-relative path of a prebuilt Mach-O executable.");if(t.layoutOs!==`darwin`)return;let F=Rn(S)?S:In(t.projectDir,S);if(!existsSync(F)||!statSync(F).isFile())throw Error(`gjsify ship: \`gjsify.ship.mainExecutable.source\` ${S} does not exist or is not a file.`);let I=Buffer.alloc(4),H=openSync(F,`r`);try{readSync(H,I,0,4,0)}finally{closeSync(H)}if(classifyBinary(I)!==`macho`)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable.source\` ${S} is not a Mach-O binary (thin or universal). macOS resolves the host app record only for a native main executable, and the Mac App Store refuses a script; the generated launcher is staged as \`Contents/Resources/<binaryName>-launcher\`.`);return F}function resolveShipBundle(t){let n=t.ship.bundle,S=typeof n==`object`&&n?n:{};for(let t of Object.keys(S))if(!Object.hasOwn(TU,t))throw Error(`gjsify ship: \`gjsify.ship.bundle.${t}\` is not an OS this command assembles for. Known: ${Object.keys(TU).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. An entry under a key nothing reads leaves that target on \`gjsify.main\` with nothing to say so.`);let C=typeof n==`string`?n:void 0,N=t.pkg.gjsify?.main??t.pkg.main,entryFor=t=>S[t]??C??N,F=S[t.layoutOs],I=entryFor(t.layoutOs),H=F===void 0?C===void 0?t.pkg.gjsify?.main===void 0?`main`:`gjsify.main`:`gjsify.ship.bundle`:`gjsify.ship.bundle.${t.layoutOs}`,W=[...new Set(Object.keys(TU).filter(n=>n!==t.layoutOs).map(entryFor).filter(t=>t!==void 0&&t!==I))];return{declared:I,key:H,overridden:F!==void 0,foreign:W}}function deriveBinaryName(t){if(!t)throw Error("gjsify ship: no package name — set `name` in package.json or `gjsify.ship.binaryName`.");let n=(t.includes(`/`)?t.split(`/`).pop():t).toLowerCase().replace(/[^a-z\d+.-]+/g,`-`).replace(/^-+|-+$/g,``);if(!/^[a-z\d][a-z\d+.-]+$/.test(n))throw Error(`gjsify ship: cannot derive a package name from "${t}" (got "${n}"). Set \`gjsify.ship.binaryName\` to something matching \`[a-z0-9][a-z0-9+.-]+\`.`);return n}function reverseDnsOrThrow(t,n){if(t&&/^[A-Za-z][\w-]*(\.[A-Za-z][\w-]*){2,}$/.test(t))return t;throw Error(`gjsify ship: no application id. Set \`gjsify.ship.appId\` (or \`gjsify.flatpak.appId\`) to a reverse-DNS id such as "io.github.you.${titleCase(n).replace(/\s+/g,``)}". It names the desktop entry, the AppStream component and the installed icon, so it cannot be guessed.`)}function definedOnly(t){return Object.fromEntries(Object.entries(t).filter(([,t])=>t!==void 0))}function titleCase(t){return t.split(/[-_.]+/).filter(t=>t.length>0).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(` `)}function sectionsFor(t){for(let[n,S]of EU)if(t?.includes(n))return S;return{section:`misc`,group:`Applications/System`}}function formatAuthor(t){if(typeof t==`string`)return t.replace(/\s*\([^)]*\)\s*$/,``).trim()||void 0;if(t?.name)return t.email?`${t.name} <${t.email}>`:t.name}function formatDeveloper(t){let n=t.developer;if(n?.name)return n.email?`${n.name} <${n.email}>`:n.name}function descriptionParagraphs(t){if(t===void 0)return;if(typeof t==`string`){let n=t.trim().split(/\n\n+/).map(t=>t.trim().replace(/\s+/g,` `)).filter(t=>t.length>0);return n.length>0?n:void 0}let n=[];for(let S of t)if(typeof S==`string`){let t=S.trim().replace(/\s+/g,` `);t&&n.push(t)}else if(`p`in S)n.push(S.p.trim().replace(/\s+/g,` `));else for(let t of S.ul)n.push(`* ${(typeof t==`string`?t:t.item).trim().replace(/\s+/g,` `)}`);return n.length>0?n:void 0}var TU,EU,DU,OU,kU,AU=__esmMin(()=>{xU(),rf(),Xn(),_U(),dH(),uV(),wU(),TU={linux:!0,darwin:!0,win32:!0},EU=[[`Development`,{section:`devel`,group:`Development/Tools`}],[`Education`,{section:`education`,group:`Applications/Education`}],[`Game`,{section:`games`,group:`Amusements/Games`}],[`Graphics`,{section:`graphics`,group:`Applications/Multimedia`}],[`AudioVideo`,{section:`sound`,group:`Applications/Multimedia`}],[`Network`,{section:`net`,group:`Applications/Internet`}],[`Office`,{section:`text`,group:`Applications/Productivity`}],[`Science`,{section:`science`,group:`Applications/Engineering`}],[`System`,{section:`admin`,group:`Applications/System`}],[`Utility`,{section:`utils`,group:`Applications/System`}]],DU=/^[a-z0-9][a-z0-9._+-]*$/,OU=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`COPYING`,`COPYING.md`],kU=[`CHANGELOG.md`,`CHANGELOG`,`CHANGELOG.txt`,`NEWS.md`,`NEWS`]});function isFormatFilesId(t){return PU.includes(t)}function discoverPayload(t){let{projectDir:n,ship:S}=t,C=resolveBundle(t),N=In(C,`..`),F=discoverLocales(n,S.localeDir);return{bundlePath:C,bundleDir:N,bundleFiles:withoutForeignEntries(withoutLocaleTree(listFilesRecursive(N),N,n,S.localeDir),N,n,t.foreignBundles??[],C),iconFiles:discoverIcons(n,S.icon??t.flatpakIcon),schemaFiles:discoverSchemas(n,S.schemas),typelibFiles:discoverTypelibs(n,resolveBundledTypelibs(S.bundledTypelibs,t.layoutOs)),formatFiles:discoverFormatFiles(n,S,t.layoutOs),localeFiles:F,fontFiles:discoverFonts(n,S.fonts),licenseFile:discoverLicense(n,S.licenseFile),changelogFile:discoverChangelog(n,S.changelogFile)}}function discoverFormatFiles(t,n,S){let C={};if(S!==void 0&&S!==`linux`)return C;for(let[S,N]of Object.entries(n.formats??{})){if(!isFormatFilesId(S))throw Error(`gjsify ship: \`gjsify.ship.formats.${S}\` is not a format that carries its own files. Known: ${PU.join(`, `)}.`);C[S]={typelibFiles:discoverTypelibs(t,N?.bundledTypelibs),extraFiles:Object.fromEntries(Object.entries(N?.extraFiles??{}).map(([n,S])=>[n,In(t,S)]))}}return C}function resolveBundledTypelibs(t,n){if(t===void 0||Array.isArray(t))return t??[];let S=[`linux`,`darwin`,`win32`];for(let n of Object.keys(t))if(!S.includes(n))throw Error(`gjsify ship: \`gjsify.ship.bundledTypelibs.${n}\` is not an OS this command assembles for. Known: ${S.join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's.`);if(n===void 0)throw Error("gjsify ship: `gjsify.ship.bundledTypelibs` is a per-OS table but no layout OS was given.");return t[n]??[]}function discoverTypelibs(t,n){let S=[];for(let C of n??[]){let n=In(t,C);if(!existsSync(n))throw Error(`gjsify ship: \`gjsify.ship.bundledTypelibs\` names ${C}, which does not exist. A missing directory here means the package would install without the typelib it promises.`);for(let t of listFilesRecursive(n))(/\.(typelib|dylib|dll)$/i.test(t)||/\.so(\.\d+)*$/.test(t))&&S.push(zn(n,t))}return S}function withoutLocaleTree(t,n,S,C){if(C===void 0)return t;let N=Bn(n,In(S,C));if(N===``||N.startsWith(`..`)||Rn(N))return t;let F=`${N.split(qn).join(On.sep)}${On.sep}`;return t.filter(t=>!`${t}${On.sep}`.startsWith(F))}function discoverLocales(t,n){if(n===void 0)return[];let S=In(t,n);if(!existsSync(S))throw Error(`gjsify ship: \`gjsify.ship.localeDir\` names ${n}, which does not exist. Compile the catalogues first (msgfmt, or @gjsify/vite-plugin-gettext) — a missing directory here means the package would install without the translations it promises.`);let C=[],N=[];for(let t of listFilesRecursive(S)){if(t.endsWith(`.po`)||t.endsWith(`.pot`)){N.push(`${t} (a .po source; bindtextdomain reads .mo only)`);continue}if(!t.endsWith(`.mo`))continue;let n=t.split(On.sep);if(n.length!==3||n[1]!==`LC_MESSAGES`){N.push(`${t} (expected <lang>/LC_MESSAGES/<domain>.mo)`);continue}C.push({rel:n.join(`/`),abs:zn(S,t)})}if(N.length>0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${n}) holds files no catalogue lookup will find:\n`+N.map(t=>` ${t}`).join(`
1168
+ `}var bU,xU=__esmMin(()=>{yU(),bU=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/});function normaliseVersion(t){let n=[],S=t.trim();S.startsWith(`v`)&&(S=S.slice(1));let C=S.indexOf(`+`);C!==-1&&(n.push(`gjsify ship: dropped the build metadata "${S.slice(C)}" from version ${t} — neither dpkg nor rpm has a field for it. Set \`gjsify.ship.version\` to pin an exact package version.`),S=S.slice(0,C));let N=S.indexOf(`-`);if(N!==-1){let t=S.slice(N+1).replace(/-/g,`.`);S=`${S.slice(0,N)}~${t}`}if(!SU.test(S))throw Error(`gjsify ship: "${t}" is not a usable package version (normalised to "${S}"). It must start with a digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.version\` in package.json to override it.`);return{version:S,warnings:n}}function assertRelease(t){if(!CU.test(t))throw Error(`gjsify ship: "${t}" is not a usable package release. It must start with a letter or digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.release\` in package.json.`);return t}var SU,CU,wU=__esmMin(()=>{SU=/^\d[A-Za-z0-9.+~]*$/,CU=/^[A-Za-z0-9][A-Za-z0-9.+~]*$/});function resolveShipApp(t){let n=t.perTarget??{};for(let t of Object.keys(n))if(!Object.hasOwn(TU,t))throw Error(`gjsify ship: \`gjsify.ship.app.${t}\` is not an OS this command assembles for. Known: ${Object.keys(TU).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. A runtime under a key nothing reads leaves that target on \`gjsify.app\` with nothing to say so.`);let S=n[t.layoutOs],C=S!==void 0,N=C?`gjsify.ship.app.${t.layoutOs}`:`gjsify.app`,F=C?S:t.project;if(F!==void 0&&F!==`gjs`&&F!==`node`)throw Error(`gjsify ship: \`${N}\` is "${F}", and only \`gjs\` and \`node\` can be packaged. A browser bundle has no process to launch, and a NativeScript app ships as an APK/IPA through a different pipeline. ADR 0024 § 4 has the runtime-per-OS table.`);return{app:F===`node`?`node`:`gjs`,key:N,overridden:C}}function resolveShipKind(t,n){return t.kind??n.kind??`app`}function resolveShipSettings(t){let n=[],{pkg:S,ship:C,flatpak:N,discovered:F}=t,I={...N,...definedOnly(C)},H=C.mimeTypes??[];if(H.length>0){validateMimeTypes(H);let t=new Set([...I.provides?.mimetypes??[],...H.map(t=>t.type)]);I.provides={...I.provides,mimetypes:[...t]}}let W=C.binaryName??deriveBinaryName(S.name),q=C.appId??N.appId??reverseDnsOrThrow(S.name,W),Y=I.name??titleCase(W),X=resolveShipKind(C,N),Z=t.app,te=C.version??S.version;if(!te)throw Error("gjsify ship: no version — set `version` in package.json or `gjsify.ship.version`.");let ne=normaliseVersion(te);n.push(...ne.warnings);let re=I.license?.project??S.license;if(!re)throw Error('gjsify ship: no licence — set `license` in package.json (an SPDX id, e.g. "MIT") or `gjsify.ship.license.project`. Both deb and rpm carry it as a required field.');I.license={...I.license,project:re};let ie=C.maintainer??formatAuthor(S.author)??formatDeveloper(I);if(!ie)throw Error('gjsify ship: no maintainer — set `author` in package.json ("Name <you@example.com>"), `gjsify.ship.maintainer`, or `gjsify.ship.developer`. dpkg refuses a package without one.');let ae=I.summary??S.description??Y,oe=descriptionParagraphs(I.description)??[ae],Q=sectionsFor(I.categories);X===`app`&&F.iconFiles.length===0&&n.push("gjsify ship: no icon found — the installed app will show a placeholder in menus on Linux, the Flatpak will carry no catalogue icon for an app store to show, and the darwin and windows layouts refuse to stage without one. Point `gjsify.ship.icon` at an SVG (or a directory of sized PNGs).");let se=resolveShipFlatpakSettings({ship:C,flatpak:N,kind:X,appId:q});n.push(...se.warnings);let ce=resolveShipNestedBundles({declared:C.nestedBundles,projectDir:t.projectDir,layoutOs:t.cli.layoutOs}),le=resolveShipHelperExecutables({declared:C.helperExecutables,projectDir:t.projectDir,layoutOs:t.cli.layoutOs}),ue=resolveShipMainExecutable({declared:C.mainExecutable,projectDir:t.projectDir,layoutOs:t.cli.layoutOs});if(t.cli.layoutOs!==`darwin`){let S=[...Array.isArray(C.nestedBundles)&&C.nestedBundles.length>0?[`nestedBundles`]:[],...Array.isArray(C.helperExecutables)&&C.helperExecutables.length>0?[`helperExecutables`]:[],...C.mainExecutable===void 0?[]:[`mainExecutable`]];S.length>0&&n.push(`gjsify ship: ${S.join(`/`)} apply to darwin only — not staged for ${t.cli.layoutOs}`)}return{settings:{projectDir:t.projectDir,appId:q,name:Y,binaryName:W,version:ne.version,release:assertRelease(C.release??`1`),maintainer:ie,summary:ae,description:oe,license:re,licenseFile:F.licenseFile,changelogFile:F.changelogFile,homepage:I.homepageUrl??S.homepage,section:C.section??Q.section,group:C.group??Q.group,kind:X,mimeTypes:H,extraDepends:{deb:C.depends?.deb??[],rpm:C.depends?.rpm??[]},typelibPackages:C.typelibPackages??{},bundlePath:F.bundlePath,bundleDir:F.bundleDir,iconFiles:F.iconFiles,schemaFiles:F.schemaFiles,typelibFiles:F.typelibFiles,formatFiles:F.formatFiles,localeFiles:F.localeFiles,fontFiles:F.fontFiles,extraFiles:C.extraFiles??{},execArgs:C.execArgs??[],desktopExecArgs:C.desktopExecArgs??[],executables:resolveShipExecutables({declared:C.executables,binaryName:W,projectDir:t.projectDir,bundleDir:F.bundleDir}),nestedBundles:ce,helperExecutables:le,...ue===void 0?{}:{mainExecutableSource:ue,hasMainExecutable:!0},outDir:t.cli.outDir??C.outDir??`ship`,arch:t.cli.arch??process.arch,app:Z,layoutOs:t.cli.layoutOs,minGjsVersion:C.minGjsVersion??`1.86`,minNodeVersion:C.minNodeVersion??`24`,flatpak:se.settings},metadata:I,warnings:n}}function resolveShipExecutables(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.executables` must be a list of `{ "name", "entry", "gui"? }` objects.');let S=new Set([t.binaryName]);return n.map((n,C)=>{let N=`gjsify.ship.executables[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`name\` and \`entry\`.`);let{name:F,entry:I,gui:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: name, entry, gui.`);if(typeof F!=`string`||!DU.test(F))throw Error(`gjsify ship: \`${N}.name\` must match ${DU} — it becomes \`bin/<name>\`, \`Contents/MacOS/<name>\` and \`<name>.cmd\`, so it is lower-case with no path separator or space.`);if(S.has(F))throw Error(`gjsify ship: \`${N}.name\` "${F}" is already taken — by the package's own \`binaryName\` or by an earlier entry. Two launchers cannot share one file name.`);if(S.add(F),typeof I!=`string`||I===``)throw Error(`gjsify ship: \`${N}.entry\` must be the project-relative path of a built bundle.`);if(H!==void 0&&typeof H!=`boolean`)throw Error(`gjsify ship: \`${N}.gui\` must be a boolean.`);let Y=Rn(I)?I:In(t.projectDir,I),X=Bn(t.bundleDir,Y);if(X===``||X.startsWith(`..`)||Rn(X))throw Error(`gjsify ship: \`${N}.entry\` ${I} is outside ${t.bundleDir}, the directory \`gjsify.main\` lives in — only that directory is staged, so the launcher would point at a file the package does not carry. Build the entries into one directory.`);return{name:F,entry:X.split(qn).join(On.sep),gui:H===!0}})}function assertUsableBundleLeaf(t,n,S){if(t===``||t===`.`||t===`..`||t.includes(`/`)||t.includes(`\\`)||t.includes(`\0`))throw Error(`gjsify ship: \`${n}.name\` "${t}" is not usable as a leaf under \`${S}\` — empty and ".", "..", and anything containing "/", "\\" or a NUL byte are refused.`);return t}function resolveShipNestedBundles(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.nestedBundles` must be a list of `{ "source", "name", "entitlements"? }` objects.');let S=new Set,C=n.map((n,C)=>{let N=`gjsify.ship.nestedBundles[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`source\` and \`name\`.`);let{source:F,name:I,entitlements:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: source, name, entitlements.`);if(typeof F!=`string`||F===``)throw Error(`gjsify ship: \`${N}.source\` must be the project-relative directory of a built bundle.`);if(typeof I!=`string`)throw Error(`gjsify ship: \`${N}.name\` must be a string — the leaf under \`Contents/PlugIns/\`.`);if(assertUsableBundleLeaf(I,N,`Contents/PlugIns`),S.has(I))throw Error(`gjsify ship: \`${N}.name\` "${I}" is already taken by an earlier nested bundle.`);S.add(I);let Y=Rn(F)?F:In(t.projectDir,F);if(t.layoutOs===`darwin`&&!existsSync(Y))throw Error(`gjsify ship: \`${N}.source\` ${F} does not exist.`);if(H!==void 0&&!Array.isArray(H))throw Error(`gjsify ship: \`${N}.entitlements\` must be a list of strings.`);return{source:Y,name:I,entitlements:(H??[]).map((t,n)=>{if(typeof t!=`string`)throw Error(`gjsify ship: \`${N}.entitlements[${n}]\` must be a string.`);return t})}});return t.layoutOs===`darwin`?C:[]}function resolveShipHelperExecutables(t){let{declared:n}=t;if(n===void 0)return[];if(!Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.helperExecutables` must be a list of `{ "source", "name", "entitlements"? }` objects.');let S=new Set,C=n.map((n,C)=>{let N=`gjsify.ship.helperExecutables[${C}]`;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: \`${N}\` must be an object with \`source\` and \`name\`.`);let{source:F,name:I,entitlements:H,...W}=n,q=Object.keys(W);if(q.length>0)throw Error(`gjsify ship: \`${N}\` has unknown key(s) ${q.join(`, `)}; known: source, name, entitlements.`);if(typeof F!=`string`||F===``)throw Error(`gjsify ship: \`${N}.source\` must be the project-relative path of a prebuilt executable.`);if(typeof I!=`string`)throw Error(`gjsify ship: \`${N}.name\` must be a string — the leaf under \`Contents/Helpers/\`.`);if(assertUsableBundleLeaf(I,N,`Contents/Helpers`),S.has(I))throw Error(`gjsify ship: \`${N}.name\` "${I}" is already taken by an earlier helper executable.`);S.add(I);let Y=Rn(F)?F:In(t.projectDir,F);if(t.layoutOs===`darwin`&&!existsSync(Y))throw Error(`gjsify ship: \`${N}.source\` ${F} does not exist.`);if(H!==void 0&&!Array.isArray(H))throw Error(`gjsify ship: \`${N}.entitlements\` must be a list of strings.`);return{source:Y,name:I,entitlements:(H??[]).map((t,n)=>{if(typeof t!=`string`)throw Error(`gjsify ship: \`${N}.entitlements[${n}]\` must be a string.`);return t})}});return t.layoutOs===`darwin`?C:[]}function resolveShipMainExecutable(t){let{declared:n}=t;if(n===void 0)return;if(typeof n!=`object`||!n||Array.isArray(n))throw Error('gjsify ship: `gjsify.ship.mainExecutable` must be an object `{ "source" }`.');let{source:S,...C}=n,N=Object.keys(C);if(N.length>0)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable\` has unknown key(s) ${N.join(`, `)}; known: source.`);if(typeof S!=`string`||S===``)throw Error("gjsify ship: `gjsify.ship.mainExecutable.source` must be the project-relative path of a prebuilt Mach-O executable.");if(t.layoutOs!==`darwin`)return;let F=Rn(S)?S:In(t.projectDir,S);if(!existsSync(F)||!statSync(F).isFile())throw Error(`gjsify ship: \`gjsify.ship.mainExecutable.source\` ${S} does not exist or is not a file.`);let I=Buffer.alloc(4),H=openSync(F,`r`);try{readSync(H,I,0,4,0)}finally{closeSync(H)}if(classifyBinary(I)!==`macho`)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable.source\` ${S} is not a Mach-O binary (thin or universal). macOS resolves the host app record only for a native main executable, and the Mac App Store refuses a script; the generated launcher is staged as \`Contents/Resources/<binaryName>-launcher\`.`);return F}function resolveShipBundle(t){let n=t.ship.bundle,S=typeof n==`object`&&n?n:{};for(let t of Object.keys(S))if(!Object.hasOwn(TU,t))throw Error(`gjsify ship: \`gjsify.ship.bundle.${t}\` is not an OS this command assembles for. Known: ${Object.keys(TU).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. An entry under a key nothing reads leaves that target on \`gjsify.main\` with nothing to say so.`);let C=typeof n==`string`?n:void 0,N=t.pkg.gjsify?.main??t.pkg.main,entryFor=t=>S[t]??C??N,F=S[t.layoutOs],I=entryFor(t.layoutOs),H=F===void 0?C===void 0?t.pkg.gjsify?.main===void 0?`main`:`gjsify.main`:`gjsify.ship.bundle`:`gjsify.ship.bundle.${t.layoutOs}`,W=[...new Set(Object.keys(TU).filter(n=>n!==t.layoutOs).map(entryFor).filter(t=>t!==void 0&&t!==I))];return{declared:I,key:H,overridden:F!==void 0,foreign:W}}function deriveBinaryName(t){if(!t)throw Error("gjsify ship: no package name — set `name` in package.json or `gjsify.ship.binaryName`.");let n=(t.includes(`/`)?t.split(`/`).pop():t).toLowerCase().replace(/[^a-z\d+.-]+/g,`-`).replace(/^-+|-+$/g,``);if(!/^[a-z\d][a-z\d+.-]+$/.test(n))throw Error(`gjsify ship: cannot derive a package name from "${t}" (got "${n}"). Set \`gjsify.ship.binaryName\` to something matching \`[a-z0-9][a-z0-9+.-]+\`.`);return n}function reverseDnsOrThrow(t,n){if(t&&/^[A-Za-z][\w-]*(\.[A-Za-z][\w-]*){2,}$/.test(t))return t;throw Error(`gjsify ship: no application id. Set \`gjsify.ship.appId\` (or \`gjsify.flatpak.appId\`) to a reverse-DNS id such as "io.github.you.${titleCase(n).replace(/\s+/g,``)}". It names the desktop entry, the AppStream component and the installed icon, so it cannot be guessed.`)}function definedOnly(t){return Object.fromEntries(Object.entries(t).filter(([,t])=>t!==void 0))}function titleCase(t){return t.split(/[-_.]+/).filter(t=>t.length>0).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(` `)}function sectionsFor(t){for(let[n,S]of EU)if(t?.includes(n))return S;return{section:`misc`,group:`Applications/System`}}function formatAuthor(t){if(typeof t==`string`)return t.replace(/\s*\([^)]*\)\s*$/,``).trim()||void 0;if(t?.name)return t.email?`${t.name} <${t.email}>`:t.name}function formatDeveloper(t){let n=t.developer;if(n?.name)return n.email?`${n.name} <${n.email}>`:n.name}function descriptionParagraphs(t){if(t===void 0)return;if(typeof t==`string`){let n=t.trim().split(/\n\n+/).map(t=>t.trim().replace(/\s+/g,` `)).filter(t=>t.length>0);return n.length>0?n:void 0}let n=[];for(let S of t)if(typeof S==`string`){let t=S.trim().replace(/\s+/g,` `);t&&n.push(t)}else if(`p`in S)n.push(S.p.trim().replace(/\s+/g,` `));else for(let t of S.ul)n.push(`* ${(typeof t==`string`?t:t.item).trim().replace(/\s+/g,` `)}`);return n.length>0?n:void 0}var TU,EU,DU,OU,kU,AU=__esmMin(()=>{xU(),rf(),Xn(),_U(),dH(),lV(),wU(),TU={linux:!0,darwin:!0,win32:!0},EU=[[`Development`,{section:`devel`,group:`Development/Tools`}],[`Education`,{section:`education`,group:`Applications/Education`}],[`Game`,{section:`games`,group:`Amusements/Games`}],[`Graphics`,{section:`graphics`,group:`Applications/Multimedia`}],[`AudioVideo`,{section:`sound`,group:`Applications/Multimedia`}],[`Network`,{section:`net`,group:`Applications/Internet`}],[`Office`,{section:`text`,group:`Applications/Productivity`}],[`Science`,{section:`science`,group:`Applications/Engineering`}],[`System`,{section:`admin`,group:`Applications/System`}],[`Utility`,{section:`utils`,group:`Applications/System`}]],DU=/^[a-z0-9][a-z0-9._+-]*$/,OU=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`COPYING`,`COPYING.md`],kU=[`CHANGELOG.md`,`CHANGELOG`,`CHANGELOG.txt`,`NEWS.md`,`NEWS`]});function isFormatFilesId(t){return PU.includes(t)}function discoverPayload(t){let{projectDir:n,ship:S}=t,C=resolveBundle(t),N=In(C,`..`),F=discoverLocales(n,S.localeDir);return{bundlePath:C,bundleDir:N,bundleFiles:withoutForeignEntries(withoutLocaleTree(listFilesRecursive(N),N,n,S.localeDir),N,n,t.foreignBundles??[],C),iconFiles:discoverIcons(n,S.icon??t.flatpakIcon),schemaFiles:discoverSchemas(n,S.schemas),typelibFiles:discoverTypelibs(n,resolveBundledTypelibs(S.bundledTypelibs,t.layoutOs)),formatFiles:discoverFormatFiles(n,S,t.layoutOs),localeFiles:F,fontFiles:discoverFonts(n,S.fonts),licenseFile:discoverLicense(n,S.licenseFile),changelogFile:discoverChangelog(n,S.changelogFile)}}function discoverFormatFiles(t,n,S){let C={};if(S!==void 0&&S!==`linux`)return C;for(let[S,N]of Object.entries(n.formats??{})){if(!isFormatFilesId(S))throw Error(`gjsify ship: \`gjsify.ship.formats.${S}\` is not a format that carries its own files. Known: ${PU.join(`, `)}.`);C[S]={typelibFiles:discoverTypelibs(t,N?.bundledTypelibs),extraFiles:Object.fromEntries(Object.entries(N?.extraFiles??{}).map(([n,S])=>[n,In(t,S)]))}}return C}function resolveBundledTypelibs(t,n){if(t===void 0||Array.isArray(t))return t??[];let S=[`linux`,`darwin`,`win32`];for(let n of Object.keys(t))if(!S.includes(n))throw Error(`gjsify ship: \`gjsify.ship.bundledTypelibs.${n}\` is not an OS this command assembles for. Known: ${S.join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's.`);if(n===void 0)throw Error("gjsify ship: `gjsify.ship.bundledTypelibs` is a per-OS table but no layout OS was given.");return t[n]??[]}function discoverTypelibs(t,n){let S=[];for(let C of n??[]){let n=In(t,C);if(!existsSync(n))throw Error(`gjsify ship: \`gjsify.ship.bundledTypelibs\` names ${C}, which does not exist. A missing directory here means the package would install without the typelib it promises.`);for(let t of listFilesRecursive(n))(/\.(typelib|dylib|dll)$/i.test(t)||/\.so(\.\d+)*$/.test(t))&&S.push(zn(n,t))}return S}function withoutLocaleTree(t,n,S,C){if(C===void 0)return t;let N=Bn(n,In(S,C));if(N===``||N.startsWith(`..`)||Rn(N))return t;let F=`${N.split(qn).join(On.sep)}${On.sep}`;return t.filter(t=>!`${t}${On.sep}`.startsWith(F))}function discoverLocales(t,n){if(n===void 0)return[];let S=In(t,n);if(!existsSync(S))throw Error(`gjsify ship: \`gjsify.ship.localeDir\` names ${n}, which does not exist. Compile the catalogues first (msgfmt, or @gjsify/vite-plugin-gettext) — a missing directory here means the package would install without the translations it promises.`);let C=[],N=[];for(let t of listFilesRecursive(S)){if(t.endsWith(`.po`)||t.endsWith(`.pot`)){N.push(`${t} (a .po source; bindtextdomain reads .mo only)`);continue}if(!t.endsWith(`.mo`))continue;let n=t.split(On.sep);if(n.length!==3||n[1]!==`LC_MESSAGES`){N.push(`${t} (expected <lang>/LC_MESSAGES/<domain>.mo)`);continue}C.push({rel:n.join(`/`),abs:zn(S,t)})}if(N.length>0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${n}) holds files no catalogue lookup will find:\n`+N.map(t=>` ${t}`).join(`
1169
1169
  `)+`
1170
1170
  A misplaced catalogue installs and then shows nothing, which reads exactly like having no translation at all. Lay them out as <lang>/LC_MESSAGES/<domain>.mo.`);if(C.length===0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${n}) contains no \`.mo\` catalogue. Declaring a locale directory that ships nothing is a promise the package does not keep.`);return C}function withoutForeignEntries(t,n,S,C,N){if(C.length===0)return t;let F=new Set;for(let t of C){let C=Rn(t)?t:In(S,t);if(C===N)continue;let I=Bn(n,C);I===``||I.startsWith(`..`)||Rn(I)||F.add(I.split(qn).join(On.sep))}return t.filter(t=>!F.has(t))}function resolveBundle(t){let n=t.declaredBundle;if(n===void 0)throw Error("gjsify ship: no bundle to ship. Set `gjsify.main` (or `main`) in package.json to the built bundle, or `gjsify.ship.bundle` to override it.");let S=Rn(n)?n:In(t.projectDir,n);if(!existsSync(S))throw Error(`gjsify ship: the bundle ${n} does not exist. Build it first (\`gjsify run build\`), or drop \`--skip-build\`.`);return S}function discoverIcons(t,n){if(n!==void 0){let S=In(t,n);if(!existsSync(S))throw Error(`gjsify ship: the configured icon path ${n} does not exist.`);return statSync(S).isDirectory()?listIcons(S):[S]}for(let n of[`data/icons`,`data/icons/hicolor`]){let S=zn(t,n);if(existsSync(S)&&statSync(S).isDirectory()){let t=listIcons(S);if(t.length>0)return t}}return[]}function listIcons(t){return listFilesRecursive(t).filter(t=>jU.some(n=>t.toLowerCase().endsWith(n))).map(n=>zn(t,n.split(`/`).join(qn))).sort()}function discoverFonts(t,n){let S=n??`data/fonts`,C=n===void 0?zn(t,`data`,`fonts`):In(t,n);if(!existsSync(C)){if(n===void 0)return[];throw Error(`gjsify ship: the configured font path ${n} does not exist.`)}if(!statSync(C).isDirectory()){if(assertNotWebFont(C,S),!MU.some(t=>C.toLowerCase().endsWith(t)))throw Error(`gjsify ship: \`gjsify.ship.fonts\` names ${n}, which is not a font face fontconfig will open (${MU.join(`, `)}). A file it cannot read installs and is never found, and Pango substitutes a fallback family rather than reporting anything.`);return[C]}let N=[];for(let t of listFilesRecursive(C))assertNotWebFont(t,S),MU.some(n=>t.toLowerCase().endsWith(n))&&N.push(zn(C,t.split(`/`).join(qn)));if(N.length===0&&n!==void 0)throw Error(`gjsify ship: \`gjsify.ship.fonts\` (${n}) holds no font face (${MU.join(`, `)}). Declaring fonts that ship nothing is a promise the package does not keep — and its symptom is a substituted family, not an error.`);return N.sort()}function assertNotWebFont(t,n){let S=t.toLowerCase(),C=NU.find(t=>S.endsWith(t));if(C!==void 0)throw Error(`gjsify ship: \`gjsify.ship.fonts\` (${n}) carries ${t}, and \`${C}\` is a web-font wrapper whose support is a FreeType BUILD option — brotli for woff2, zlib for woff. Whether it opens is therefore a property of the FreeType the SHIPPED artifact loads (inside \`@gjsify/gtk-runtime-<target>\` for a \`.app\` or a Windows program directory), not of the machine that packaged it. Ship the desktop face instead (${MU.join(`, `)}); a font that fails to open is not an error, it is Pango quietly substituting a different typeface.`)}function discoverSchemas(t,n){let S=n===void 0?[zn(t,`data`)]:[In(t,n)];for(let t of S){if(!existsSync(t)){if(n!==void 0)throw Error(`gjsify ship: the configured schema path ${n} does not exist.`);continue}if(!statSync(t).isDirectory())return[t];let S=listFilesRecursive(t).filter(t=>t.endsWith(`.gschema.xml`)).map(n=>zn(t,n.split(`/`).join(qn))).sort();if(S.length>0)return S}return[]}function discoverLicense(t,n){if(n!==void 0){let S=In(t,n);if(!existsSync(S))throw Error(`gjsify ship: the configured licence file ${n} does not exist.`);return S}for(let n of licenseSearchDirs(t))for(let t of OU){let S=zn(n,t);if(existsSync(S))return S}}function discoverChangelog(t,n){if(n!==void 0){let S=In(t,n);if(!existsSync(S))throw Error(`gjsify ship: the configured changelog file ${n} does not exist.`);return S}for(let n of licenseSearchDirs(t))for(let t of kU){let S=zn(n,t);if(existsSync(S))return S}}function licenseSearchDirs(t){let n=[];for(let S=t;;){if(n.push(S),isProjectRoot(S))return n;let C=Hn(S);if(C===S)return[t];S=C}}function isProjectRoot(t){if(existsSync(zn(t,`.git`)))return!0;let n=zn(t,`package.json`);if(!existsSync(n))return!1;try{return JSON.parse(readFileSync(n,`utf-8`)).workspaces!==void 0}catch{return!1}}function listFilesRecursive(t){let n=[],walk=S=>{for(let C of readdirSync(S,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1)){let N=zn(S,C.name);if(C.isDirectory())walk(N);else if(C.isSymbolicLink())throw Error(`gjsify ship: ${N} is a symlink. The payload has to be self-contained — replace it with the file it points at, or exclude it from the bundle directory.`);else C.isFile()&&n.push(On.join(...Bn(t,N).split(qn)))}};return walk(t),n.sort()}var jU,MU,NU,PU,FU=__esmMin(()=>{rf(),Xn(),AU(),jU=[`.svg`,`.png`],MU=[`.ttf`,`.otf`,`.ttc`,`.otc`],NU=[`.woff`,`.woff2`,`.eot`],PU=Object.keys({deb:null,rpm:null,appimage:null})});function isNodeRuntimeTarget(t){return IU.includes(t)}function nodeRuntimePackageName(t){return`@gjsify/node-runtime-${t}`}function nodeRuntimeBinaryName(t){return t.startsWith(`win32-`)?`node.exe`:`node`}function resolveNodeRuntime(t,n={}){let S=n.env??process.env,C=nodeRuntimeBinaryName(t),N=S.GJSIFY_NODE_RUNTIME;if(N){let t=complete(`GJSIFY_NODE_RUNTIME`,N,C);if(t)return t}let F=nodeRuntimePackageName(t),I=resolveInstalledPackage(F,{cwd:n.cwd,bundleUrl:import.meta.url});return I===null?null:complete(F,zn(Hn(I),`bin`),C)}function complete(t,n,S){let C=zn(n,S),N=zn(n,`LICENSE`);return!existsSync(C)||!existsSync(N)?null:{source:t,binDir:n,nodePath:C,licensePath:N}}var IU,LU=__esmMin(()=>{rf(),Xn(),GI(),IU=[`darwin-arm64`,`darwin-x64`,`win32-x64`,`win32-arm64`]});function rfc822(t){let n=new Date(t*1e3),pad=t=>String(t).padStart(2,`0`);return`${RU[n.getUTCDay()]}, ${pad(n.getUTCDate())} ${zU[n.getUTCMonth()]} ${n.getUTCFullYear()} ${pad(n.getUTCHours())}:${pad(n.getUTCMinutes())}:${pad(n.getUTCSeconds())} +0000`}function changelogEntriesFor(t,n){let S=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),C=RegExp(`^##+[ \\t]+\\[?${S}\\]?[^\\n]*$`,`m`).exec(n);if(C===null)return[];let N=n.slice(C.index+C[0].length),F=/^##[ \t]+\[?\d/m.exec(N),I=F===null?N:N.slice(0,F.index),H=[];for(let t of I.split(`
1171
1171
  `)){let n=/^[*-][ \t]+(.*\S)\s*$/.exec(t);n!==null&&H.push(n[1].replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\*\*([^*]+)\*\*/g,`$1`).replace(/\s+/g,` `).trim())}return H}function wrapEntry(t){let n=[],S=` *`;for(let C of t.split(/\s+/))C!==``&&(S.length+1+C.length>BU&&S!==` *`&&S!==` `&&(n.push(S),S=` `),S+=` ${C}`);return n.push(S),n}function renderDebianChangelog(t,n,S){let C=n===void 0?[]:changelogEntriesFor(t.version,n),N=t.homepage?`Release ${t.version}. See ${t.homepage} for the upstream changes.`:`Release ${t.version}.`,F=(C.length>0?C:[N]).flatMap(wrapEntry);return[`${t.binaryName} (${t.version}-${t.release}) unstable; urgency=medium`,``,...F,``,` -- ${t.maintainer} ${rfc822(S)}`,``].join(`
@@ -1188,10 +1188,10 @@ A misplaced catalogue installs and then shows nothing, which reads exactly like
1188
1188
  `)}function renderWindowsLauncher(t,n,S,C){let N=S.dirs(t),at=t=>`%HERE%${windowsPath(t)}`,F=[`@echo off`,`rem Generated by "gjsify ship" - do not edit.`,`setlocal`,`set "HERE=%~dp0"`,prependVar(`XDG_DATA_DIRS`,at(N.data))];C.gtkRuntimeDir!==void 0&&F.push(`set "GJSIFY_GTK_RUNTIME=${at(C.gtkRuntimeDir)}"`),C.nodeGiAddon!==void 0&&F.push(`set "NODE_GI_NATIVE=${at(C.nodeGiAddon)}"`),t.typelibFiles.length>0&&F.push(prependVar(`GI_TYPELIB_PATH`,at(N.native)),prependVar(`PATH`,at(N.native))),t.localeFiles.length>0&&F.push(`set "GJSIFY_LOCALE_DIR=${at(N.data)}\\locale"`),t.fontFiles.length>0&&F.push(`set "GJSIFY_FONT_DIR=${at(stagedFontDir(N.data,t.appId))}"`);let I=C.interpreter===void 0?void 0:`"${at(C.interpreter)}"`;return F.push(`${execLine(S,`"${at(N.bundle)}\\${windowsPath(n)}"`,t,I)} %*`,``),F.join(`\r
1189
1189
  `)}function prependVar(t,n){return`if defined ${t} (set "${t}=${n};%${t}%") else (set "${t}=${n}")`}function windowsPath(t){return t.split(`/`).filter(t=>t.length>0).join(`\\`)}function execLine(t,n,S,C){let N=t.name===`windows`?cmdQuote:shellQuote,F=S.execArgs.map(N).join(` `),I=C??(S.app===`node`?`node`:`gjs`);return`${S.app===`node`?I:`${I} -m`} ${n}${F?` ${F}`:``}`}var nG=__esmMin(()=>{Xn(),mH()});function createCpioArchive(t){let n=[],S=0;t.forEach((t,C)=>{let N=t.linkTarget===void 0?t.data??new Uint8Array:encodeUtf8(t.linkTarget),F=encodeUtf8(`${t.name}\0`),I=buildHeader({ino:t.ino??C+1,mode:t.mode,nlink:t.nlink??1,mtime:t.mtime??0,filesize:N.byteLength,namesize:F.byteLength});S=push(n,I,S),S=push(n,F,S),S=padTo4(n,S),S=push(n,N,S),S=padTo4(n,S)});let C=encodeUtf8(`TRAILER!!!\0`);return S=push(n,buildHeader({ino:0,mode:0,nlink:1,mtime:0,filesize:0,namesize:C.byteLength}),S),S=push(n,C,S),padTo4(n,S),concatBytes(n)}function buildHeader(t){let n=rG+hex8(t.ino)+hex8(t.mode)+hex8(0)+hex8(0)+hex8(t.nlink)+hex8(t.mtime)+hex8(t.filesize)+hex8(0)+hex8(0)+hex8(0)+hex8(0)+hex8(t.namesize)+hex8(0);if(n.length!==iG)throw Error(`gjsify ship: internal error — cpio header is ${n.length} bytes, expected ${iG}.`);return encodeUtf8(n)}function hex8(t){if(t<0||!Number.isInteger(t))throw Error(`gjsify ship: cpio header field must be a non-negative integer, got ${t}.`);let n=t.toString(16).toUpperCase();if(n.length>8)throw Error(`gjsify ship: cpio header field ${t} does not fit in 8 hex digits.`);return n.padStart(8,`0`)}function push(t,n,S){return n.byteLength>0&&t.push(n),S+n.byteLength}function padTo4(t,n){let S=n%4;if(S===0)return n;let C=4-S;return t.push(new Uint8Array(C)),n+C}var rG,iG,aG,oG,sG=__esmMin(()=>{$V(),rG=`070701`,iG=110,aG=32768,oG=16384});function buildRpmHeader(t,n){let S=[...t].sort((t,n)=>t.tag-n.tag),C=[],N=[],F=0;for(let t of S){if(t.tag<100)throw Error(`gjsify ship: rpm tag ${t.tag} is below 100 and would be rejected by hdrchkTag.`);let{data:n,count:S}=encodeValue(t.type,t.value,t.tag),I=dG[t.type],H=(I-F%I)%I;H>0&&(N.push(new Uint8Array(H)),F+=H),C.push({tag:t.tag,type:t.type,offset:F,count:S}),N.push(n),F+=n.byteLength}let I=F,H=C.length+1;N.push(indexEntry(n,7,-(lG*H),uG)),F+=lG;let W=new Uint8Array(cG.byteLength+8+H*lG+F),q=new DataView(W.buffer);W.set(cG,0),q.setUint32(8,H),q.setUint32(12,F);let Y=16;W.set(indexEntry(n,7,I,uG),Y),Y+=lG;for(let t of C)W.set(indexEntry(t.tag,t.type,t.offset,t.count),Y),Y+=lG;for(let t of N)W.set(t,Y),Y+=t.byteLength;return W}function indexEntry(t,n,S,C){let N=new Uint8Array(lG),F=new DataView(N.buffer);return F.setInt32(0,t),F.setInt32(4,n),F.setInt32(8,S),F.setInt32(12,C),N}function encodeValue(t,n,S){let C=new TextEncoder;switch(t){case 6:if(typeof n!=`string`)throw typeMismatch(S,`a string`);return{data:C.encode(`${n}\0`),count:1};case 8:case 9:{let t=typeof n==`string`?[n]:n;if(!Array.isArray(t))throw typeMismatch(S,`a string array`);if(t.length===0)throw Error(`gjsify ship: rpm tag ${S} has an empty array; omit it instead.`);return{data:C.encode(t.map(t=>`${t}\0`).join(``)),count:t.length}}case 7:if(!(n instanceof Uint8Array))throw typeMismatch(S,`binary data`);return{data:n,count:n.byteLength};case 3:case 4:{let C=typeof n==`number`?[n]:n;if(!Array.isArray(C))throw typeMismatch(S,`a number array`);if(C.length===0)throw Error(`gjsify ship: rpm tag ${S} has an empty array; omit it instead.`);let N=t===3?2:4,F=new Uint8Array(C.length*N),I=new DataView(F.buffer);return C.forEach((n,S)=>{t===3?I.setUint16(S*N,n&65535):I.setUint32(S*N,n>>>0)}),{data:F,count:C.length}}}}function typeMismatch(t,n){return Error(`gjsify ship: internal error — rpm tag ${t} expects ${n}.`)}function buildRpmLead(t){let n=new Uint8Array(96),S=new DataView(n.buffer);n.set([237,171,238,219],0),n[4]=3,n[5]=0,S.setInt16(6,0),S.setInt16(8,0);let C=new TextEncoder().encode(t).slice(0,65);return n.set(C,10),S.setInt16(76,0),S.setInt16(78,5),n}function padToEight(t){let n=(8-t.byteLength%8)%8;if(n===0)return t;let S=new Uint8Array(t.byteLength+n);return S.set(t,0),S}var cG,lG,uG,dG,fG=__esmMin(()=>{cG=Uint8Array.from([142,173,232,1,0,0,0,0]),lG=16,uG=16,dG={3:2,4:4,6:1,7:1,8:1,9:1}});async function buildRpm(t){let{settings:n,mtime:S}=t,C=collectFiles(t,`/${t.prefix.replace(/^\/+|\/+$/g,``)}`),N=createCpioArchive(C.map((t,n)=>({name:`.${t.path}`,mode:t.mode,data:t.data,mtime:S,ino:n+1}))),F=await gzipDeterministic(N),I=buildRpmHeader(mainHeaderEntries(t,C,N,F),63),H=concatBytes([I,F]),W=padToEight(buildRpmHeader([{tag:mG.SHA1HEADER,type:6,value:hashHex(`sha1`,I)},{tag:mG.SHA256HEADER,type:6,value:hashHex(`sha256`,I)},{tag:mG.SIZE,type:4,value:[H.byteLength]},{tag:mG.MD5,type:7,value:hashBytes(`md5`,H)},{tag:mG.PAYLOADSIZE,type:4,value:[N.byteLength]}],62));return concatBytes([buildRpmLead(`${n.binaryName}-${n.version}-${n.release}`),W,H])}function collectFiles(t,n){let S=t.payload.map(t=>{if(t.data.byteLength>4294967295)throw Error(`gjsify ship: ${t.path} is larger than 4 GiB, which needs rpm's LONGFILESIZES tag. That is not implemented — split the payload.`);return{path:`${n}/${t.path}`,mode:aG|t.mode&4095,data:t.data,isDirectory:!1}}),C=new Set;for(let t of S){let n=t.path.split(`/`).slice(1);n.pop();let S=``;for(let t of n)S=`${S}/${t}`,vG.has(S)||C.add(S)}for(let t of C)S.push({path:t,mode:oG|493,data:new Uint8Array,isDirectory:!0});return S.sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function mainHeaderEntries(t,n,S,C){let{settings:N}=t,F=`${N.version}-${N.release}`,I=[],H=[],W=[];for(let t of n){let n=t.path.lastIndexOf(`/`),S=`${t.path.slice(0,n)}/`,C=I.indexOf(S);C===-1&&(C=I.push(S)-1),H.push(C),W.push(t.path.slice(n+1))}let q=renderRpmScriptlets(readPayloadFacts(t.payload),t.prefix),Y=buildRequires(t.depends,q,readShebangInterpreters(t.payload)),X=buildRecommends(t.recommends??[]),Z=[{tag:pG.HEADERI18NTABLE,type:8,value:[`C`]},{tag:pG.NAME,type:6,value:N.binaryName},{tag:pG.VERSION,type:6,value:N.version},{tag:pG.RELEASE,type:6,value:N.release},{tag:pG.SUMMARY,type:9,value:[N.summary]},{tag:pG.DESCRIPTION,type:9,value:[N.description.join(`
1190
1190
 
1191
- `)]},{tag:pG.BUILDTIME,type:4,value:[t.mtime]},{tag:pG.BUILDHOST,type:6,value:`localhost`},{tag:pG.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:pG.LICENSE,type:6,value:N.license},{tag:pG.GROUP,type:9,value:[N.group]},{tag:pG.OS,type:6,value:`linux`},{tag:pG.ARCH,type:6,value:t.archLabel},{tag:pG.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:pG.RPMVERSION,type:6,value:`4.20.0`},{tag:pG.ENCODING,type:6,value:`utf-8`},{tag:pG.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:pG.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:pG.FILERDEVS,type:3,value:n.map(()=>0)},{tag:pG.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:pG.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:pG.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:pG.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:pG.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:pG.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:pG.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:pG.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:pG.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:pG.FILELANGS,type:8,value:n.map(()=>``)},{tag:pG.FILEDIGESTALGO,type:4,value:[gG]},{tag:pG.DIRINDEXES,type:4,value:H},{tag:pG.BASENAMES,type:8,value:W},{tag:pG.DIRNAMES,type:8,value:I},{tag:pG.PROVIDENAME,type:8,value:[N.binaryName]},{tag:pG.PROVIDEFLAGS,type:4,value:[hG.EQUAL]},{tag:pG.PROVIDEVERSION,type:8,value:[F]},{tag:pG.REQUIRENAME,type:8,value:Y.names},{tag:pG.REQUIREFLAGS,type:4,value:Y.flags},{tag:pG.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:pG.RECOMMENDNAME,type:8,value:X.names},{tag:pG.RECOMMENDFLAGS,type:4,value:X.flags},{tag:pG.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:pG.PAYLOADFORMAT,type:6,value:`cpio`},{tag:pG.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:pG.PAYLOADFLAGS,type:6,value:`9`},{tag:pG.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:pG.PAYLOADDIGESTALGO,type:4,value:[gG]},{tag:pG.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:pG.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:pG.POSTIN,type:6,value:q.post}),Z.push({tag:pG.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:pG.POSTUN,type:6,value:q.postun}),Z.push({tag:pG.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([pG.FILESIZES,pG.FILEMODES,pG.FILERDEVS,pG.FILEMTIMES,pG.FILEDIGESTS,pG.FILELINKTOS,pG.FILEFLAGS,pG.FILEUSERNAME,pG.FILEGROUPNAME,pG.FILEVERIFYFLAGS,pG.FILEDEVICES,pG.FILEINODES,pG.FILELANGS,pG.DIRINDEXES,pG.BASENAMES]);for(let C of t){if(!S.has(C.tag))continue;let t=Array.isArray(C.value)?C.value.length:1;if(t!==n)throw Error(`gjsify ship: internal error — rpm tag ${C.tag} has ${t} values for ${n} files.`)}}function buildRequires(t,n,S){let C=[],N=[],F=[];for(let n of t){let t=parseDepend(n);C.push(t.name),N.push(senseFor(t.relation)),F.push(t.version??``)}n.post!==void 0&&(C.push(`/bin/sh`),N.push(hG.INTERP|hG.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(hG.INTERP|hG.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(hG.FIND_REQUIRES),F.push(``);for(let[t,n]of _G)C.push(t),N.push(hG.RPMLIB|hG.LESS|hG.EQUAL),F.push(n);return{names:C,flags:N,versions:F}}function buildRecommends(t){let n=[],S=[],C=[];for(let N of t){let t=parseDepend(N);n.push(t.name),S.push(senseFor(t.relation)),C.push(t.version??``)}return{names:n,flags:S,versions:C}}function senseFor(t){switch(t){case`>=`:return hG.GREATER|hG.EQUAL;case`>`:return hG.GREATER;case`<=`:return hG.LESS|hG.EQUAL;case`<`:return hG.LESS;case`=`:return hG.EQUAL;default:return 0}}function hashHex(t,n){return createHash(t).update(n).digest(`hex`)}function hashBytes(t,n){return new Uint8Array(createHash(t).update(n).digest())}var pG,mG,hG,gG,_G,vG,yG=__esmMin(()=>{hl(),$V(),sG(),dH(),_U(),fG(),fH(),hH(),mH(),pG={HEADERI18NTABLE:100,NAME:1e3,VERSION:1001,RELEASE:1002,SUMMARY:1004,DESCRIPTION:1005,BUILDTIME:1006,BUILDHOST:1007,SIZE:1009,LICENSE:1014,GROUP:1016,URL:1020,OS:1021,ARCH:1022,POSTIN:1024,POSTUN:1026,FILESIZES:1028,FILEMODES:1030,FILERDEVS:1033,FILEMTIMES:1034,FILEDIGESTS:1035,FILELINKTOS:1036,FILEFLAGS:1037,FILEUSERNAME:1039,FILEGROUPNAME:1040,SOURCERPM:1044,FILEVERIFYFLAGS:1045,PROVIDENAME:1047,REQUIREFLAGS:1048,REQUIRENAME:1049,REQUIREVERSION:1050,RECOMMENDNAME:5046,RECOMMENDVERSION:5047,RECOMMENDFLAGS:5048,RPMVERSION:1064,POSTINPROG:1086,POSTUNPROG:1088,FILEDEVICES:1095,FILEINODES:1096,FILELANGS:1097,PROVIDEFLAGS:1112,PROVIDEVERSION:1113,DIRINDEXES:1116,BASENAMES:1117,DIRNAMES:1118,PAYLOADFORMAT:1124,PAYLOADCOMPRESSOR:1125,PAYLOADFLAGS:1126,FILEDIGESTALGO:5011,ENCODING:5062,PAYLOADDIGEST:5092,PAYLOADDIGESTALGO:5093,PAYLOADDIGESTALT:5097},mG={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},hG={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},gG=8,_G=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],vG=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${pH.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${pH.metainfo}`,`/usr/share/glib-2.0`,`/usr/${pH.schemas}`,`/usr/${pH.fonts}`,`/etc`,`/opt`,`/var`])});async function assemble(t){let n=process.cwd(),S=t.os===void 0?hostLayout():resolveLayout(t.os),C=await new Config().forCommand(n),N=C.ship??{},F=C.flatpak??{},I=resolveShipApp({project:C.app,perTarget:N.app,layoutOs:S.os}),H=I.app;I.overridden&&ge.log(`${bG} runtime for ${S.name}: ${H} — \`${I.key}\` overrides \`gjsify.app${C.app===void 0?``:`: "${C.app}"`}\`.`);let W=readPackageJson$2(zn(n,`package.json`))??{},q,Y=[];if(t.target!==void 0)q=resolveFormats(t.target,S);else if(N.targets!==void 0){let t=configuredFormats(N.targets,S);q=t.formats,t.dropped.length>0&&ge.log(`${bG} \`gjsify.ship.targets\` names ${t.dropped.join(`, `)}, which wrap another layout — not built for ${S.name}. Pass --target to ask for one explicitly.`)}else{let t=defaultFormatIds(S.os).map(t=>OW[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${bG} ${Y.map(t=>t.id).join(`, `)} wrap the ${S.name} layout but cannot run \`${H}\`, which \`${I.key}\` resolves to — ${Y[0]?.interpreterGap??``}. Set \`gjsify.ship.app.${S.os}\` to "${Y[0]?.interpreters.join(`" / "`)}" to ship this OS on that runtime; it leaves every other target on \`gjsify.app\`. Assembling the layout only; pass --target to be told the same thing as an error.`)}q.some(t=>t.id===`flatpak`)&&assertNoDroppedFlatpakModules(F),t.stage||assertPackable(q,S,t.os===void 0?`host`:`positional`,Y);let X=resolveSignPlan({flag:t.sign,config:N.sign,layoutOs:S.os}),Z=resolveNotaryPlan({flag:t.notarize,layoutOs:S.os,sign:X});if(t.stage&&assertNothingToSignYet(t),t.stage||(announceSigning(X,Z),X.kind===`sign`&&assertHostCanSign(X.signer)),t.stage||assertKindCanPack(q,resolveShipKind(N,F)),!t.stage)for(let t of q)assertCanPack(t);let te=parseDeclaredChannel(t.channel,`--channel`)??parseDeclaredChannel(N.channel,`gjsify.ship.channel`)??(q.some(t=>t.id===`flatpak`)?`flathub`:void 0),ne=parseDeclaredPricing(t.pricing,`--pricing`)??parseDeclaredPricing(N.pricing,`gjsify.ship.pricing`)??`free`;t[`skip-build`]||await runProjectBuild(n,te,ne);let re=resolveShipBundle({pkg:W,ship:N,layoutOs:S.os});re.overridden&&ge.log(`${bG} entry for ${S.name}: ${re.declared} — \`${re.key}\` overrides \`gjsify.main\`.`);let ie=discoverPayload({projectDir:n,pkg:W,ship:N,flatpakIcon:F.icon,declaredBundle:re.declared,layoutOs:S.os,foreignBundles:re.foreign}),{settings:ae,metadata:oe,warnings:Q}=resolveShipSettings({projectDir:n,pkg:W,ship:N,flatpak:F,cli:{outDir:t.out,arch:t.arch,layoutOs:S.os},discovered:ie,app:H});for(let t of Q)ge.warn(`${bG} ${t}`);for(let t of q)assertFormatCanRunInterpreter(t,ae.app);let se=readFileSync(ae.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:ae.app,source:se,entry:Bn(n,ae.bundlePath)||ae.bundlePath,appKey:I.key,bundleKey:re.key,layoutOs:S.os});let ce=buildTimestamp(ae.bundlePath),le={appId:ae.appId,name:ae.name,command:ae.binaryName,kind:ae.kind,metadata:oe,channel:te,configKey:`gjsify.ship`,copyrightYear:new Date(ce*1e3).getUTCFullYear()};for(let t of validateAppMetadata(le))ge.warn(`${bG} ${t.field} is not set — ${t.hint}`);ae.licenseFile!==void 0&&Hn(ae.licenseFile)!==n&&ge.log(`${bG} licence text from ${Bn(n,ae.licenseFile)} (this package carries none of its own)`);let ue=localizeMetadata({metainfo:ae.kind===`app`?renderMetainfoApp$1(le):renderMetainfoCli$1(le),desktopEntry:ae.kind===`app`?renderDesktopEntry(le):void 0},ae.localeFiles),de=await resolveCarriedRuntime(S,ae,n);carryNodeModules(de,S,ae,n,N.nodeModules,N.nodeModulesExclude);let fe=stageSubordinates({layout:S,identity:ae,nestedBundles:ae.nestedBundles,helperExecutables:ae.helperExecutables,mainExecutable:ae.mainExecutableSource}),pe={bundleFiles:ie.bundleFiles,launcher:renderLauncher(ae,Un(ae.bundlePath),S,de.launcher),executableLaunchers:Object.fromEntries(ae.executables.map(t=>[t.name,renderLauncher(ae,t.entry,S,de.launcher)])),metainfo:ue.metainfo,desktopEntry:ue.desktopEntry,licenseText:ae.licenseFile===void 0?void 0:readFileSync(ae.licenseFile,`utf-8`),changelogText:ae.changelogFile===void 0?void 0:readFileSync(ae.changelogFile,`utf-8`),mtime:ce},me=In(n,ae.outDir),he=zn(me,`stage`),_e=[...planStage(ae,pe),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:ae.schemaFiles,workDir:zn(me,`schemas`)})],ve=ae.kind===`app`&&S.icon!==void 0&&(S.icon.required||ae.iconFiles.length>0)?await resolveAppIcon({iconFiles:ae.iconFiles,appId:ae.appId,sizes:S.icon.sizes,target:S.icon.writes}):void 0;ve!==void 0&&ge.log(`${bG} icon: ${iconSizes(ve).join(`/`)} px, ${ve.source}`);let ye=placeStage(S,{...ae,icon:ve,categories:oe.categories},_e,[...de.files,...fe.files]);if(writeStage(he,ye),ge.log(`${bG} staged ${ye.length} file(s) for ${S.name} in ${Bn(n,he)}/`),t.verbose)for(let t of ye)ge.log(`${bG} ${t.path}`);if(assertPayloadMatchesArch(readStage([he],ye),ae.arch,{exempt:payloadArchExemptions(S.os,ae)}),S.os!==`linux`){let t=linuxInstallDependent(_e);if(t.length>0){ge.warn(`${bG} the ${S.name} layout carries ${t.length} file(s) whose Linux correctness comes from a package install step it has no equivalent for:`);let n={aborts:`ABORTS: `,unknown:`UNCLASSIFIED: `,inert:``};for(let{path:S,verdict:C,why:N}of t)ge.warn(`${bG} ${n[C]??``}${S} — ${N}`)}for(let t of de.found)ge.log(`${bG} carries its own ${t}`);for(let t of de.missing)ge.warn(`${bG} ${t}`);de.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${bG} ${S.runtimeGap}`),S.fontGap!==void 0&&_e.some(t=>isUnder(t.path,pH.fonts))&&ge.warn(`${bG} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(ae.arch)&&ge.warn(`${bG} this stage is labelled ${ae.arch} and the ${S.name} layout has no runtime for it — ${S.arches.why}. Nothing can pack this stage; \`--arch ${S.arches.only.join(`|`)}\` is what produces an artifact.`)}let be=scanGiRequirements(se),xe=be.namespaces,Se=be.optional;if(t.verbose){let t=xe.filter(t=>!Se.includes(t));ge.log(`${bG} gi namespaces: ${xe.join(`, `)||`(none)`}`),Se.length>0&&(ge.log(`${bG} gi optional namespaces: ${Se.join(`, `)}`),ge.log(`${bG} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let Ce=new Map;for(let t of q)Ce.set(t.id,(await planOverlay(ae,t,pe)).map(t=>({...t,path:place(S,ae,t.path)})));let we=readPayloadFacts(_e);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:xe,optionalNamespaces:Se,hasIcons:we.hasIcons,hasSchemas:we.hasSchemas,interpreter:ae.app,extra:ae.extraDepends[t.depends],typelibPackages:ae.typelibPackages,bundledTypelibs:we.bundledTypelibs,minGjsVersion:ae.minGjsVersion,minNodeVersion:ae.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${bG} gi://${S} is imported optionally, but no ${t.depends} package is known to ship its typelib, so no Recommends entry names it. The package builds and runs without it. Add the row if the namespace should be recommended: \`gjsify.ship.typelibPackages.${S} = { "${t.depends}": "…" }\`.`);let S=ae.app===`node`?warnAboutNodeFloor(t.depends,ae.minNodeVersion):warnAboutGjsFloor(t.depends,ae.minGjsVersion);for(let t of S)ge.warn(`${bG} ${t}`)}let Te=writeStageManifest({stageDir:he,settings:ae,formats:q,mtime:ce,namespaces:xe,optionalNamespaces:Se,staged:ye,overlay:Ce});if(t.stage){let t=Y.length>0?`(none — ${Y.map(t=>t.id).join(` and `)} need \`gjsify.ship.app.${S.os}: "node"\`)`:formatIdsFor(S.os).length===0?`(none — no format wraps the ${S.name} layout)`:`(none asked for)`,n=Te.formats.join(`, `)||t;ge.log(`${bG} stage manifest: ${formatTarget(Te.target)}, formats ${n}`);return}let Ee=[];for(let n of q)Ee.push(await packOne({format:n,settings:ae,arch:ae.arch,staged:ye,overlay:Ce.get(n.id)??[],stageDir:he,outRoot:me,namespaces:xe,optionalNamespaces:Se,mtime:ce,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,Ee)}function assertNothingToSignYet(t){let n=t.sign===void 0?t.notarize===void 0?void 0:`--notarize`:`--sign`;if(n!==void 0)throw Error(`gjsify ship: ${n} belongs to the finish phase, and --stage produces no artifact to sign — it writes the tree a packing host reads back. Assemble here, then run \`gjsify ship --from-stage <dir> --sign <identity>\` on the host that holds the identity (ADR 0024 § A2, § A14).`)}function announceSigning(t,n){t.kind===`skip`&&ge.warn(`${bG} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${bG} ${n.message}`)}async function resolveCarriedRuntime(t,n,S){let C={files:[],launcher:{},found:[],missing:[]};if(t.os===`linux`||n.app!==`node`)return C;let N=`${t.os}-${n.arch}`;if(!isGtkRuntimeTarget(N))return C;let F=await acquireGtkRuntime({target:N,version:cliVersion(),discovery:{cwd:S},ensure:async S=>(await ensurePkgDir(parseSpec(S),{verbose:!1,cacheMaxAge:SG,frozen:!1,platform:{os:t.os,cpu:n.arch}})).pkgDir,log:t=>ge.log(`${bG} ${t}`)});return stageAppRuntime({layout:t,identity:n,target:N,cwd:S,interpreter:isNodeRuntimeTarget(N)?resolveNodeRuntime(N,{cwd:S}):null,...F.kind===`fetched`?{fetchedGtkRuntimeDir:F.dir}:{},...F.kind===`failed`?{gtkFetchFailure:F.reason}:{}})}function carryNodeModules(t,n,S,C,N,F){if(N===void 0||N.length===0)return;let I=resolveNodeModulesClosure(N,C,{target:{os:n.os,cpu:S.arch},exclude:F});t.files.push(...stageNodeModules(I,n.dirs(S).bundle)),t.found.push(`node_modules: ${I.packages.length} package(s) for ${N.join(`, `)}`),I.skippedPrebuilds!==void 0&&I.skippedPrebuilds.length>0&&ge.log(`${bG} node_modules: left out, prebuilds for another platform than ${n.os}-${S.arch}: `+I.skippedPrebuilds.join(`, `)),I.excluded.length>0&&ge.log(`${bG} node_modules: left out by gjsify.ship.nodeModulesExclude: ${I.excluded.join(`, `)}`),I.skippedForTarget.length>0&&ge.log(`${bG} node_modules: left out, installed but built for another platform than ${n.os}-${S.arch}: `+I.skippedForTarget.join(`, `)),I.skippedOptional.length>0&&ge.log(`${bG} node_modules: ${I.skippedOptional.length} optional dependenc(ies) not installed, so not carried (other platforms' builds): ${I.skippedOptional.join(`, `)}`)}async function finishFromStage(t,n){if(t.stage)throw Error("gjsify ship: --stage and --from-stage are the two halves of one split and cannot run together. `--stage` assembles a payload and stops; `--from-stage <dir>` packs one that is already assembled. Run them as two commands, on the host each belongs on (ADR 0024 § A2).");if(t[`skip-build`])throw Error(`gjsify ship: --from-stage never runs a build — the payload it packs was built and staged by an earlier run — so --skip-build has nothing to skip. Drop it.`);if(t.arch!==void 0)throw Error("gjsify ship: --arch is decided when the stage is assembled, not when it is packed: the launcher, the payload and the recorded target were all fixed then. Pass --arch to `gjsify ship --stage`, and use `--expect-target <os>-<arch>` here to assert which leg you are packing.");if(t.os!==void 0)throw Error(`gjsify ship: the layout is decided when the stage is assembled, so "${t.os}" has nothing to change here — the staged tree already IS one OS's layout. Use \`--expect-target <os>-<arch>\` to assert which one you are packing.`);let S=process.cwd(),C=In(S,n),N=readStageManifest(C);assertExpectedTarget(N,t[`expect-target`]);let F=layoutForOs(N.target.os);t.target===void 0&&assertPackable(N.formats.map(t=>OW[t]),F,`stage`,defaultFormatIds(F.os).map(t=>OW[t]).filter(t=>!t.interpreters.includes(N.settings.app)));let I=resolveFormats(t.target??N.formats,F);assertFormatsStaged(N,I);for(let t of I)assertCanPack(t);let H=resolveSignPlan({flag:t.sign,layoutOs:F.os}),W=resolveNotaryPlan({flag:t.notarize,layoutOs:F.os,sign:H});announceSigning(H,W),H.kind===`sign`&&assertHostCanSign(H.signer);for(let t of warnOnToolSkew(N))ge.warn(`${bG} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${bG} ${t}`);if(ge.log(`${bG} packing ${N.settings.binaryName} ${N.settings.version}-${N.settings.release} for ${formatTarget(N.target)} from ${Bn(S,C)||`.`}/`),t.verbose){for(let t of N.staged)ge.log(`${bG} ${t.path}`);ge.log(`${bG} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${bG} gi optional namespaces: ${N.optionalNamespaces?.join(`, `)}`)}let X=t.out===void 0?Hn(C):In(S,t.out),Z=[];for(let n of I){if(assertFormatCanRunInterpreter(n,N.settings.app),n.depends!==null){let t=N.settings.app===`node`?warnAboutNodeFloor(n.depends,N.settings.minNodeVersion):warnAboutGjsFloor(n.depends,N.settings.minGjsVersion);for(let n of t)ge.warn(`${bG} ${n}`)}Z.push(await packOne({format:n,settings:N.settings,arch:N.target.arch,staged:N.staged,overlay:overlayFiles(N,n.id),stageDir:C,outRoot:X,namespaces:N.namespaces,optionalNamespaces:N.optionalNamespaces??[],mtime:q,sign:H,notarize:W,verbose:t.verbose}))}printArtifacts(S,Z)}async function packOne(t){let{format:n,settings:S,stageDir:C,outRoot:N,mtime:F}=t;assertOverlayIsLicensed(n.id,S.binaryName,t.overlay);let I=zn(N,`overlay`,n.id);writeStage(I,t.overlay);let H=readStage([C,I],[...t.staged,...t.overlay]),W=readPayloadFacts(H),q=n.depends===null?{requires:[],recommends:[],unmappedOptional:[]}:deriveDepends(n.depends,{namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,hasIcons:W.hasIcons,hasSchemas:W.hasSchemas,interpreter:S.app,extra:S.extraDepends[n.depends],typelibPackages:S.typelibPackages,bundledTypelibs:W.bundledTypelibs,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion}),Y=q.requires,X=q.recommends;assertPayloadMatchesArch(H,t.arch,{exempt:payloadArchExemptions(n.layoutOs,S)});let Z=layoutForOs(n.layoutOs);assertLauncherMatchesInterpreter(H,Z,S,S.app),assertLayoutSupportsArch(Z,t.arch);let te=signedSubordinatesFor(Z,S,S),ne=t.sign.kind===`sign`?await signPayload({payload:H,identity:t.sign.identity,signer:t.sign.signer,workDir:zn(N,`signed`,n.id),bundleRoot:Z.root(S),entitlementsPath:zn(N,`signed`,`${n.id}.entitlements.plist`),nestedBundles:te.nestedBundles,helperExecutables:te.helperExecutables,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)}):H,re=n.archName(t.arch,isArchIndependent(ne)),ie={settings:S,payload:ne,prefix:n.prefix,depends:Y,recommends:X,archLabel:re,mtime:F},ae=zn(N,`out`);mkdirSync(ae,{recursive:!0});let oe=zn(ae,n.fileName(S,re));switch(n.id){case`deb`:writeFileSync(oe,await buildDeb(ie));break;case`rpm`:writeFileSync(oe,await buildRpm(ie));break;case`flatpak`:await buildFlatpakBundle({settings:S,stageDir:C,overlayDir:I,stageManifestFile:XW,workDir:zn(N,`flatpak`),target:oe,archLabel:re,verbose:t.verbose});break;case`appimage`:{let n=appImageHostRequirements({app:S.app,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion,namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,bundledTypelibs:W.bundledTypelibs}),C=appDirFor(N),I=appDirPayload(S,ne,n,await compileSchemasForPayload({payload:ne,workDir:zn(N,`appimage-schemas`)}));writePayload(C,I,``),stampAppDirTimes(C,I,F),ge.log(`${bG} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(re);ge.log(`${bG} ${appImageRuntimeNotice(re,H)}`),await buildAppImage({appDir:C,target:oe,archLabel:re,runtimeFile:H,workDir:Hn(C),verbose:t.verbose});break}case`linux-tar`:case`linux-tar-flatpak`:{let t=n.id===`linux-tar-flatpak`?await compileSchemasForPayload({payload:ne,workDir:zn(N,`tar-schemas`)}):void 0;writeFileSync(oe,await buildLinuxTarball({settings:S,payload:t===void 0?ne:[...ne,t],archLabel:re,mtime:F}));break}case`macos-app`:case`windows-dir`:writePayload(oe,ne,Z.root(S));break;case`macos-app-dmg`:{let n=dmgVolumeDir(N);if(writePayload(n,ne,``),t.notarize.kind===`notarize`){let C=t.notarize,N=zn(n,`${S.name}.app`),I=zn(Hn(n),`bundle-notarize.zip`);await stapleBundleBeforeImage({writeArchive:()=>writeFileSync(I,buildZip(zipEntriesFromPayload(ne),F)),notarize:()=>notarizeArtifact({plan:C,artifact:I,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)}),staple:()=>stapleArtifact({notary:C.notary,artifact:N,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)})})}addApplicationsLink(n),await buildDmgImage({volumeName:dmgVolumeName(S),sourceDir:n,target:oe,workDir:Hn(n),verbose:t.verbose}),t.sign.kind===`sign`&&await signDmgImage({identity:t.sign.identity,file:oe,adhoc:t.sign.identity===`-`,workDir:Hn(n),verbose:t.verbose});break}case`macos-app-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne),F));break;case`windows-dir-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne,windowsProgramDirName(S)),F));break;case`msi`:{let n=zn(N,`msi`);writePayload(zn(n,PW),ne,Z.root(S)),await buildMsi({settings:S,files:ne.map(t=>({path:t.path,source:`${PW}/${t.path}`})),programDirName:windowsProgramDirName(S),archLabel:re,workDir:n,target:oe,verbose:t.verbose});break}default:{let t=n.id;throw Error(`gjsify ship: no packer is wired for format "${String(t)}".`)}}let Q=n.artifactKind===`directory`?directorySize(oe):statSync(oe).size,se=!1,ce=!1;if(t.notarize.kind===`notarize`&&(n.artifactKind===`directory`?ge.warn(`${bG} ${n.id} is a directory, and notarytool submits an archive or an installer — not notarised. The container format beside it is what carries the ticket.`):(await notarizeArtifact({plan:t.notarize,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)}),se=!0,canCarryTicket(n.id)?(await stapleArtifact({notary:t.notarize.notary,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)}),ce=!0):ge.warn(`${bG} ${n.id} is notarised and NOT stapled: \`stapler\` takes a UDIF image, a signed flat package or a code-signed bundle, and an archive is none of them. Apple's remedy is to staple each item that went INTO the archive and re-create it — for this artifact that is the \`.app\`, which \`--target macos-app\` writes beside it.`))),n.artifactKind===`file`){let S=writeReleaseRecord({file:oe,format:n.id,os:n.layoutOs,arch:isArchIndependent(ne)?`noarch`:t.arch,signature:recordedSignature(t.sign.kind===`sign`?t.sign.identity:void 0,`-`),notarized:se,stapled:ce,nestedBundles:recordedNestedBundles(ne,te.nestedBundles),generator:`@gjsify/cli ${cliVersion()}`});t.verbose&&ge.log(`${bG} release record: ${S}`)}return{format:n.id,path:oe,size:Q}}function printArtifacts(t,n){for(let S of n)ge.log(`${bG} ${S.format}: ${Bn(t,S.path)} (${S.size} bytes)`)}function assertCanPack(t){assertHostCanFinish(t),assertToolsInstalled(t)}function assertPackable(t,n,S,C=[]){if(t.length>0)return;if(C.length>0)throw Error(`gjsify ship: ${C.map(t=>t.id).join(` and `)} wrap the ${n.name} layout, and neither can run this project — ${C[0]?.interpreterGap??``}.\n Set \`gjsify.ship.app.${n.os}\` to "${C[0]?.interpreters.join(`" / "`)}" — it overrides \`gjsify.app\` for THIS target and\n leaves every other one alone, which is what lets one project be GJS on Linux and Node here.
1191
+ `)]},{tag:pG.BUILDTIME,type:4,value:[t.mtime]},{tag:pG.BUILDHOST,type:6,value:`localhost`},{tag:pG.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:pG.LICENSE,type:6,value:N.license},{tag:pG.GROUP,type:9,value:[N.group]},{tag:pG.OS,type:6,value:`linux`},{tag:pG.ARCH,type:6,value:t.archLabel},{tag:pG.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:pG.RPMVERSION,type:6,value:`4.20.0`},{tag:pG.ENCODING,type:6,value:`utf-8`},{tag:pG.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:pG.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:pG.FILERDEVS,type:3,value:n.map(()=>0)},{tag:pG.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:pG.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:pG.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:pG.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:pG.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:pG.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:pG.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:pG.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:pG.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:pG.FILELANGS,type:8,value:n.map(()=>``)},{tag:pG.FILEDIGESTALGO,type:4,value:[gG]},{tag:pG.DIRINDEXES,type:4,value:H},{tag:pG.BASENAMES,type:8,value:W},{tag:pG.DIRNAMES,type:8,value:I},{tag:pG.PROVIDENAME,type:8,value:[N.binaryName]},{tag:pG.PROVIDEFLAGS,type:4,value:[hG.EQUAL]},{tag:pG.PROVIDEVERSION,type:8,value:[F]},{tag:pG.REQUIRENAME,type:8,value:Y.names},{tag:pG.REQUIREFLAGS,type:4,value:Y.flags},{tag:pG.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:pG.RECOMMENDNAME,type:8,value:X.names},{tag:pG.RECOMMENDFLAGS,type:4,value:X.flags},{tag:pG.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:pG.PAYLOADFORMAT,type:6,value:`cpio`},{tag:pG.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:pG.PAYLOADFLAGS,type:6,value:`9`},{tag:pG.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:pG.PAYLOADDIGESTALGO,type:4,value:[gG]},{tag:pG.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:pG.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:pG.POSTIN,type:6,value:q.post}),Z.push({tag:pG.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:pG.POSTUN,type:6,value:q.postun}),Z.push({tag:pG.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([pG.FILESIZES,pG.FILEMODES,pG.FILERDEVS,pG.FILEMTIMES,pG.FILEDIGESTS,pG.FILELINKTOS,pG.FILEFLAGS,pG.FILEUSERNAME,pG.FILEGROUPNAME,pG.FILEVERIFYFLAGS,pG.FILEDEVICES,pG.FILEINODES,pG.FILELANGS,pG.DIRINDEXES,pG.BASENAMES]);for(let C of t){if(!S.has(C.tag))continue;let t=Array.isArray(C.value)?C.value.length:1;if(t!==n)throw Error(`gjsify ship: internal error — rpm tag ${C.tag} has ${t} values for ${n} files.`)}}function buildRequires(t,n,S){let C=[],N=[],F=[];for(let n of t){let t=parseDepend(n);C.push(t.name),N.push(senseFor(t.relation)),F.push(t.version??``)}n.post!==void 0&&(C.push(`/bin/sh`),N.push(hG.INTERP|hG.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(hG.INTERP|hG.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(hG.FIND_REQUIRES),F.push(``);for(let[t,n]of _G)C.push(t),N.push(hG.RPMLIB|hG.LESS|hG.EQUAL),F.push(n);return{names:C,flags:N,versions:F}}function buildRecommends(t){let n=[],S=[],C=[];for(let N of t){let t=parseDepend(N);n.push(t.name),S.push(senseFor(t.relation)),C.push(t.version??``)}return{names:n,flags:S,versions:C}}function senseFor(t){switch(t){case`>=`:return hG.GREATER|hG.EQUAL;case`>`:return hG.GREATER;case`<=`:return hG.LESS|hG.EQUAL;case`<`:return hG.LESS;case`=`:return hG.EQUAL;default:return 0}}function hashHex(t,n){return createHash(t).update(n).digest(`hex`)}function hashBytes(t,n){return new Uint8Array(createHash(t).update(n).digest())}var pG,mG,hG,gG,_G,vG,yG=__esmMin(()=>{hl(),$V(),sG(),dH(),_U(),fG(),fH(),hH(),mH(),pG={HEADERI18NTABLE:100,NAME:1e3,VERSION:1001,RELEASE:1002,SUMMARY:1004,DESCRIPTION:1005,BUILDTIME:1006,BUILDHOST:1007,SIZE:1009,LICENSE:1014,GROUP:1016,URL:1020,OS:1021,ARCH:1022,POSTIN:1024,POSTUN:1026,FILESIZES:1028,FILEMODES:1030,FILERDEVS:1033,FILEMTIMES:1034,FILEDIGESTS:1035,FILELINKTOS:1036,FILEFLAGS:1037,FILEUSERNAME:1039,FILEGROUPNAME:1040,SOURCERPM:1044,FILEVERIFYFLAGS:1045,PROVIDENAME:1047,REQUIREFLAGS:1048,REQUIRENAME:1049,REQUIREVERSION:1050,RECOMMENDNAME:5046,RECOMMENDVERSION:5047,RECOMMENDFLAGS:5048,RPMVERSION:1064,POSTINPROG:1086,POSTUNPROG:1088,FILEDEVICES:1095,FILEINODES:1096,FILELANGS:1097,PROVIDEFLAGS:1112,PROVIDEVERSION:1113,DIRINDEXES:1116,BASENAMES:1117,DIRNAMES:1118,PAYLOADFORMAT:1124,PAYLOADCOMPRESSOR:1125,PAYLOADFLAGS:1126,FILEDIGESTALGO:5011,ENCODING:5062,PAYLOADDIGEST:5092,PAYLOADDIGESTALGO:5093,PAYLOADDIGESTALT:5097},mG={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},hG={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},gG=8,_G=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],vG=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${pH.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${pH.metainfo}`,`/usr/share/glib-2.0`,`/usr/${pH.schemas}`,`/usr/${pH.fonts}`,`/etc`,`/opt`,`/var`])});async function assemble(t){let n=process.cwd(),S=t.os===void 0?hostLayout():resolveLayout(t.os),C=await new Config().forCommand(n),N=C.ship??{},F=C.flatpak??{},I=resolveShipApp({project:C.app,perTarget:N.app,layoutOs:S.os}),H=I.app;I.overridden&&ge.log(`${bG} runtime for ${S.name}: ${H} — \`${I.key}\` overrides \`gjsify.app${C.app===void 0?``:`: "${C.app}"`}\`.`);let W=readPackageJson$2(zn(n,`package.json`))??{},q,Y=[];if(t.target!==void 0)q=resolveFormats(t.target,S);else if(N.targets!==void 0){let t=configuredFormats(N.targets,S);q=t.formats,t.dropped.length>0&&ge.log(`${bG} \`gjsify.ship.targets\` names ${t.dropped.join(`, `)}, which wrap another layout — not built for ${S.name}. Pass --target to ask for one explicitly.`)}else{let t=defaultFormatIds(S.os).map(t=>OW[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${bG} ${Y.map(t=>t.id).join(`, `)} wrap the ${S.name} layout but cannot run \`${H}\`, which \`${I.key}\` resolves to — ${Y[0]?.interpreterGap??``}. Set \`gjsify.ship.app.${S.os}\` to "${Y[0]?.interpreters.join(`" / "`)}" to ship this OS on that runtime; it leaves every other target on \`gjsify.app\`. Assembling the layout only; pass --target to be told the same thing as an error.`)}q.some(t=>t.id===`flatpak`)&&assertNoDroppedFlatpakModules(F),t.stage||assertPackable(q,S,t.os===void 0?`host`:`positional`,Y);let X=resolveSignPlan({flag:t.sign,config:N.sign,layoutOs:S.os}),Z=resolveNotaryPlan({flag:t.notarize,layoutOs:S.os,sign:X});if(t.stage&&assertNothingToSignYet(t),t.stage||(announceSigning(X,Z),X.kind===`sign`&&assertHostCanSign(X.signer)),t.stage||assertKindCanPack(q,resolveShipKind(N,F)),!t.stage)for(let t of q)assertCanPack(t);let te=parseDeclaredChannel(t.channel,`--channel`)??parseDeclaredChannel(N.channel,`gjsify.ship.channel`)??(q.some(t=>t.id===`flatpak`)?`flathub`:void 0),ne=parseDeclaredPricing(t.pricing,`--pricing`)??parseDeclaredPricing(N.pricing,`gjsify.ship.pricing`)??`free`;t[`skip-build`]||await runProjectBuild(n,te,ne);let re=resolveShipBundle({pkg:W,ship:N,layoutOs:S.os});re.overridden&&ge.log(`${bG} entry for ${S.name}: ${re.declared} — \`${re.key}\` overrides \`gjsify.main\`.`);let ie=discoverPayload({projectDir:n,pkg:W,ship:N,flatpakIcon:F.icon,declaredBundle:re.declared,layoutOs:S.os,foreignBundles:re.foreign}),{settings:ae,metadata:oe,warnings:Q}=resolveShipSettings({projectDir:n,pkg:W,ship:N,flatpak:F,cli:{outDir:t.out,arch:t.arch,layoutOs:S.os},discovered:ie,app:H});for(let t of Q)ge.warn(`${bG} ${t}`);for(let t of q)assertFormatCanRunInterpreter(t,ae.app);let se=readFileSync(ae.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:ae.app,source:se,entry:Bn(n,ae.bundlePath)||ae.bundlePath,appKey:I.key,bundleKey:re.key,layoutOs:S.os});let ce=buildTimestamp(ae.bundlePath),le={appId:ae.appId,name:ae.name,command:ae.binaryName,kind:ae.kind,metadata:oe,desktopExecArgs:ae.desktopExecArgs,channel:te,configKey:`gjsify.ship`,copyrightYear:new Date(ce*1e3).getUTCFullYear()};for(let t of validateAppMetadata(le))ge.warn(`${bG} ${t.field} is not set — ${t.hint}`);ae.licenseFile!==void 0&&Hn(ae.licenseFile)!==n&&ge.log(`${bG} licence text from ${Bn(n,ae.licenseFile)} (this package carries none of its own)`);let ue=localizeMetadata({metainfo:ae.kind===`app`?renderMetainfoApp$1(le):renderMetainfoCli$1(le),desktopEntry:ae.kind===`app`?renderDesktopEntry(le):void 0},ae.localeFiles),de=await resolveCarriedRuntime(S,ae,n);carryNodeModules(de,S,ae,n,N.nodeModules,N.nodeModulesExclude);let fe=stageSubordinates({layout:S,identity:ae,nestedBundles:ae.nestedBundles,helperExecutables:ae.helperExecutables,mainExecutable:ae.mainExecutableSource}),pe={bundleFiles:ie.bundleFiles,launcher:renderLauncher(ae,Un(ae.bundlePath),S,de.launcher),executableLaunchers:Object.fromEntries(ae.executables.map(t=>[t.name,renderLauncher(ae,t.entry,S,de.launcher)])),metainfo:ue.metainfo,desktopEntry:ue.desktopEntry,licenseText:ae.licenseFile===void 0?void 0:readFileSync(ae.licenseFile,`utf-8`),changelogText:ae.changelogFile===void 0?void 0:readFileSync(ae.changelogFile,`utf-8`),mtime:ce},me=In(n,ae.outDir),he=zn(me,`stage`),_e=[...planStage(ae,pe),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:ae.schemaFiles,workDir:zn(me,`schemas`)})],ve=ae.kind===`app`&&S.icon!==void 0&&(S.icon.required||ae.iconFiles.length>0)?await resolveAppIcon({iconFiles:ae.iconFiles,appId:ae.appId,sizes:S.icon.sizes,target:S.icon.writes}):void 0;ve!==void 0&&ge.log(`${bG} icon: ${iconSizes(ve).join(`/`)} px, ${ve.source}`);let ye=placeStage(S,{...ae,icon:ve,categories:oe.categories},_e,[...de.files,...fe.files]);if(writeStage(he,ye),ge.log(`${bG} staged ${ye.length} file(s) for ${S.name} in ${Bn(n,he)}/`),t.verbose)for(let t of ye)ge.log(`${bG} ${t.path}`);if(assertPayloadMatchesArch(readStage([he],ye),ae.arch,{exempt:payloadArchExemptions(S.os,ae)}),S.os!==`linux`){let t=linuxInstallDependent(_e);if(t.length>0){ge.warn(`${bG} the ${S.name} layout carries ${t.length} file(s) whose Linux correctness comes from a package install step it has no equivalent for:`);let n={aborts:`ABORTS: `,unknown:`UNCLASSIFIED: `,inert:``};for(let{path:S,verdict:C,why:N}of t)ge.warn(`${bG} ${n[C]??``}${S} — ${N}`)}for(let t of de.found)ge.log(`${bG} carries its own ${t}`);for(let t of de.missing)ge.warn(`${bG} ${t}`);de.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${bG} ${S.runtimeGap}`),S.fontGap!==void 0&&_e.some(t=>isUnder(t.path,pH.fonts))&&ge.warn(`${bG} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(ae.arch)&&ge.warn(`${bG} this stage is labelled ${ae.arch} and the ${S.name} layout has no runtime for it — ${S.arches.why}. Nothing can pack this stage; \`--arch ${S.arches.only.join(`|`)}\` is what produces an artifact.`)}let be=scanGiRequirements(se),xe=be.namespaces,Se=be.optional;if(t.verbose){let t=xe.filter(t=>!Se.includes(t));ge.log(`${bG} gi namespaces: ${xe.join(`, `)||`(none)`}`),Se.length>0&&(ge.log(`${bG} gi optional namespaces: ${Se.join(`, `)}`),ge.log(`${bG} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let Ce=new Map;for(let t of q)Ce.set(t.id,(await planOverlay(ae,t,pe)).map(t=>({...t,path:place(S,ae,t.path)})));let we=readPayloadFacts(_e);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:xe,optionalNamespaces:Se,hasIcons:we.hasIcons,hasSchemas:we.hasSchemas,interpreter:ae.app,extra:ae.extraDepends[t.depends],typelibPackages:ae.typelibPackages,bundledTypelibs:we.bundledTypelibs,minGjsVersion:ae.minGjsVersion,minNodeVersion:ae.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${bG} gi://${S} is imported optionally, but no ${t.depends} package is known to ship its typelib, so no Recommends entry names it. The package builds and runs without it. Add the row if the namespace should be recommended: \`gjsify.ship.typelibPackages.${S} = { "${t.depends}": "…" }\`.`);let S=ae.app===`node`?warnAboutNodeFloor(t.depends,ae.minNodeVersion):warnAboutGjsFloor(t.depends,ae.minGjsVersion);for(let t of S)ge.warn(`${bG} ${t}`)}let Te=writeStageManifest({stageDir:he,settings:ae,formats:q,mtime:ce,namespaces:xe,optionalNamespaces:Se,staged:ye,overlay:Ce});if(t.stage){let t=Y.length>0?`(none — ${Y.map(t=>t.id).join(` and `)} need \`gjsify.ship.app.${S.os}: "node"\`)`:formatIdsFor(S.os).length===0?`(none — no format wraps the ${S.name} layout)`:`(none asked for)`,n=Te.formats.join(`, `)||t;ge.log(`${bG} stage manifest: ${formatTarget(Te.target)}, formats ${n}`);return}let Ee=[];for(let n of q)Ee.push(await packOne({format:n,settings:ae,arch:ae.arch,staged:ye,overlay:Ce.get(n.id)??[],stageDir:he,outRoot:me,namespaces:xe,optionalNamespaces:Se,mtime:ce,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,Ee)}function assertNothingToSignYet(t){let n=t.sign===void 0?t.notarize===void 0?void 0:`--notarize`:`--sign`;if(n!==void 0)throw Error(`gjsify ship: ${n} belongs to the finish phase, and --stage produces no artifact to sign — it writes the tree a packing host reads back. Assemble here, then run \`gjsify ship --from-stage <dir> --sign <identity>\` on the host that holds the identity (ADR 0024 § A2, § A14).`)}function announceSigning(t,n){t.kind===`skip`&&ge.warn(`${bG} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${bG} ${n.message}`)}async function resolveCarriedRuntime(t,n,S){let C={files:[],launcher:{},found:[],missing:[]};if(t.os===`linux`||n.app!==`node`)return C;let N=`${t.os}-${n.arch}`;if(!isGtkRuntimeTarget(N))return C;let F=await acquireGtkRuntime({target:N,version:cliVersion(),discovery:{cwd:S},ensure:async S=>(await ensurePkgDir(parseSpec(S),{verbose:!1,cacheMaxAge:SG,frozen:!1,platform:{os:t.os,cpu:n.arch}})).pkgDir,log:t=>ge.log(`${bG} ${t}`)});return stageAppRuntime({layout:t,identity:n,target:N,cwd:S,interpreter:isNodeRuntimeTarget(N)?resolveNodeRuntime(N,{cwd:S}):null,...F.kind===`fetched`?{fetchedGtkRuntimeDir:F.dir}:{},...F.kind===`failed`?{gtkFetchFailure:F.reason}:{}})}function carryNodeModules(t,n,S,C,N,F){if(N===void 0||N.length===0)return;let I=resolveNodeModulesClosure(N,C,{target:{os:n.os,cpu:S.arch},exclude:F});t.files.push(...stageNodeModules(I,n.dirs(S).bundle)),t.found.push(`node_modules: ${I.packages.length} package(s) for ${N.join(`, `)}`),I.skippedPrebuilds!==void 0&&I.skippedPrebuilds.length>0&&ge.log(`${bG} node_modules: left out, prebuilds for another platform than ${n.os}-${S.arch}: `+I.skippedPrebuilds.join(`, `)),I.excluded.length>0&&ge.log(`${bG} node_modules: left out by gjsify.ship.nodeModulesExclude: ${I.excluded.join(`, `)}`),I.skippedForTarget.length>0&&ge.log(`${bG} node_modules: left out, installed but built for another platform than ${n.os}-${S.arch}: `+I.skippedForTarget.join(`, `)),I.skippedOptional.length>0&&ge.log(`${bG} node_modules: ${I.skippedOptional.length} optional dependenc(ies) not installed, so not carried (other platforms' builds): ${I.skippedOptional.join(`, `)}`)}async function finishFromStage(t,n){if(t.stage)throw Error("gjsify ship: --stage and --from-stage are the two halves of one split and cannot run together. `--stage` assembles a payload and stops; `--from-stage <dir>` packs one that is already assembled. Run them as two commands, on the host each belongs on (ADR 0024 § A2).");if(t[`skip-build`])throw Error(`gjsify ship: --from-stage never runs a build — the payload it packs was built and staged by an earlier run — so --skip-build has nothing to skip. Drop it.`);if(t.arch!==void 0)throw Error("gjsify ship: --arch is decided when the stage is assembled, not when it is packed: the launcher, the payload and the recorded target were all fixed then. Pass --arch to `gjsify ship --stage`, and use `--expect-target <os>-<arch>` here to assert which leg you are packing.");if(t.os!==void 0)throw Error(`gjsify ship: the layout is decided when the stage is assembled, so "${t.os}" has nothing to change here — the staged tree already IS one OS's layout. Use \`--expect-target <os>-<arch>\` to assert which one you are packing.`);let S=process.cwd(),C=In(S,n),N=readStageManifest(C);assertExpectedTarget(N,t[`expect-target`]);let F=layoutForOs(N.target.os);t.target===void 0&&assertPackable(N.formats.map(t=>OW[t]),F,`stage`,defaultFormatIds(F.os).map(t=>OW[t]).filter(t=>!t.interpreters.includes(N.settings.app)));let I=resolveFormats(t.target??N.formats,F);assertFormatsStaged(N,I);for(let t of I)assertCanPack(t);let H=resolveSignPlan({flag:t.sign,layoutOs:F.os}),W=resolveNotaryPlan({flag:t.notarize,layoutOs:F.os,sign:H});announceSigning(H,W),H.kind===`sign`&&assertHostCanSign(H.signer);for(let t of warnOnToolSkew(N))ge.warn(`${bG} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${bG} ${t}`);if(ge.log(`${bG} packing ${N.settings.binaryName} ${N.settings.version}-${N.settings.release} for ${formatTarget(N.target)} from ${Bn(S,C)||`.`}/`),t.verbose){for(let t of N.staged)ge.log(`${bG} ${t.path}`);ge.log(`${bG} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${bG} gi optional namespaces: ${N.optionalNamespaces?.join(`, `)}`)}let X=t.out===void 0?Hn(C):In(S,t.out),Z=[];for(let n of I){if(assertFormatCanRunInterpreter(n,N.settings.app),n.depends!==null){let t=N.settings.app===`node`?warnAboutNodeFloor(n.depends,N.settings.minNodeVersion):warnAboutGjsFloor(n.depends,N.settings.minGjsVersion);for(let n of t)ge.warn(`${bG} ${n}`)}Z.push(await packOne({format:n,settings:N.settings,arch:N.target.arch,staged:N.staged,overlay:overlayFiles(N,n.id),stageDir:C,outRoot:X,namespaces:N.namespaces,optionalNamespaces:N.optionalNamespaces??[],mtime:q,sign:H,notarize:W,verbose:t.verbose}))}printArtifacts(S,Z)}async function packOne(t){let{format:n,settings:S,stageDir:C,outRoot:N,mtime:F}=t;assertOverlayIsLicensed(n.id,S.binaryName,t.overlay);let I=zn(N,`overlay`,n.id);writeStage(I,t.overlay);let H=readStage([C,I],[...t.staged,...t.overlay]),W=readPayloadFacts(H),q=n.depends===null?{requires:[],recommends:[],unmappedOptional:[]}:deriveDepends(n.depends,{namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,hasIcons:W.hasIcons,hasSchemas:W.hasSchemas,interpreter:S.app,extra:S.extraDepends[n.depends],typelibPackages:S.typelibPackages,bundledTypelibs:W.bundledTypelibs,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion}),Y=q.requires,X=q.recommends;assertPayloadMatchesArch(H,t.arch,{exempt:payloadArchExemptions(n.layoutOs,S)});let Z=layoutForOs(n.layoutOs);assertLauncherMatchesInterpreter(H,Z,S,S.app),assertLayoutSupportsArch(Z,t.arch);let te=signedSubordinatesFor(Z,S,S),ne=t.sign.kind===`sign`?await signPayload({payload:H,identity:t.sign.identity,signer:t.sign.signer,workDir:zn(N,`signed`,n.id),bundleRoot:Z.root(S),entitlementsPath:zn(N,`signed`,`${n.id}.entitlements.plist`),nestedBundles:te.nestedBundles,helperExecutables:te.helperExecutables,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)}):H,re=n.archName(t.arch,isArchIndependent(ne)),ie={settings:S,payload:ne,prefix:n.prefix,depends:Y,recommends:X,archLabel:re,mtime:F},ae=zn(N,`out`);mkdirSync(ae,{recursive:!0});let oe=zn(ae,n.fileName(S,re));switch(n.id){case`deb`:writeFileSync(oe,await buildDeb(ie));break;case`rpm`:writeFileSync(oe,await buildRpm(ie));break;case`flatpak`:await buildFlatpakBundle({settings:S,stageDir:C,overlayDir:I,stageManifestFile:XW,workDir:zn(N,`flatpak`),target:oe,archLabel:re,verbose:t.verbose});break;case`appimage`:{let n=appImageHostRequirements({app:S.app,minGjsVersion:S.minGjsVersion,minNodeVersion:S.minNodeVersion,namespaces:t.namespaces,optionalNamespaces:t.optionalNamespaces,bundledTypelibs:W.bundledTypelibs}),C=appDirFor(N),I=appDirPayload(S,ne,n,await compileSchemasForPayload({payload:ne,workDir:zn(N,`appimage-schemas`)}));writePayload(C,I,``),stampAppDirTimes(C,I,F),ge.log(`${bG} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(re);ge.log(`${bG} ${appImageRuntimeNotice(re,H)}`),await buildAppImage({appDir:C,target:oe,archLabel:re,runtimeFile:H,workDir:Hn(C),verbose:t.verbose});break}case`linux-tar`:case`linux-tar-flatpak`:{let t=n.id===`linux-tar-flatpak`?await compileSchemasForPayload({payload:ne,workDir:zn(N,`tar-schemas`)}):void 0;writeFileSync(oe,await buildLinuxTarball({settings:S,payload:t===void 0?ne:[...ne,t],archLabel:re,mtime:F}));break}case`macos-app`:case`windows-dir`:writePayload(oe,ne,Z.root(S));break;case`macos-app-dmg`:{let n=dmgVolumeDir(N);if(writePayload(n,ne,``),t.notarize.kind===`notarize`){let C=t.notarize,N=zn(n,`${S.name}.app`),I=zn(Hn(n),`bundle-notarize.zip`);await stapleBundleBeforeImage({writeArchive:()=>writeFileSync(I,buildZip(zipEntriesFromPayload(ne),F)),notarize:()=>notarizeArtifact({plan:C,artifact:I,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)}),staple:()=>stapleArtifact({notary:C.notary,artifact:N,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)})})}addApplicationsLink(n),await buildDmgImage({volumeName:dmgVolumeName(S),sourceDir:n,target:oe,workDir:Hn(n),verbose:t.verbose}),t.sign.kind===`sign`&&await signDmgImage({identity:t.sign.identity,file:oe,adhoc:t.sign.identity===`-`,workDir:Hn(n),verbose:t.verbose});break}case`macos-app-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne),F));break;case`windows-dir-zip`:writeFileSync(oe,buildZip(zipEntriesFromPayload(ne,windowsProgramDirName(S)),F));break;case`msi`:{let n=zn(N,`msi`);writePayload(zn(n,PW),ne,Z.root(S)),await buildMsi({settings:S,files:ne.map(t=>({path:t.path,source:`${PW}/${t.path}`})),programDirName:windowsProgramDirName(S),archLabel:re,workDir:n,target:oe,verbose:t.verbose});break}default:{let t=n.id;throw Error(`gjsify ship: no packer is wired for format "${String(t)}".`)}}let Q=n.artifactKind===`directory`?directorySize(oe):statSync(oe).size,se=!1,ce=!1;if(t.notarize.kind===`notarize`&&(n.artifactKind===`directory`?ge.warn(`${bG} ${n.id} is a directory, and notarytool submits an archive or an installer — not notarised. The container format beside it is what carries the ticket.`):(await notarizeArtifact({plan:t.notarize,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)}),se=!0,canCarryTicket(n.id)?(await stapleArtifact({notary:t.notarize.notary,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${bG} ${t}`)}),ce=!0):ge.warn(`${bG} ${n.id} is notarised and NOT stapled: \`stapler\` takes a UDIF image, a signed flat package or a code-signed bundle, and an archive is none of them. Apple's remedy is to staple each item that went INTO the archive and re-create it — for this artifact that is the \`.app\`, which \`--target macos-app\` writes beside it.`))),n.artifactKind===`file`){let S=writeReleaseRecord({file:oe,format:n.id,os:n.layoutOs,arch:isArchIndependent(ne)?`noarch`:t.arch,signature:recordedSignature(t.sign.kind===`sign`?t.sign.identity:void 0,`-`),notarized:se,stapled:ce,nestedBundles:recordedNestedBundles(ne,te.nestedBundles),generator:`@gjsify/cli ${cliVersion()}`});t.verbose&&ge.log(`${bG} release record: ${S}`)}return{format:n.id,path:oe,size:Q}}function printArtifacts(t,n){for(let S of n)ge.log(`${bG} ${S.format}: ${Bn(t,S.path)} (${S.size} bytes)`)}function assertCanPack(t){assertHostCanFinish(t),assertToolsInstalled(t)}function assertPackable(t,n,S,C=[]){if(t.length>0)return;if(C.length>0)throw Error(`gjsify ship: ${C.map(t=>t.id).join(` and `)} wrap the ${n.name} layout, and neither can run this project — ${C[0]?.interpreterGap??``}.\n Set \`gjsify.ship.app.${n.os}\` to "${C[0]?.interpreters.join(`" / "`)}" — it overrides \`gjsify.app\` for THIS target and\n leaves every other one alone, which is what lets one project be GJS on Linux and Node here.
1192
1192
  \`gjsify ship ${n.name} --stage\` assembles the tree either way.`);let N=formatIdsFor(n.os).sort();if(N.length>0){let t=S===`stage`?`${n.name} --stage --target`:`${n.name} --target`;throw Error(`gjsify ship: this run records no formats for the ${n.name} layout, so there is nothing to pack — and it is not that none exist: ${N.join(`, `)} wrap it.\n An empty list means none were SELECTED. \`gjsify.ship.targets\` is filtered to the layout being assembled,
1193
1193
  so a configured list naming only another OS's formats leaves this one empty and says so at stage time.
1194
- Name one where the payload is assembled: \`gjsify ship ${t} ${N[0]}\`.`)}let F=defaultFormatIds(`linux`).join(`,`),I={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${n.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${F} from right here.`,positional:`\`gjsify ship ${n.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${n.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[S];throw Error(`gjsify ship: no format wraps the ${n.name} layout, so there is nothing to pack. ${I} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(t,n){if(!t.interpreters.includes(n))throw Error(`gjsify ship: this ${t.layoutOs} target runs \`${n}\`, and the ${t.id} runtime cannot run it — it provides ${t.interpreters.join(`, `)}.\n ${t.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${t.layoutOs}: "${t.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(t,n,S){if(typeof readPackageJson$2(zn(t,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ge.log(`${bG} running the project's build script`);let C=S===void 0&&n===void 0?void 0:{...process.env};C!==void 0&&(n!==void 0&&(C[Dh]=n),S!==void 0&&(C[Ah]=S));let N=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:t,stdio:`inherit`,env:C,notFound:()=>Error("gjsify ship: `gjsify` is not on PATH, so the project build cannot be run. Build the project yourself and pass --skip-build.")});if(N.code!==0)throw Error(`gjsify ship: the project's build script failed with ${describeExit(N)}.`)}var bG,xG,SG,CG=__esmMin(()=>{_e(),Oh(),jh(),rf(),Xn(),pR(),SB(),fV(),VI(),gB(),Sh(),mv(),vU(),dH(),YU(),XU(),QU(),$U(),FU(),cW(),pW(),uV(),mW(),bH(),hW(),jW(),nU(),LU(),mH(),sU(),FW(),IW(),WW(),KW(),cP(),_U(),HU(),JW(),tG(),nG(),yG(),AU(),ZW(),QW(),bG=`[gjsify ship]`,xG={command:`ship [os]`,description:`Build installable artifacts (${kW.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${eU.join(`|`)}, ADR 0024 § A2). Default: this host. Assembly is not host-bound, so any of them can be staged anywhere.`}).option(`target`,{type:`string`,array:!0,description:`Formats to build, comma-separated or repeated. Default: every format wrapping the target OS's layout that needs no extra tooling — on linux, ${defaultFormatIds(`linux`).join(`,`)}. Also available for linux, and opt-in because it needs tooling this CLI does not carry: ${formatIdsFor(`linux`).filter(t=>!defaultFormatIds(`linux`).includes(t)).join(`, `)}.`}).option(`out`,{type:`string`,normalize:!0,description:"Output root, relative to the project. Default: `gjsify.ship.outDir`, else `ship`."}).option(`stage`,{type:`boolean`,default:!1,description:`Produce the staged payload and stop, without packing anything.`}).option(`from-stage`,{type:`string`,normalize:!0,description:"Pack a staged payload written by an earlier `--stage` run. Needs no project: the stage carries its own closure."}).option(`expect-target`,{type:`string`,description:"With --from-stage: refuse unless the stage was assembled for this `<os>-<arch>`, e.g. `linux-arm64`."}).option(`channel`,{type:`string`,choices:[...Th],description:"Distribution channel (ADR 0113). Overrides gjsify.ship.channel; `--target flatpak` implies flathub. Passed to the project build, and gates the metainfo donation URL."}).option(`pricing`,{type:`string`,choices:[...kh],description:`Pricing tier (ADR 0139): 'free' or 'paid'. Overrides gjsify.ship.pricing; passed to the project build. Default 'free'.`}).option(`skip-build`,{type:`boolean`,default:!1,description:"Package what is already built instead of running the project's `build` script."}).option(`arch`,{type:`string`,description:"Target architecture in `process.arch` spelling. Default: this host."}).option(`sign`,{type:`string`,requiresArg:!0,description:"Sign the payload with this identity, e.g. a Developer ID name or SHA-1 fingerprint. `-` signs ad-hoc and needs no developer identity. Default: `gjsify.ship.sign.<darwin|win32>.identity`; absent means unsigned, which is a legitimate output."}).option(`notarize`,{type:`string`,requiresArg:!0,description:"Submit the signed artifact to Apple with this `notarytool` keychain profile. Needs --sign; darwin only."}).option(`verbose`,{type:`boolean`,default:!1,description:`Print each staged file, the GI namespaces the bundle imports, and every tool a host-bound packer invokes.`}),handler:async t=>{if(t[`from-stage`]!==void 0)return await finishFromStage(t,t[`from-stage`]);await assemble(t)}},SG=1440*7});function parseGithubRepo(t){let n=t.trim().replace(/^git\+/,``),S=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(n),C=/^(?:https?|ssh|git):\/\/(?:[^@/]+@)?github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(n)??S;return C===null?void 0:`${C[1]}/${C[2].replace(/\.git$/,``)}`}function releaseDateOf(t){return new Date(t*1e3).toISOString().slice(0,10)}function readFlatparkSources(t){let n=[];if(existsSync(t.dir))for(let S of readdirSync(t.dir).sort()){if(!S.endsWith(`.gjsify-release.json`))continue;let C=JSON.parse(readFileSync(zn(t.dir,S),`utf-8`));C.format===`linux-tar-flatpak`&&C.os===`linux`&&n.push(C)}if(n.length===0)throw Error(`gjsify flatpark: no release record for \`${TG}\` in ${t.dir}. The URL, sha256 and size come from \`<artifact>${qW}\`, which \`gjsify ship --target ${TG}\` writes beside the archive. Run that first, or point --release-dir at the directory that holds the record.`);let S=`${t.tagPrefix}${t.version}`,C=n.map(n=>{let C=EG[n.arch===`noarch`?t.stageArch??n.arch:n.arch];if(C===void 0)throw Error(`gjsify flatpark: ${n.artifact} is built for \`${n.arch}\`, which has no Flatpak arch (known: ${Object.keys(EG).join(`, `)}).`);return{arch:C,artifact:n.artifact,url:`https://github.com/${t.repo}/releases/download/${S}/${n.artifact}`,sha256:n.sha256,size:n.size}}),N=new Set;for(let n of C){if(N.has(n.arch))throw Error(`gjsify flatpark: two release records for ${n.arch} in ${t.dir}; keep one.`);N.add(n.arch)}return C.sort((t,n)=>t.arch.localeCompare(n.arch))}function renderApplyExtra(t){return`#!/bin/sh
1194
+ Name one where the payload is assembled: \`gjsify ship ${t} ${N[0]}\`.`)}let F=defaultFormatIds(`linux`).join(`,`),I={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${n.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${F} from right here.`,positional:`\`gjsify ship ${n.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${n.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[S];throw Error(`gjsify ship: no format wraps the ${n.name} layout, so there is nothing to pack. ${I} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(t,n){if(!t.interpreters.includes(n))throw Error(`gjsify ship: this ${t.layoutOs} target runs \`${n}\`, and the ${t.id} runtime cannot run it — it provides ${t.interpreters.join(`, `)}.\n ${t.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${t.layoutOs}: "${t.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(t,n,S){if(typeof readPackageJson$2(zn(t,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ge.log(`${bG} running the project's build script`);let C=S===void 0&&n===void 0?void 0:{...process.env};C!==void 0&&(n!==void 0&&(C[Dh]=n),S!==void 0&&(C[Ah]=S));let N=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:t,stdio:`inherit`,env:C,notFound:()=>Error("gjsify ship: `gjsify` is not on PATH, so the project build cannot be run. Build the project yourself and pass --skip-build.")});if(N.code!==0)throw Error(`gjsify ship: the project's build script failed with ${describeExit(N)}.`)}var bG,xG,SG,CG=__esmMin(()=>{_e(),Oh(),jh(),rf(),Xn(),pR(),SB(),fV(),VI(),gB(),Sh(),mv(),vU(),dH(),YU(),XU(),QU(),$U(),FU(),cW(),pW(),lV(),mW(),bH(),hW(),jW(),nU(),LU(),mH(),sU(),FW(),IW(),WW(),KW(),cP(),_U(),HU(),JW(),tG(),nG(),yG(),AU(),ZW(),QW(),bG=`[gjsify ship]`,xG={command:`ship [os]`,description:`Build installable artifacts (${kW.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${eU.join(`|`)}, ADR 0024 § A2). Default: this host. Assembly is not host-bound, so any of them can be staged anywhere.`}).option(`target`,{type:`string`,array:!0,description:`Formats to build, comma-separated or repeated. Default: every format wrapping the target OS's layout that needs no extra tooling — on linux, ${defaultFormatIds(`linux`).join(`,`)}. Also available for linux, and opt-in because it needs tooling this CLI does not carry: ${formatIdsFor(`linux`).filter(t=>!defaultFormatIds(`linux`).includes(t)).join(`, `)}.`}).option(`out`,{type:`string`,normalize:!0,description:"Output root, relative to the project. Default: `gjsify.ship.outDir`, else `ship`."}).option(`stage`,{type:`boolean`,default:!1,description:`Produce the staged payload and stop, without packing anything.`}).option(`from-stage`,{type:`string`,normalize:!0,description:"Pack a staged payload written by an earlier `--stage` run. Needs no project: the stage carries its own closure."}).option(`expect-target`,{type:`string`,description:"With --from-stage: refuse unless the stage was assembled for this `<os>-<arch>`, e.g. `linux-arm64`."}).option(`channel`,{type:`string`,choices:[...Th],description:"Distribution channel (ADR 0113). Overrides gjsify.ship.channel; `--target flatpak` implies flathub. Passed to the project build, and gates the metainfo donation URL."}).option(`pricing`,{type:`string`,choices:[...kh],description:`Pricing tier (ADR 0139): 'free' or 'paid'. Overrides gjsify.ship.pricing; passed to the project build. Default 'free'.`}).option(`skip-build`,{type:`boolean`,default:!1,description:"Package what is already built instead of running the project's `build` script."}).option(`arch`,{type:`string`,description:"Target architecture in `process.arch` spelling. Default: this host."}).option(`sign`,{type:`string`,requiresArg:!0,description:"Sign the payload with this identity, e.g. a Developer ID name or SHA-1 fingerprint. `-` signs ad-hoc and needs no developer identity. Default: `gjsify.ship.sign.<darwin|win32>.identity`; absent means unsigned, which is a legitimate output."}).option(`notarize`,{type:`string`,requiresArg:!0,description:"Submit the signed artifact to Apple with this `notarytool` keychain profile. Needs --sign; darwin only."}).option(`verbose`,{type:`boolean`,default:!1,description:`Print each staged file, the GI namespaces the bundle imports, and every tool a host-bound packer invokes.`}),handler:async t=>{if(t[`from-stage`]!==void 0)return await finishFromStage(t,t[`from-stage`]);await assemble(t)}},SG=1440*7});function parseGithubRepo(t){let n=t.trim().replace(/^git\+/,``),S=/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(n),C=/^(?:https?|ssh|git):\/\/(?:[^@/]+@)?github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(n)??S;return C===null?void 0:`${C[1]}/${C[2].replace(/\.git$/,``)}`}function releaseDateOf(t){return new Date(t*1e3).toISOString().slice(0,10)}function readFlatparkSources(t){let n=[];if(existsSync(t.dir))for(let S of readdirSync(t.dir).sort()){if(!S.endsWith(`.gjsify-release.json`))continue;let C=JSON.parse(readFileSync(zn(t.dir,S),`utf-8`));C.format===`linux-tar-flatpak`&&C.os===`linux`&&n.push(C)}if(n.length===0)throw Error(`gjsify flatpark: no release record for \`${TG}\` in ${t.dir}. The URL, sha256 and size come from \`<artifact>${qW}\`, which \`gjsify ship --target ${TG}\` writes beside the archive. Run that first, or point --release-dir at the directory that holds the record.`);let S=`${t.tagPrefix}${t.version}`,C=n.map(n=>{let C=EG[n.arch===`noarch`?t.stageArch??n.arch:n.arch];if(C===void 0)throw Error(`gjsify flatpark: ${n.artifact} is built for \`${n.arch}\`, which has no Flatpak arch (known: ${Object.keys(EG).join(`, `)}).`);return{arch:C,artifact:n.artifact,url:`https://github.com/${t.repo}/releases/download/${S}/${n.artifact}`,sha256:n.sha256,size:n.size}}),N=new Set;for(let n of C){if(N.has(n.arch))throw Error(`gjsify flatpark: two release records for ${n.arch} in ${t.dir}; keep one.`);N.add(n.arch)}return C.sort((t,n)=>t.arch.localeCompare(n.arch))}function renderApplyExtra(t){return`#!/bin/sh
1195
1195
  set -eu
1196
1196
 
1197
1197
  extra_root="\${EXTRA_ROOT:-/app/extra}"
@@ -1950,4 +1950,5 @@ await runBrowserDevtools({
1950
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
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
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);
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 resolveSubmitProject(t,n){let S=t.gjsify?.webext;if(S!==void 0&&!isRecord(S))throw Error("gjsify webext: `gjsify.webext` must be an object.");let C=S??{},N=[],F=C.targets??[...jY],I=[];if(!Array.isArray(F)||F.length===0)N.push("`targets` must be a non-empty array of target names.");else for(let t of F)try{I.push(parseWebextTarget(String(t)))}catch(t){N.push(t.message.replace(/^gjsify webext: /,``))}if(N.length>0)throw Error(`gjsify webext: \`gjsify.webext\` in ${zn(n,`package.json`)}:\n - ${N.join(`
1954
+ - `)}`);return{root:n,name:C.name??defaultArtifactName(t.name),version:t.version??`0.0.0`,targets:I,outDir:Rn(C.outDir??`.output`)?C.outDir:In(n,C.outDir??`.output`)}}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 loadSubmitProject(t){let n=zn(t,`package.json`);if(!existsSync(n))throw Error(`gjsify webext: no package.json in ${t}.`);return resolveSubmitProject(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:loadSubmitProject(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);