@gjsify/cli 0.64.57-next.363 → 0.64.58
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 +68 -68
- package/lib/types/config-data.d.ts +14 -0
- package/lib/utils/ship/settings.js +1 -0
- package/lib/utils/ship/snap.js +10 -0
- package/lib/utils/ship/stage-manifest.js +9 -0
- package/lib/utils/ship/types.d.ts +5 -0
- package/package.json +21 -22
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=>{!Bp.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=>{Bp.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 Bp,Vp=__esmMin(()=>{Dp(),Cp(),zp(),Mp(),Bp=[`$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,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,oh,YargsInstance,sh=__esmMin(()=>{_e(),jp(),Cp(),Vl(),Pp(),Dp(),Rp(),Vp(),Mp(),Wl(),Op(),wp(),kp(),Np(),__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)},wm=Symbol(`copyDoubleDash`),Tm=Symbol(`copyDoubleDash`),Em=Symbol(`deleteFromParserHintObject`),Dm=Symbol(`emitWarning`),Om=Symbol(`freeze`),km=Symbol(`getDollarZero`),Am=Symbol(`getParserConfiguration`),jm=Symbol(`getUsageConfiguration`),Mm=Symbol(`guessLocale`),Nm=Symbol(`guessVersion`),Pm=Symbol(`parsePositionalNumbers`),Fm=Symbol(`pkgUp`),Im=Symbol(`populateParserHintArray`),Lm=Symbol(`populateParserHintSingleValueDictionary`),Rm=Symbol(`populateParserHintArrayDictionary`),zm=Symbol(`populateParserHintDictionary`),Bm=Symbol(`sanitizeKey`),Vm=Symbol(`setKey`),Hm=Symbol(`unfreeze`),Um=Symbol(`validateAsync`),Wm=Symbol(`getCommandInstance`),Gm=Symbol(`getContext`),Km=Symbol(`getHasOutput`),qm=Symbol(`getLoggerInstance`),Jm=Symbol(`getParseContext`),Ym=Symbol(`getUsageInstance`),Xm=Symbol(`getValidationInstance`),Zm=Symbol(`hasParseCallback`),Qm=Symbol(`isGlobalContext`),$m=Symbol(`postProcess`),eh=Symbol(`rebase`),th=Symbol(`reset`),nh=Symbol(`runYargsParserAndExecuteCommands`),rh=Symbol(`runValidation`),ih=Symbol(`setHasOutput`),ah=Symbol(`kTrackManuallySetKeys`),oh=`en_US`,YargsInstance=class{constructor(t=[],n,S,C){this.customScriptName=!1,this.parsed=!1,Hp.set(this,void 0),Up.set(this,void 0),Wp.set(this,{commands:[],fullCommands:[]}),Gp.set(this,null),Kp.set(this,null),qp.set(this,`show-hidden`),Jp.set(this,null),Yp.set(this,!0),Xp.set(this,{}),Zp.set(this,!0),Qp.set(this,[]),$p.set(this,void 0),em.set(this,{}),tm.set(this,!1),nm.set(this,null),im.set(this,!0),am.set(this,void 0),om.set(this,``),sm.set(this,void 0),cm.set(this,void 0),lm.set(this,{}),um.set(this,null),dm.set(this,null),fm.set(this,{}),pm.set(this,{}),mm.set(this,void 0),hm.set(this,!1),gm.set(this,void 0),_m.set(this,!1),vm.set(this,!1),ym.set(this,!1),bm.set(this,void 0),xm.set(this,{}),Sm.set(this,null),Cm.set(this,void 0),__classPrivateFieldSet(this,gm,C,`f`),__classPrivateFieldSet(this,mm,t,`f`),__classPrivateFieldSet(this,Up,n,`f`),__classPrivateFieldSet(this,cm,S,`f`),__classPrivateFieldSet(this,$p,new GlobalMiddleware(this),`f`),this.$0=this[km](),this[th](),__classPrivateFieldSet(this,Hp,__classPrivateFieldGet(this,Hp,`f`),`f`),__classPrivateFieldSet(this,bm,__classPrivateFieldGet(this,bm,`f`),`f`),__classPrivateFieldSet(this,Cm,__classPrivateFieldGet(this,Cm,`f`),`f`),__classPrivateFieldSet(this,sm,__classPrivateFieldGet(this,sm,`f`),`f`),__classPrivateFieldGet(this,sm,`f`).showHiddenOpt=__classPrivateFieldGet(this,qp,`f`),__classPrivateFieldSet(this,am,this[Tm](),`f`),__classPrivateFieldGet(this,gm,`f`).y18n.setLocale(oh)}addHelpOpt(t,n){return argsert(`[string|boolean] [string]`,[t,n],arguments.length),__classPrivateFieldGet(this,nm,`f`)&&(this[Em](__classPrivateFieldGet(this,nm,`f`)),__classPrivateFieldSet(this,nm,null,`f`)),t===!1&&n===void 0?this:(__classPrivateFieldSet(this,nm,typeof t==`string`?t:`help`,`f`),this.boolean(__classPrivateFieldGet(this,nm,`f`)),this.describe(__classPrivateFieldGet(this,nm,`f`),n||__classPrivateFieldGet(this,bm,`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,qp,`f`);return this.boolean(S),this.describe(S,n||__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Show hidden options`)),__classPrivateFieldGet(this,sm,`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[Rm](this.alias.bind(this),`alias`,t,n),this}array(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`array`,t),this[ah](t),this}boolean(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`boolean`,t),this[ah](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,bm,`f`).fail(S.toString(),S):__classPrivateFieldGet(this,bm,`f`).fail(__classPrivateFieldGet(this,gm,`f`).y18n.__(`Argument check failed: %s`,t.toString())),n),t=>(__classPrivateFieldGet(this,bm,`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[Rm](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 Bl(`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 Bl(`coerce callback must be provided`);let S=t;return __classPrivateFieldGet(this,sm,`f`).key[S]=!0,__classPrivateFieldGet(this,$p,`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 Bl(t.message)})},S),this}conflicts(t,n){return argsert(`<string|object> [string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Cm,`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,Up,`f`),this[Am]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).configObjects=(__classPrivateFieldGet(this,sm,`f`).configObjects||[]).concat(t),this):(typeof n==`function`&&(S=n,n=void 0),this.describe(t,n||__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(t)?t:[t]).forEach(t=>{__classPrivateFieldGet(this,sm,`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,Kp,t||__classPrivateFieldGet(this,Kp,`f`)||`completion`,`f`),!n&&n!==!1&&(n=`generate completion script`),this.command(__classPrivateFieldGet(this,Kp,`f`),n),S&&__classPrivateFieldGet(this,Gp,`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,Hp,`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,cm,`f`)||__classPrivateFieldGet(this,gm,`f`).require;return __classPrivateFieldGet(this,Hp,`f`).addDirectory(t,S,__classPrivateFieldGet(this,gm,`f`).getCallerFile(),n),this}count(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`count`,t),this[ah](t),this}default(t,n,S){return argsert(`<object|string|array> [*] [string]`,[t,n,S],arguments.length),S&&(assertSingleKey(t,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]=S),typeof n==`function`&&(assertSingleKey(t,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]||(__classPrivateFieldGet(this,sm,`f`).defaultDescription[t]=__classPrivateFieldGet(this,bm,`f`).functionDescription(n)),n=n.call()),this[Lm](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,sm,`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,gm,`f`)),this.demandOption(t,S)}),n=1/0):typeof n!=`number`&&(S=n,n=1/0),typeof t==`number`?(assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,gm,`f`)),this.demandCommand(t,n,S,S)):Array.isArray(t)?t.forEach(t=>{assertNotStrictEqual(S,!0,__classPrivateFieldGet(this,gm,`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[Lm](this.demandOption.bind(this),`demandedOptions`,t,n),this}deprecateOption(t,n){return argsert(`<string> [string|boolean]`,[t,n],arguments.length),__classPrivateFieldGet(this,sm,`f`).deprecatedOptions[t]=n,this}describe(t,n){return argsert(`<object|string|array> [string]`,[t,n],arguments.length),this[Vm](t,!0),__classPrivateFieldGet(this,bm,`f`).describe(t,n),this}detectLocale(t){return argsert(`<boolean>`,[t],arguments.length),__classPrivateFieldSet(this,Yp,t,`f`),this}env(t){return argsert(`[string|boolean]`,[t],arguments.length),t===!1?delete __classPrivateFieldGet(this,sm,`f`).envPrefix:__classPrivateFieldGet(this,sm,`f`).envPrefix=t||``,this}epilogue(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,bm,`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,bm,`f`).example(t,n),this}exit(t,n){__classPrivateFieldSet(this,tm,!0,`f`),__classPrivateFieldSet(this,Jp,n,`f`),__classPrivateFieldGet(this,Zp,`f`)&&__classPrivateFieldGet(this,gm,`f`).process.exit(t)}exitProcess(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,Zp,t,`f`),this}fail(t){if(argsert(`<function|boolean>`,[t],arguments.length),typeof t==`boolean`&&t!==!1)throw new Bl(`Invalid first argument. Expected function or boolean 'false'`);return __classPrivateFieldGet(this,bm,`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,Gp,`f`).getCompletion(t,n):new Promise((n,S)=>{__classPrivateFieldGet(this,Gp,`f`).getCompletion(t,(t,C)=>{t?S(t):n(C)})})}getDemandedOptions(){return argsert([],0),__classPrivateFieldGet(this,sm,`f`).demandedOptions}getDemandedCommands(){return argsert([],0),__classPrivateFieldGet(this,sm,`f`).demandedCommands}getDeprecatedOptions(){return argsert([],0),__classPrivateFieldGet(this,sm,`f`).deprecatedOptions}getDetectLocale(){return __classPrivateFieldGet(this,Yp,`f`)}getExitProcess(){return __classPrivateFieldGet(this,Zp,`f`)}getGroups(){return Object.assign({},__classPrivateFieldGet(this,em,`f`),__classPrivateFieldGet(this,pm,`f`))}getHelp(){if(__classPrivateFieldSet(this,tm,!0,`f`),!__classPrivateFieldGet(this,bm,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[nh](__classPrivateFieldGet(this,mm,`f`),void 0,void 0,0,!0);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,bm,`f`).help())}let t=__classPrivateFieldGet(this,Hp,`f`).runDefaultBuilderOn(this);if(isPromise(t))return t.then(()=>__classPrivateFieldGet(this,bm,`f`).help())}return Promise.resolve(__classPrivateFieldGet(this,bm,`f`).help())}getOptions(){return __classPrivateFieldGet(this,sm,`f`)}getStrict(){return __classPrivateFieldGet(this,_m,`f`)}getStrictCommands(){return __classPrivateFieldGet(this,vm,`f`)}getStrictOptions(){return __classPrivateFieldGet(this,ym,`f`)}global(t,n){return argsert(`<string|array> [boolean]`,[t,n],arguments.length),t=[].concat(t),n===!1?t.forEach(t=>{__classPrivateFieldGet(this,sm,`f`).local.includes(t)||__classPrivateFieldGet(this,sm,`f`).local.push(t)}):__classPrivateFieldGet(this,sm,`f`).local=__classPrivateFieldGet(this,sm,`f`).local.filter(n=>t.indexOf(n)===-1),this}group(t,n){argsert(`<string|array> <string>`,[t,n],arguments.length);let S=__classPrivateFieldGet(this,pm,`f`)[n]||__classPrivateFieldGet(this,em,`f`)[n];__classPrivateFieldGet(this,pm,`f`)[n]&&delete __classPrivateFieldGet(this,pm,`f`)[n];let C={};return __classPrivateFieldGet(this,em,`f`)[n]=(S||[]).concat(t).filter(t=>C[t]?!1:C[t]=!0),this}hide(t){return argsert(`<string>`,[t],arguments.length),__classPrivateFieldGet(this,sm,`f`).hiddenOptions.push(t),this}implies(t,n){return argsert(`<string|object> [number|string|array]`,[t,n],arguments.length),__classPrivateFieldGet(this,Cm,`f`).implies(t,n),this}locale(t){return argsert(`[string]`,[t],arguments.length),t===void 0?(this[Mm](),__classPrivateFieldGet(this,gm,`f`).y18n.getLocale()):(__classPrivateFieldSet(this,Yp,!1,`f`),__classPrivateFieldGet(this,gm,`f`).y18n.setLocale(t),this)}middleware(t,n,S){return __classPrivateFieldGet(this,$p,`f`).addMiddleware(t,!!n,S)}nargs(t,n){return argsert(`<string|object|array> [number]`,[t,n],arguments.length),this[Lm](this.nargs.bind(this),`narg`,t,n),this}normalize(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`normalize`,t),this}number(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`number`,t),this[ah](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[ah](t),__classPrivateFieldGet(this,Sm,`f`)&&(t===`version`||n?.alias===`version`)&&this[Dm]([`"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,sm,`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,sm,`f`).defaultDescription[t]=n.defaultDescription),n.skipValidation&&this.skipValidation(t);let N=n.describe||n.description||n.desc,F=__classPrivateFieldGet(this,bm,`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[Om](),t===void 0&&(t=__classPrivateFieldGet(this,mm,`f`)),typeof n==`object`&&(__classPrivateFieldSet(this,dm,n,`f`),n=S),typeof n==`function`&&(__classPrivateFieldSet(this,um,n,`f`),n=!1),n||__classPrivateFieldSet(this,mm,t,`f`),__classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldSet(this,Zp,!1,`f`);let C=this[nh](t,!!n),N=this.parsed;return __classPrivateFieldGet(this,Gp,`f`).setParsed(this.parsed),isPromise(C)?C.then(t=>(__classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldGet(this,um,`f`).call(this,__classPrivateFieldGet(this,Jp,`f`),t,__classPrivateFieldGet(this,om,`f`)),t)).catch(t=>{throw __classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldGet(this,um,`f`)(t,this.parsed.argv,__classPrivateFieldGet(this,om,`f`)),t}).finally(()=>{this[Hm](),this.parsed=N}):(__classPrivateFieldGet(this,um,`f`)&&__classPrivateFieldGet(this,um,`f`).call(this,__classPrivateFieldGet(this,Jp,`f`),C,__classPrivateFieldGet(this,om,`f`)),this[Hm](),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 Bl(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return C}parserConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,lm,t,`f`),this}pkgConf(t,n){argsert(`<string> [string]`,[t,n],arguments.length);let S=null,C=this[Fm](n||__classPrivateFieldGet(this,Up,`f`));return C[t]&&typeof C[t]==`object`&&(S=applyExtends(C[t],n||__classPrivateFieldGet(this,Up,`f`),this[Am]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,gm,`f`)),__classPrivateFieldGet(this,sm,`f`).configObjects=(__classPrivateFieldGet(this,sm,`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,Wp,`f`).fullCommands[__classPrivateFieldGet(this,Wp,`f`).fullCommands.length-1],N=C?__classPrivateFieldGet(this,Hp,`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,bm,`f`).getPositionalGroupName()),this.option(t,n)}recommendCommands(t=!0){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,hm,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,sm,`f`).narg[t]||this[Lm](this.requiresArg.bind(this),`narg`,t,NaN),this}showCompletionScript(t,n){return argsert(`[string] [string]`,[t,n],arguments.length),t||=this.$0,__classPrivateFieldGet(this,am,`f`).log(__classPrivateFieldGet(this,Gp,`f`).generateCompletionScript(t,n||__classPrivateFieldGet(this,Kp,`f`)||`completion`)),this}showHelp(t){if(argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldSet(this,tm,!0,`f`),!__classPrivateFieldGet(this,bm,`f`).hasCachedHelpMessage()){if(!this.parsed){let n=this[nh](__classPrivateFieldGet(this,mm,`f`),void 0,void 0,0,!0);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,bm,`f`).showHelp(t)}),this}let n=__classPrivateFieldGet(this,Hp,`f`).runDefaultBuilderOn(this);if(isPromise(n))return n.then(()=>{__classPrivateFieldGet(this,bm,`f`).showHelp(t)}),this}return __classPrivateFieldGet(this,bm,`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,bm,`f`).showHelpOnFail(t,n),this}showVersion(t){return argsert(`[string|function]`,[t],arguments.length),__classPrivateFieldGet(this,bm,`f`).showVersion(t),this}skipValidation(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`skipValidation`,t),this}strict(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,_m,t!==!1,`f`),this}strictCommands(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,vm,t!==!1,`f`),this}strictOptions(t){return argsert(`[boolean]`,[t],arguments.length),__classPrivateFieldSet(this,ym,t!==!1,`f`),this}string(t){return argsert(`<array|string>`,[t],arguments.length),this[Im](`string`,t),this[ah](t),this}terminalWidth(){return argsert([],0),__classPrivateFieldGet(this,gm,`f`).process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,Yp,!1,`f`),__classPrivateFieldGet(this,gm,`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,gm,`f`)),(t||``).match(/^\$0( |$)/))return this.command(t,n,S,C);throw new Bl(`.usage() description must start with $0 if being used as alias for .command()`)}else return __classPrivateFieldGet(this,bm,`f`).usage(t),this}usageConfiguration(t){return argsert(`<object>`,[t],arguments.length),__classPrivateFieldSet(this,xm,t,`f`),this}version(t,n,S){let C=`version`;if(argsert(`[boolean|string] [string] [string]`,[t,n,S],arguments.length),__classPrivateFieldGet(this,Sm,`f`)&&(this[Em](__classPrivateFieldGet(this,Sm,`f`)),__classPrivateFieldGet(this,bm,`f`).version(void 0),__classPrivateFieldSet(this,Sm,null,`f`)),arguments.length===0)S=this[Nm](),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,Sm,typeof t==`string`?t:C,`f`),n||=__classPrivateFieldGet(this,bm,`f`).deferY18nLookup(`Show version number`),__classPrivateFieldGet(this,bm,`f`).version(S||void 0),this.boolean(__classPrivateFieldGet(this,Sm,`f`)),this.describe(__classPrivateFieldGet(this,Sm,`f`),n),this}wrap(t){return argsert(`<number|null|undefined>`,[t],arguments.length),__classPrivateFieldGet(this,bm,`f`).wrap(t),this}[(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=new WeakMap,wm)](t){if(!t._||!t[`--`])return t;t._.push.apply(t._,t[`--`]);try{delete t[`--`]}catch{}return t}[Tm](){return{log:(...t)=>{this[Zm]()||ge.log(...t),__classPrivateFieldSet(this,tm,!0,`f`),__classPrivateFieldGet(this,om,`f`).length&&__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+`
|
|
148
148
|
`,`f`),__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+t.join(` `),`f`)},error:(...t)=>{this[Zm]()||ge.error(...t),__classPrivateFieldSet(this,tm,!0,`f`),__classPrivateFieldGet(this,om,`f`).length&&__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+`
|
|
149
|
-
`,`f`),__classPrivateFieldSet(this,om,__classPrivateFieldGet(this,om,`f`)+t.join(` `),`f`)}}}[Em](t){objectKeys(__classPrivateFieldGet(this,sm,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,sm,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,bm,`f`).getDescriptions()[t]}[Dm](t,n,S){__classPrivateFieldGet(this,Xp,`f`)[S]||(__classPrivateFieldGet(this,gm,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Xp,`f`)[S]=!0)}[Om](){__classPrivateFieldGet(this,Qp,`f`).push({options:__classPrivateFieldGet(this,sm,`f`),configObjects:__classPrivateFieldGet(this,sm,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Zp,`f`),groups:__classPrivateFieldGet(this,em,`f`),strict:__classPrivateFieldGet(this,_m,`f`),strictCommands:__classPrivateFieldGet(this,vm,`f`),strictOptions:__classPrivateFieldGet(this,ym,`f`),completionCommand:__classPrivateFieldGet(this,Kp,`f`),output:__classPrivateFieldGet(this,om,`f`),exitError:__classPrivateFieldGet(this,Jp,`f`),hasOutput:__classPrivateFieldGet(this,tm,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,um,`f`),parseContext:__classPrivateFieldGet(this,dm,`f`)}),__classPrivateFieldGet(this,bm,`f`).freeze(),__classPrivateFieldGet(this,Cm,`f`).freeze(),__classPrivateFieldGet(this,Hp,`f`).freeze(),__classPrivateFieldGet(this,$p,`f`).freeze()}[km](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,gm,`f`).process.argv()[0])?__classPrivateFieldGet(this,gm,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,gm,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[eh](__classPrivateFieldGet(this,Up,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,gm,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,gm,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,gm,`f`).path.dirname(__classPrivateFieldGet(this,gm,`f`).process.execPath())}/`,``)),t}[Am](){return __classPrivateFieldGet(this,lm,`f`)}[jm](){return __classPrivateFieldGet(this,xm,`f`)}[Mm](){if(!__classPrivateFieldGet(this,Yp,`f`))return;let t=__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[Nm](){return this[Fm]().version||`unknown`}[Pm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,gm,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[Fm](t){let n=t||`*`;if(__classPrivateFieldGet(this,fm,`f`)[n])return __classPrivateFieldGet(this,fm,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,gm,`f`).mainFilename;__classPrivateFieldGet(this,gm,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,gm,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,gm,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,gm,`f`)),S=JSON.parse(__classPrivateFieldGet(this,gm,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,fm,`f`)[n]=S||{},__classPrivateFieldGet(this,fm,`f`)[n]}[Im](t,n){n=[].concat(n),n.forEach(n=>{n=this[Bm](n),__classPrivateFieldGet(this,sm,`f`)[t].push(n)})}[Lm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=S})}[Rm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=(__classPrivateFieldGet(this,sm,`f`)[t][n]||[]).concat(S)})}[zm](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[Bm](S),C)}[Bm](t){return t===`__proto__`?`___proto___`:t}[Vm](t,n){return this[Lm](this[Vm].bind(this),`key`,t,n),this}[Hm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Qp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,gm,`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,sm,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Zp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,em,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,om,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Jp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,tm,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,_m,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,vm,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,ym,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Kp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,um,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,dm,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,sm,`f`).configObjects=te,__classPrivateFieldGet(this,bm,`f`).unfreeze(),__classPrivateFieldGet(this,Cm,`f`).unfreeze(),__classPrivateFieldGet(this,Hp,`f`).unfreeze(),__classPrivateFieldGet(this,$p,`f`).unfreeze()}[Um](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[Wm].bind(this),getContext:this[Gm].bind(this),getHasOutput:this[Km].bind(this),getLoggerInstance:this[qm].bind(this),getParseContext:this[Jm].bind(this),getParserConfiguration:this[Am].bind(this),getUsageConfiguration:this[jm].bind(this),getUsageInstance:this[Ym].bind(this),getValidationInstance:this[Xm].bind(this),hasParseCallback:this[Zm].bind(this),isGlobalContext:this[Qm].bind(this),postProcess:this[$m].bind(this),reset:this[th].bind(this),runValidation:this[rh].bind(this),runYargsParserAndExecuteCommands:this[nh].bind(this),setHasOutput:this[ih].bind(this)}}[Wm](){return __classPrivateFieldGet(this,Hp,`f`)}[Gm](){return __classPrivateFieldGet(this,Wp,`f`)}[Km](){return __classPrivateFieldGet(this,tm,`f`)}[qm](){return __classPrivateFieldGet(this,am,`f`)}[Jm](){return __classPrivateFieldGet(this,dm,`f`)||{}}[Ym](){return __classPrivateFieldGet(this,bm,`f`)}[Xm](){return __classPrivateFieldGet(this,Cm,`f`)}[Zm](){return!!__classPrivateFieldGet(this,um,`f`)}[Qm](){return __classPrivateFieldGet(this,im,`f`)}[$m](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[wm](t)),(this[Am]()[`parse-positional-numbers`]||this[Am]()[`parse-positional-numbers`]===void 0)&&(t=this[Pm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)),t)}[th](t={}){__classPrivateFieldSet(this,sm,__classPrivateFieldGet(this,sm,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,sm,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,sm,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,pm,`f`),Object.keys(__classPrivateFieldGet(this,em,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,em,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,em,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,sm,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,sm,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,sm,`f`).envPrefix,__classPrivateFieldSet(this,sm,n,`f`),__classPrivateFieldSet(this,bm,__classPrivateFieldGet(this,bm,`f`)?__classPrivateFieldGet(this,bm,`f`).reset(S):usage(this,__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Cm,__classPrivateFieldGet(this,Cm,`f`)?__classPrivateFieldGet(this,Cm,`f`).reset(S):validation(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Hp,__classPrivateFieldGet(this,Hp,`f`)?__classPrivateFieldGet(this,Hp,`f`).reset():command(__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Cm,`f`),__classPrivateFieldGet(this,$p,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,Gp,`f`)||__classPrivateFieldSet(this,Gp,completion(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Hp,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,$p,`f`).reset(),__classPrivateFieldSet(this,Kp,null,`f`),__classPrivateFieldSet(this,om,``,`f`),__classPrivateFieldSet(this,Jp,null,`f`),__classPrivateFieldSet(this,tm,!1,`f`),this.parsed=!1,this}[eh](t,n){return __classPrivateFieldGet(this,gm,`f`).path.relative(t,n)}[nh](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,mm,`f`),__classPrivateFieldGet(this,sm,`f`).__=__classPrivateFieldGet(this,gm,`f`).y18n.__,__classPrivateFieldGet(this,sm,`f`).configuration=this[Am]();let I=!!__classPrivateFieldGet(this,sm,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,sm,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,gm,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,sm,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,dm,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,nm,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Sm,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,bm,`f`).clearCachedHelpMessage();try{if(this[Mm](),n)return this[$m](q,I,!!S,!1);__classPrivateFieldGet(this,nm,`f`)&&[__classPrivateFieldGet(this,nm,`f`)].concat(X[__classPrivateFieldGet(this,nm,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,im,!1,`f`);let H=__classPrivateFieldGet(this,Hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Gp,`f`)?.completionKey?[__classPrivateFieldGet(this,Gp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Gp,`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,Kp,`f`)){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[$m](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Kp,`f`)){t=F;break}!__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,hm,`f`)&&t&&!re&&__classPrivateFieldGet(this,Cm,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Kp,`f`)&&q._.includes(__classPrivateFieldGet(this,Kp,`f`))&&!ne&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[$m](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Gp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Gp,`f`).getCompletion(n,(t,n)=>{if(t)throw new Bl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,am,`f`).log(t)}),this.exit(0)}),this[$m](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,tm,`f`)||(Z?(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,am,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,bm,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,sm,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,sm,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new Bl(W.error.message);if(!ne){let t=this[rh](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!0)),Y=this[Um](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof Bl)__classPrivateFieldGet(this,bm,`f`).fail(t.message,t);else throw t}return this[$m](Y??q,I,!!S,!0)}[rh](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new Bl(S.message);__classPrivateFieldGet(this,Cm,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Cm,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,vm,`f`)&&(I=__classPrivateFieldGet(this,Cm,`f`).unknownCommands(F)),__classPrivateFieldGet(this,_m,`f`)&&!I?__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,ym,`f`)&&__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Cm,`f`).limitedChoices(F),__classPrivateFieldGet(this,Cm,`f`).implications(F),__classPrivateFieldGet(this,Cm,`f`).conflicting(F)}}[ih](){__classPrivateFieldSet(this,tm,!0,`f`)}[ah](t){if(typeof t==`string`)__classPrivateFieldGet(this,sm,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,sm,`f`).key[n]=!0}}}),ch,lh=__esmMin(()=>{Sp(),sh(),ch=YargsFactory(xp)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var uh=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.64.57-next.363`,"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 dh=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,fh=__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):ph}function parseNpmrc(t){let n={registry:ph,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 ph,mh=__esmMin(()=>{ph=`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 hh=__esmMin(()=>{fh(),__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 gh=__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 vh=__esmMin(()=>{dh(),fh(),mh(),hh()});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 yh=__esmMin(()=>{dh(),fh(),hh(),gh()});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 bh=__esmMin(()=>{dh(),mh()}),xh=__esmMin(()=>{dh(),fh(),mh(),gh(),vh(),yh(),bh()});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 Sh===void 0&&(Sh=`0.64.57-next.363`),Sh}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 Sh,Ch=__esmMin(()=>{af(),Xn(),cr(),xh()}),wh,Th=__esmMin(()=>{wh=`gjsify`});function parseDeclaredChannel(t,n){if(!(t===void 0||t===``)){if(Eh.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a distribution channel. Known: ${Eh.join(`, `)}.`)}}function channelAllowsDonations(t){return t!==void 0&&Dh[t]===`external-link`}var Eh,Dh,Oh,kh=__esmMin(()=>{Eh=[`flathub`,`web`,`microsoft-store`,`apple-app-store`],Dh={flathub:`external-link`,web:`external-link`,"microsoft-store":`none`,"apple-app-store":`store-purchase`},Oh=`GJSIFY_CHANNEL`});function parseDeclaredPricing(t,n){if(!(t===void 0||t===``)){if(Ah.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a pricing tier. Known: ${Ah.join(`, `)}.`)}}var Ah,jh,Mh=__esmMin(()=>{Ah=[`free`,`paid`],jh=`GJSIFY_PRICING`}),Nh=__commonJSMin(((t,n)=>{let S=(Xn(),__toCommonJS(Pn)),C=(eu(),__toCommonJS(Xl)),N=(af(),__toCommonJS(nf)),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)})),Ph=__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})),Fh=__commonJSMin(((t,n)=>{let S=Ph();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}}}})),Ih=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(iu(),__toCommonJS(tu)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(Xn(),__toCommonJS(Pn)),H=Nh(),W=Fh();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)}})),Lh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),Rh=__commonJSMin(((t,n)=>{var S=(Uu(),__toCommonJS(zu)),C=Lh(),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,om,__classPrivateFieldGet(this,om,`f`)+t.join(` `),`f`)}}}[Em](t){objectKeys(__classPrivateFieldGet(this,sm,`f`)).forEach(n=>{if((t=>t===`configObjects`)(n))return;let S=__classPrivateFieldGet(this,sm,`f`)[n];Array.isArray(S)?S.includes(t)&&S.splice(S.indexOf(t),1):typeof S==`object`&&delete S[t]}),delete __classPrivateFieldGet(this,bm,`f`).getDescriptions()[t]}[Dm](t,n,S){__classPrivateFieldGet(this,Xp,`f`)[S]||(__classPrivateFieldGet(this,gm,`f`).process.emitWarning(t,n),__classPrivateFieldGet(this,Xp,`f`)[S]=!0)}[Om](){__classPrivateFieldGet(this,Qp,`f`).push({options:__classPrivateFieldGet(this,sm,`f`),configObjects:__classPrivateFieldGet(this,sm,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,Zp,`f`),groups:__classPrivateFieldGet(this,em,`f`),strict:__classPrivateFieldGet(this,_m,`f`),strictCommands:__classPrivateFieldGet(this,vm,`f`),strictOptions:__classPrivateFieldGet(this,ym,`f`),completionCommand:__classPrivateFieldGet(this,Kp,`f`),output:__classPrivateFieldGet(this,om,`f`),exitError:__classPrivateFieldGet(this,Jp,`f`),hasOutput:__classPrivateFieldGet(this,tm,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,um,`f`),parseContext:__classPrivateFieldGet(this,dm,`f`)}),__classPrivateFieldGet(this,bm,`f`).freeze(),__classPrivateFieldGet(this,Cm,`f`).freeze(),__classPrivateFieldGet(this,Hp,`f`).freeze(),__classPrivateFieldGet(this,$p,`f`).freeze()}[km](){let t=``,n;return n=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,gm,`f`).process.argv()[0])?__classPrivateFieldGet(this,gm,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,gm,`f`).process.argv().slice(0,1),t=n.map(t=>{let n=this[eh](__classPrivateFieldGet(this,Up,`f`),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&n.length<t.length?n:t}).join(` `).trim(),__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,gm,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,gm,`f`).getEnv(`_`)&&(t=__classPrivateFieldGet(this,gm,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,gm,`f`).path.dirname(__classPrivateFieldGet(this,gm,`f`).process.execPath())}/`,``)),t}[Am](){return __classPrivateFieldGet(this,lm,`f`)}[jm](){return __classPrivateFieldGet(this,xm,`f`)}[Mm](){if(!__classPrivateFieldGet(this,Yp,`f`))return;let t=__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,gm,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(t.replace(/[.:].*/,``))}[Nm](){return this[Fm]().version||`unknown`}[Pm](t){let n=t[`--`]?t[`--`]:t._;for(let t=0,S;(S=n[t])!==void 0;t++)__classPrivateFieldGet(this,gm,`f`).Parser.looksLikeNumber(S)&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))&&(n[t]=Number(S));return t}[Fm](t){let n=t||`*`;if(__classPrivateFieldGet(this,fm,`f`)[n])return __classPrivateFieldGet(this,fm,`f`)[n];let S={};try{let n=t||__classPrivateFieldGet(this,gm,`f`).mainFilename;__classPrivateFieldGet(this,gm,`f`).path.extname(n)&&(n=__classPrivateFieldGet(this,gm,`f`).path.dirname(n));let C=__classPrivateFieldGet(this,gm,`f`).findUp(n,(t,n)=>{if(n.includes(`package.json`))return`package.json`});assertNotStrictEqual(C,void 0,__classPrivateFieldGet(this,gm,`f`)),S=JSON.parse(__classPrivateFieldGet(this,gm,`f`).readFileSync(C,`utf8`))}catch{}return __classPrivateFieldGet(this,fm,`f`)[n]=S||{},__classPrivateFieldGet(this,fm,`f`)[n]}[Im](t,n){n=[].concat(n),n.forEach(n=>{n=this[Bm](n),__classPrivateFieldGet(this,sm,`f`)[t].push(n)})}[Lm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=S})}[Rm](t,n,S,C){this[zm](t,n,S,C,(t,n,S)=>{__classPrivateFieldGet(this,sm,`f`)[t][n]=(__classPrivateFieldGet(this,sm,`f`)[t][n]||[]).concat(S)})}[zm](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[Bm](S),C)}[Bm](t){return t===`__proto__`?`___proto___`:t}[Vm](t,n){return this[Lm](this[Vm].bind(this),`key`,t,n),this}[Hm](){var t,n,S,C,N,F,I,H,W,q,Y,X;let Z=__classPrivateFieldGet(this,Qp,`f`).pop();assertNotStrictEqual(Z,void 0,__classPrivateFieldGet(this,gm,`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,sm,n,`f`)}}.value,configObjects:te,exitProcess:{set value(t){__classPrivateFieldSet(n,Zp,t,`f`)}}.value,groups:{set value(t){__classPrivateFieldSet(S,em,t,`f`)}}.value,output:{set value(t){__classPrivateFieldSet(C,om,t,`f`)}}.value,exitError:{set value(t){__classPrivateFieldSet(N,Jp,t,`f`)}}.value,hasOutput:{set value(t){__classPrivateFieldSet(F,tm,t,`f`)}}.value,parsed:this.parsed,strict:{set value(t){__classPrivateFieldSet(I,_m,t,`f`)}}.value,strictCommands:{set value(t){__classPrivateFieldSet(H,vm,t,`f`)}}.value,strictOptions:{set value(t){__classPrivateFieldSet(W,ym,t,`f`)}}.value,completionCommand:{set value(t){__classPrivateFieldSet(q,Kp,t,`f`)}}.value,parseFn:{set value(t){__classPrivateFieldSet(Y,um,t,`f`)}}.value,parseContext:{set value(t){__classPrivateFieldSet(X,dm,t,`f`)}}.value}=Z,__classPrivateFieldGet(this,sm,`f`).configObjects=te,__classPrivateFieldGet(this,bm,`f`).unfreeze(),__classPrivateFieldGet(this,Cm,`f`).unfreeze(),__classPrivateFieldGet(this,Hp,`f`).unfreeze(),__classPrivateFieldGet(this,$p,`f`).unfreeze()}[Um](t,n){return maybeAsyncResult(n,n=>(t(n),n))}getInternalMethods(){return{getCommandInstance:this[Wm].bind(this),getContext:this[Gm].bind(this),getHasOutput:this[Km].bind(this),getLoggerInstance:this[qm].bind(this),getParseContext:this[Jm].bind(this),getParserConfiguration:this[Am].bind(this),getUsageConfiguration:this[jm].bind(this),getUsageInstance:this[Ym].bind(this),getValidationInstance:this[Xm].bind(this),hasParseCallback:this[Zm].bind(this),isGlobalContext:this[Qm].bind(this),postProcess:this[$m].bind(this),reset:this[th].bind(this),runValidation:this[rh].bind(this),runYargsParserAndExecuteCommands:this[nh].bind(this),setHasOutput:this[ih].bind(this)}}[Wm](){return __classPrivateFieldGet(this,Hp,`f`)}[Gm](){return __classPrivateFieldGet(this,Wp,`f`)}[Km](){return __classPrivateFieldGet(this,tm,`f`)}[qm](){return __classPrivateFieldGet(this,am,`f`)}[Jm](){return __classPrivateFieldGet(this,dm,`f`)||{}}[Ym](){return __classPrivateFieldGet(this,bm,`f`)}[Xm](){return __classPrivateFieldGet(this,Cm,`f`)}[Zm](){return!!__classPrivateFieldGet(this,um,`f`)}[Qm](){return __classPrivateFieldGet(this,im,`f`)}[$m](t,n,S,C){return S||isPromise(t)?t:(n||(t=this[wm](t)),(this[Am]()[`parse-positional-numbers`]||this[Am]()[`parse-positional-numbers`]===void 0)&&(t=this[Pm](t)),C&&(t=applyMiddleware(t,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)),t)}[th](t={}){__classPrivateFieldSet(this,sm,__classPrivateFieldGet(this,sm,`f`)||{},`f`);let n={};n.local=__classPrivateFieldGet(this,sm,`f`).local||[],n.configObjects=__classPrivateFieldGet(this,sm,`f`).configObjects||[];let S={};return n.local.forEach(n=>{S[n]=!0,(t[n]||[]).forEach(t=>{S[t]=!0})}),Object.assign(__classPrivateFieldGet(this,pm,`f`),Object.keys(__classPrivateFieldGet(this,em,`f`)).reduce((t,n)=>{let C=__classPrivateFieldGet(this,em,`f`)[n].filter(t=>!(t in S));return C.length>0&&(t[n]=C),t},{})),__classPrivateFieldSet(this,em,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(t=>{n[t]=(__classPrivateFieldGet(this,sm,`f`)[t]||[]).filter(t=>!S[t])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(t=>{n[t]=objFilter(__classPrivateFieldGet(this,sm,`f`)[t],t=>!S[t])}),n.envPrefix=__classPrivateFieldGet(this,sm,`f`).envPrefix,__classPrivateFieldSet(this,sm,n,`f`),__classPrivateFieldSet(this,bm,__classPrivateFieldGet(this,bm,`f`)?__classPrivateFieldGet(this,bm,`f`).reset(S):usage(this,__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Cm,__classPrivateFieldGet(this,Cm,`f`)?__classPrivateFieldGet(this,Cm,`f`).reset(S):validation(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldSet(this,Hp,__classPrivateFieldGet(this,Hp,`f`)?__classPrivateFieldGet(this,Hp,`f`).reset():command(__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Cm,`f`),__classPrivateFieldGet(this,$p,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,Gp,`f`)||__classPrivateFieldSet(this,Gp,completion(this,__classPrivateFieldGet(this,bm,`f`),__classPrivateFieldGet(this,Hp,`f`),__classPrivateFieldGet(this,gm,`f`)),`f`),__classPrivateFieldGet(this,$p,`f`).reset(),__classPrivateFieldSet(this,Kp,null,`f`),__classPrivateFieldSet(this,om,``,`f`),__classPrivateFieldSet(this,Jp,null,`f`),__classPrivateFieldSet(this,tm,!1,`f`),this.parsed=!1,this}[eh](t,n){return __classPrivateFieldGet(this,gm,`f`).path.relative(t,n)}[nh](t,n,S,C=0,N=!1){let F=!!S||N;t||=__classPrivateFieldGet(this,mm,`f`),__classPrivateFieldGet(this,sm,`f`).__=__classPrivateFieldGet(this,gm,`f`).y18n.__,__classPrivateFieldGet(this,sm,`f`).configuration=this[Am]();let I=!!__classPrivateFieldGet(this,sm,`f`).configuration[`populate--`],H=Object.assign({},__classPrivateFieldGet(this,sm,`f`).configuration,{"populate--":!0}),W=__classPrivateFieldGet(this,gm,`f`).Parser.detailed(t,Object.assign({},__classPrivateFieldGet(this,sm,`f`),{configuration:{"parse-positional-numbers":!1,...H}})),q=Object.assign(W.argv,__classPrivateFieldGet(this,dm,`f`)),Y,X=W.aliases,Z=!1,te=!1;Object.keys(q).forEach(t=>{t===__classPrivateFieldGet(this,nm,`f`)&&q[t]?Z=!0:t===__classPrivateFieldGet(this,Sm,`f`)&&q[t]&&(te=!0)}),q.$0=this.$0,this.parsed=W,C===0&&__classPrivateFieldGet(this,bm,`f`).clearCachedHelpMessage();try{if(this[Mm](),n)return this[$m](q,I,!!S,!1);__classPrivateFieldGet(this,nm,`f`)&&[__classPrivateFieldGet(this,nm,`f`)].concat(X[__classPrivateFieldGet(this,nm,`f`)]||[]).filter(t=>t.length>1).includes(``+q._[q._.length-1])&&(q._.pop(),Z=!0),__classPrivateFieldSet(this,im,!1,`f`);let H=__classPrivateFieldGet(this,Hp,`f`).getCommands(),ne=__classPrivateFieldGet(this,Gp,`f`)?.completionKey?[__classPrivateFieldGet(this,Gp,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Gp,`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,Kp,`f`)){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(F,this,W,n+1,N,Z||te||N);return this[$m](t,I,!!S,!1)}else if(!t&&F!==__classPrivateFieldGet(this,Kp,`f`)){t=F;break}!__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,hm,`f`)&&t&&!re&&__classPrivateFieldGet(this,Cm,`f`).recommendCommands(t,H)}__classPrivateFieldGet(this,Kp,`f`)&&q._.includes(__classPrivateFieldGet(this,Kp,`f`))&&!ne&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Hp,`f`).hasDefaultCommand()&&!re){let t=__classPrivateFieldGet(this,Hp,`f`).runCommand(null,this,W,0,N,Z||te||N);return this[$m](t,I,!!S,!1)}if(ne){__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),t=[].concat(t);let n=t.slice(t.indexOf(`--${__classPrivateFieldGet(this,Gp,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Gp,`f`).getCompletion(n,(t,n)=>{if(t)throw new Bl(t.message);(n||[]).forEach(t=>{__classPrivateFieldGet(this,am,`f`).log(t)}),this.exit(0)}),this[$m](q,!I,!!S,!1)}if(__classPrivateFieldGet(this,tm,`f`)||(Z?(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,this.showHelp(t=>{__classPrivateFieldGet(this,am,`f`).log(t),this.exit(0)})):te&&(__classPrivateFieldGet(this,Zp,`f`)&&setBlocking(!0),F=!0,__classPrivateFieldGet(this,bm,`f`).showVersion(`log`),this.exit(0))),!F&&__classPrivateFieldGet(this,sm,`f`).skipValidation.length>0&&(F=Object.keys(q).some(t=>__classPrivateFieldGet(this,sm,`f`).skipValidation.indexOf(t)>=0&&q[t]===!0)),!F){if(W.error)throw new Bl(W.error.message);if(!ne){let t=this[rh](X,{},W.error);S||(Y=applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!0)),Y=this[Um](t,Y??q),isPromise(Y)&&!S&&(Y=Y.then(()=>applyMiddleware(q,this,__classPrivateFieldGet(this,$p,`f`).getMiddleware(),!1)))}}}catch(t){if(t instanceof Bl)__classPrivateFieldGet(this,bm,`f`).fail(t.message,t);else throw t}return this[$m](Y??q,I,!!S,!0)}[rh](t,n,S,C){let N={...this.getDemandedOptions()};return F=>{if(S)throw new Bl(S.message);__classPrivateFieldGet(this,Cm,`f`).nonOptionCount(F),__classPrivateFieldGet(this,Cm,`f`).requiredArguments(F,N);let I=!1;__classPrivateFieldGet(this,vm,`f`)&&(I=__classPrivateFieldGet(this,Cm,`f`).unknownCommands(F)),__classPrivateFieldGet(this,_m,`f`)&&!I?__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,n,!!C):__classPrivateFieldGet(this,ym,`f`)&&__classPrivateFieldGet(this,Cm,`f`).unknownArguments(F,t,{},!1,!1),__classPrivateFieldGet(this,Cm,`f`).limitedChoices(F),__classPrivateFieldGet(this,Cm,`f`).implications(F),__classPrivateFieldGet(this,Cm,`f`).conflicting(F)}}[ih](){__classPrivateFieldSet(this,tm,!0,`f`)}[ah](t){if(typeof t==`string`)__classPrivateFieldGet(this,sm,`f`).key[t]=!0;else for(let n of t)__classPrivateFieldGet(this,sm,`f`).key[n]=!0}}}),ch,lh=__esmMin(()=>{Sp(),sh(),ch=YargsFactory(xp)});function classifyCliFailure(t,n){return typeof t==`string`&&t.length>0?{kind:`usage`,message:t}:{kind:`runtime`}}var uh=__esmMin(()=>{});function buildHeaders(t,n){let S={"user-agent":`gjsify-install/0.64.58`,"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 dh=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,RegistryUnreachableError,fh=__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):ph}function parseNpmrc(t){let n={registry:ph,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 ph,mh=__esmMin(()=>{ph=`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 hh=__esmMin(()=>{fh(),__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 gh=__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 vh=__esmMin(()=>{dh(),fh(),mh(),hh()});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 yh=__esmMin(()=>{dh(),fh(),hh(),gh()});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 bh=__esmMin(()=>{dh(),mh()}),xh=__esmMin(()=>{dh(),fh(),mh(),gh(),vh(),yh(),bh()});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 Sh===void 0&&(Sh=`0.64.58`),Sh}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 Sh,Ch=__esmMin(()=>{af(),Xn(),cr(),xh()}),wh,Th=__esmMin(()=>{wh=`gjsify`});function parseDeclaredChannel(t,n){if(!(t===void 0||t===``)){if(Eh.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a distribution channel. Known: ${Eh.join(`, `)}.`)}}function channelAllowsDonations(t){return t!==void 0&&Dh[t]===`external-link`}var Eh,Dh,Oh,kh=__esmMin(()=>{Eh=[`flathub`,`web`,`microsoft-store`,`apple-app-store`],Dh={flathub:`external-link`,web:`external-link`,"microsoft-store":`none`,"apple-app-store":`store-purchase`},Oh=`GJSIFY_CHANNEL`});function parseDeclaredPricing(t,n){if(!(t===void 0||t===``)){if(Ah.includes(t))return t;throw Error(`${n}: "${String(t)}" is not a pricing tier. Known: ${Ah.join(`, `)}.`)}}var Ah,jh,Mh=__esmMin(()=>{Ah=[`free`,`paid`],jh=`GJSIFY_PRICING`}),Nh=__commonJSMin(((t,n)=>{let S=(Xn(),__toCommonJS(Pn)),C=(eu(),__toCommonJS(Xl)),N=(af(),__toCommonJS(nf)),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)})),Ph=__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})),Fh=__commonJSMin(((t,n)=>{let S=Ph();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}}}})),Ih=__commonJSMin(((t,n)=>{var{__gjsifyModuleDir:S,__gjsifyModuleFile:C}=(iu(),__toCommonJS(tu)),N=S(`import-fresh/index.js`),F=C(`import-fresh/index.js`);let I=(Xn(),__toCommonJS(Pn)),H=Nh(),W=Fh();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)}})),Lh=__commonJSMin(((t,n)=>{n.exports=function isArrayish(t){return t?t instanceof Array||Array.isArray(t)||t.length>=0&&t.splice instanceof Function:!1}})),Rh=__commonJSMin(((t,n)=>{var S=(Uu(),__toCommonJS(zu)),C=Lh(),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})),zh=__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{}}})),Bh=__commonJSMin((t=>{t.__esModule=!0,t.LinesAndColumns=void 0;var n=`
|
|
@@ -951,7 +951,7 @@ Add @gjsify/node-gi as a dependency to run it on Node, e.g.:
|
|
|
951
951
|
echo "gjsify: got: node $*" >&2
|
|
952
952
|
exit 127 ;;
|
|
953
953
|
esac
|
|
954
|
-
`+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var Xz,Zz,Qz,$z=__esmMin(()=>{gl(),af(),o_(),Xn(),cr(),P_(),NR(),gL(),ZR(),Yz(),qI(),Xz=!1,Zz=!1,Qz=`node-shim`});function markDaemonCommand(){eB=!0}function isDaemonCommand(){return eB}var eB,tB=__esmMin(()=>{eB=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(zn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=In(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Un(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=zn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[zn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(zn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(
|
|
954
|
+
`+S+`exec "${C}" -m "${n}" run --node-script "$@"\n`}var Xz,Zz,Qz,$z=__esmMin(()=>{gl(),af(),o_(),Xn(),cr(),P_(),NR(),gL(),ZR(),Yz(),qI(),Xz=!1,Zz=!1,Qz=`node-shim`});function markDaemonCommand(){eB=!0}function isDaemonCommand(){return eB}var eB,tB=__esmMin(()=>{eB=!1});async function runTargetOnRuntime(t,n,S){if(!looksLikeFile(n))return ge.error(`gjsify run: --runtime ${t} needs a bundle FILE, but "${n}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${t===`gjs`?`gjs`:`node`} --outfile dist/app.${t===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let C=readPackageJson$1(zn(process.cwd(),`package.json`)),N=checkRuntimeSupported(t,readDeclaredRuntimes(C),C?.name??n);if(!N.ok)return ge.error(`gjsify run: ${N.message}`),process.exit(1);let F=In(n);t===`gjs`?await runGjsBundle(F,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(t,F,S,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(t){if(/\.gjs\.[mc]?js$/.test(t))return!0;try{let n=readFileSync(t,`utf-8`).slice(0,65536);return n.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(n)||/\bimports\.(?:gi|system)\b/.test(n)}catch{return!1}}function looksLikeFile(t){if(t.startsWith(`./`)||t.startsWith(`../`)||t.startsWith(`/`)||t.includes(`/`)||t.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(t))return!0;try{return statSync(t).isFile()}catch{return!1}}async function runScriptInWorkspace(t,n,S){let C=findWorkspaceRoot(process.cwd())??process.cwd(),N;try{N=discoverWorkspaces(C)}catch(t){return ge.error(`gjsify run: could not read workspaces at ${C}: ${t.message}`),process.exit(1)}let F=N.find(n=>n.name===t||n.relativeLocation===t||Un(n.location)===t);if(!F){let n=N.map(t=>t.relativeLocation).join(`, `)||`<none>`;return ge.error(`gjsify run: no workspace "${t}" under ${C} (available: ${n})`),process.exit(1)}await runScript(n,S,F.location)}async function runScript(t,n,S=process.cwd()){let C=zn(S,`package.json`),N=readPackageJson$1(C);if(!N)return ge.error(`gjsify run: no package.json in ${S}`),process.exit(1);let F=N.scripts??{},I=F[t];if(typeof I!=`string`){let n=Object.keys(F).join(`, `)||`<none>`;return ge.error(`gjsify run: no script "${t}" in ${C} (available: ${n})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[zn(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(zn(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let q=nodeShimDir();q&&W.unshift(q);let Y=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},X={...process.env,...Y,PATH:[...W,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:t,npm_package_name:N.name??``,npm_package_version:N.version??``},Z=isGjs()?gjsifyInProcessArgv(I,n):null;if(Z){process.env.PATH=X.PATH,process.env.npm_lifecycle_event=X.npm_lifecycle_event,process.env.npm_package_name=X.npm_package_name,process.env.npm_package_version=X.npm_package_version,X.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=X.FORCE_COLOR),S!==process.cwd()&&process.chdir(S);let t=!1;try{let{runCli:t}=await Promise.resolve().then(()=>(HX(),VX));await t(Z)}catch(n){ge.error(n.message),t=!0}if(!t&&isDaemonCommand())return;let n=t?1:process.exitCode==null?0:Number(process.exitCode);return process.exit(n)}let te=n.length>0?`${I} ${n.map(shellEscape).join(` `)}`:I,ne;try{ne=await spawnToCompletion(te,[],{completion:`exit`,cwd:S,env:X,shell:!0})}catch(t){return ge.error(t.message),process.exit(1)}return ne.code===0?process.exit(0):(ge.error(`script "${t}" exited with ${describeExit(ne)}`),process.exit(1))}function shellEscape(t){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(t)?t:`'${t.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(t,n){let S=gjsifyCommandArgv(t);return S?[...S,...n]:null}var nB,rB=__esmMin(()=>{_e(),af(),Xn(),TR(),hv(),VR(),UR(),YR(),XR(),$z(),qI(),sR(),tB(),GI(),P_(),vv(),nB={command:`run <target> [args..]`,description:"Run a script from package.json (yarn-run-style) or a GJS bundle file. If <target> resolves to a file on disk (or has a path-like prefix), it is launched via gjs with LD_LIBRARY_PATH + GI_TYPELIB_PATH set for native packages. Otherwise it is looked up in the current package.json `scripts`.",builder:t=>t.positional(`target`,{description:"Either a script name (looked up in package.json `scripts`) or a path to a GJS bundle (e.g. dist/gjs.js).",type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments passed through to the script / gjs.`,type:`string`,array:!0,default:[]}).option(`workspace`,{alias:`w`,type:`string`,description:"Run <target> as a script in the named workspace (by name or path), like `npm run <script> -w <name>`."}).option(`node-script`,{type:`boolean`,default:!1,description:"Treat <target> as an unbundled Node-style script (imports `node:` builtins) and run it on the host runtime. Under GJS the file is bundled `--app gjs` on the fly first, which is what makes a repo script runnable on a host that has no Node."}).option(`runtime`,{type:`string`,choices:gv,description:"Runtime to launch a bundle FILE on: gjs (default, `--app gjs` bundle) | node | bun | deno (the `--app node` bundle). Forces file mode."}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async t=>{let n=t.target,S=[...t.args??[],...doubleDashArgs(t)];if(t.nodeScript===!0){let isSet=t=>typeof t==`string`&&t.length>0,C=isSet(t.runtime)?`--runtime`:isSet(t.workspace)?`--workspace`:null;if(C)return ge.error(`gjsify run: --node-script cannot be combined with ${C}.`),process.exit(1);await runNodeScript(n,S,{completion:`exit`,exitOnSuccess:!0});return}let C=t.runtime;if(typeof C==`string`&&C.length>0){if(typeof t.workspace==`string`&&t.workspace.length>0)return ge.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(C))return ge.error(`gjsify run: unknown --runtime "${C}" (expected: ${gv.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(C,n,S);return}if(typeof t.workspace==`string`&&t.workspace.length>0){await runScriptInWorkspace(t.workspace,n,S);return}let N=readPackageJson$1(zn(process.cwd(),`package.json`));if(!(N?.scripts&&typeof N.scripts[n]==`string`)&&looksLikeFile(n)){let t=In(n),C=hostRuntime$1(),N=C===`gjs`||isLikelyGjsBundle(t)?`gjs`:C;N===`gjs`?await runGjsBundle(t,S,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(N,t,S,{completion:`exit`,exitOnSuccess:!0});return}await runScript(n,S)}}}),iB,aB=__esmMin(()=>{_e(),Xn(),gL(),iB={command:`info [file]`,description:`Show native gjsify packages detected in node_modules and the env vars needed to run a GJS bundle directly with gjs.`,builder:t=>t.positional(`file`,{description:`Optional: the GJS bundle path to include in the example command (e.g. dist/gjs.js)`,type:`string`,normalize:!0}).option(`export`,{description:`Output only shell export statements suitable for eval (eval $(gjsify info --export))`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.file?In(t.file):null,C=detectNativePackages(n),N=buildNativeEnv(C),F=Object.entries(N).filter(([,t])=>t!==void 0);if(t.export){for(let[t,n]of F)ge.log(`export ${t}="${n}"`);return}if(C.length===0){ge.log(`No native gjsify packages detected in node_modules.`),ge.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ge.log(`Native packages detected:`);for(let t of C)ge.log(` ${t.name} → ${t.prebuildsDir}`);ge.log(``),ge.log(`To run your app directly with gjs, set:`);for(let[t,n]of F)ge.log(` export ${t}="${n}"`);S?ge.log(` gjs -m ${S}`):ge.log(` gjs -m <your-bundle.js>`),ge.log(``),ge.log(`Or use gjsify run to handle this automatically:`),S?ge.log(` gjsify run ${t.file}`):ge.log(` gjsify run <your-bundle.js>`)}}}),oB,sB=__esmMin(()=>{_e(),dL(),oB={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:t=>t.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async t=>{let n=runAllChecks(process.cwd()),S=detectPackageManager$1(),C=checkTypeSkew(process.cwd()),N=n.filter(t=>!t.found&&t.severity===`required`),F=n.filter(t=>!t.found&&t.severity===`optional`),I=[...N,...F];if(t.json)return ge.log(JSON.stringify({packageManager:S,deps:n,typeSkew:C},null,2)),process.exit(+(N.length>0));ge.log(`System dependency check
|
|
955
955
|
`);let H=n.filter(t=>t.severity===`required`),W=n.filter(t=>t.severity===`optional`);if(H.length>0){ge.log(`Required:`);for(let t of H){let n=t.found?`✓`:`✗`,S=t.version?` (${t.version})`:``;ge.log(` ${n} ${t.name}${S}`)}}if(W.length>0){ge.log(`
|
|
956
956
|
Optional:`);for(let t of W){let n=t.found?`✓`:`⚠`,S=t.version?` (${t.version})`:``,C=t.requiredBy&&t.requiredBy.length>0?` — needed by ${t.requiredBy.join(`, `)}`:``;ge.log(` ${n} ${t.name}${S}${C}`)}}if(C.length>0){ge.log(`
|
|
957
957
|
Type/runtime version skew:`);for(let t of C){let n=t.relation===`ahead`?`⚠`:`ℹ`;ge.log(` ${n} ${t.typePackage} describes ${t.declared}, installed ${t.pkgConfig} is ${t.installed}`)}C.some(t=>t.relation===`ahead`)&&ge.log(`
|
|
@@ -972,7 +972,7 @@ No install command available for your package manager. Install manually.`),proce
|
|
|
972
972
|
bunx @gjsify/cli@latest showcase <name>
|
|
973
973
|
deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,kB={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:gv,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: ${gv.join(`, `)}).`),process.exit(1);if(requiresGjsSystemDeps(S)){let t=runMinimalChecks().filter(t=>!t.found&&t.severity===`required`);if(t.length>0){ge.error(`Missing system dependencies:
|
|
975
|
-
`);for(let n of t)ge.error(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),t);return n&&ge.error(`\nInstall with:\n ${n}`),process.exit(1)}}let C=readCliVersion();if(S!==`gjs`){await runShowcaseOnRuntime(n,S,C);return}let N=C?`${n.packageName}@${C}`:n.packageName;ge.log(`Running showcase: ${n.name} ${runningAs(C)}(via gjsify dlx ${N})\n`);try{let{runCli:t}=await Promise.resolve().then(()=>(
|
|
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(()=>(HX(),VX));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=jB[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 jB,MB=__esmMin(()=>{af(),eu(),Xn(),cr(),jB={"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,...PB[t]].join(` `)}function runScriptCommand(t){return FB[t]}function packageManagersForRuntime(t){return IB[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 NB,PB,FB,IB,LB,RB=__esmMin(()=>{NB=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],PB={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},FB={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},IB={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},LB={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 zB=__esmMin(()=>{RB()});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=[[BB,n],[VB,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(!HB.has(H)&&!UB.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 BB,VB,HB,UB,WB=__esmMin(()=>{_e(),cv(),af(),Xn(),MB(),RB(),zB(),BB=`new-gjsify-app`,VB=`org.gjsify.example`,HB=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`,`.svg`]),UB=new Set([`LICENSE`,`LICENCE`,`COPYING`,`NOTICE`])});function isCancelled(t){return t instanceof Error&&t.message===KB}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?`${GB.cyan}❯${GB.reset}`:` `,F=S===n?`${GB.bold}${GB.green}${C.label}${GB.reset}`:C.label,I=C.description?` ${GB.dim}${C.description}${GB.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(`${GB.bold}${t}${GB.reset} ${GB.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${GB.reset}\n`),render(n,F,!0),emitKeypressEvents(Sn),Sn.isTTY&&Sn.setRawMode(!0),Sn.resume();let cleanup=()=>{Sn.removeListener(`keypress`,onKeypress),Sn.isTTY&&Sn.setRawMode(!1),Sn.pause()},onKeypress=(t,S)=>{if(S){if(S.ctrl&&S.name===`c`){cleanup(),xn.write(`
|
|
976
976
|
`),N(Error(KB));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:LB[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 GB,KB,qB=__esmMin(()=>{_e(),Cn(),Xd(),RB(),zB(),GB={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},KB=`Cancelled by user`}),JB,YB=__esmMin(()=>{_e(),WB(),qB(),JB={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:NB})},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 XB,ZB,QB=__esmMin(()=>{_e(),cv(),Vd(),Xn(),Uu(),XB=promisify(execFile),ZB={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 XB(`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 $B=__esmMin(()=>{cv(),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 eV(`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 eV,tV,nV=__esmMin(()=>{_e(),cv(),Vd(),o_(),Xn(),Uu(),$B(),eV=promisify(execFile),tV={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}}}}),rV,iV,aV=__esmMin(()=>{_e(),cv(),Vd(),Xn(),Uu(),rV=promisify(execFile),iV={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 rV(`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 oV,sV=__esmMin(()=>{af(),Xn(),oV=`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 cV,lV,uV=__esmMin(()=>{cV=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],lV=[]});function pickFlatpakBuildKeys(t,n){let S=t??{},C={},N=[];for(let t of fV){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`?lV:cV),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 ${dV}. 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 dV,fV,pV=__esmMin(()=>{uV(),dV=`1.0.0`,fV=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return mV}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===``?`""`:hV.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
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,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var mV,hV,gV=__esmMin(()=>{kh(),mV=`[Desktop Entry]
|
|
@@ -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 wU,TU=__esmMin(()=>{CU(),wU=/^[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(!EU.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(!DU.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 EU,DU,OU=__esmMin(()=>{EU=/^\d[A-Za-z0-9.+~]*$/,DU=/^[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(kU,t))throw Error(`gjsify ship: \`gjsify.ship.app.${t}\` is not an OS this command assembles for. Known: ${Object.keys(kU).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`||!jU.test(F))throw Error(`gjsify ship: \`${N}.name\` must match ${jU} — 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(kU,t))throw Error(`gjsify ship: \`gjsify.ship.bundle.${t}\` is not an OS this command assembles for. Known: ${Object.keys(kU).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(kU).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 AU)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 kU,AU,jU,MU,NU,PU=__esmMin(()=>{TU(),af(),Xn(),xU(),hH(),pV(),OU(),kU={linux:!0,darwin:!0,win32:!0},AU=[[`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`}]],jU=/^[a-z0-9][a-z0-9._+-]*$/,MU=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`COPYING`,`COPYING.md`],NU=[`CHANGELOG.md`,`CHANGELOG`,`CHANGELOG.txt`,`NEWS.md`,`NEWS`]});function isFormatFilesId(t){return RU.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: ${RU.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 wU,TU=__esmMin(()=>{CU(),wU=/^[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(!EU.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(!DU.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 EU,DU,OU=__esmMin(()=>{EU=/^\d[A-Za-z0-9.+~]*$/,DU=/^[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(kU,t))throw Error(`gjsify ship: \`gjsify.ship.app.${t}\` is not an OS this command assembles for. Known: ${Object.keys(kU).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,...C.snap?.plugs===void 0||C.snap.plugs.length===0?{}:{snapPlugs:C.snap.plugs}},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`||!jU.test(F))throw Error(`gjsify ship: \`${N}.name\` must match ${jU} — 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(kU,t))throw Error(`gjsify ship: \`gjsify.ship.bundle.${t}\` is not an OS this command assembles for. Known: ${Object.keys(kU).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(kU).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 AU)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 kU,AU,jU,MU,NU,PU=__esmMin(()=>{TU(),af(),Xn(),xU(),hH(),pV(),OU(),kU={linux:!0,darwin:!0,win32:!0},AU=[[`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`}]],jU=/^[a-z0-9][a-z0-9._+-]*$/,MU=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`COPYING`,`COPYING.md`],NU=[`CHANGELOG.md`,`CHANGELOG`,`CHANGELOG.txt`,`NEWS.md`,`NEWS`]});function isFormatFilesId(t){return RU.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: ${RU.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=>FU.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),!IU.some(t=>C.toLowerCase().endsWith(t)))throw Error(`gjsify ship: \`gjsify.ship.fonts\` names ${n}, which is not a font face fontconfig will open (${IU.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),IU.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 (${IU.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=LU.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 (${IU.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 MU){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 NU){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 FU,IU,LU,RU,zU=__esmMin(()=>{af(),Xn(),PU(),FU=[`.svg`,`.png`],IU=[`.ttf`,`.otf`,`.ttc`,`.otc`],LU=[`.woff`,`.woff2`,`.eot`],RU=Object.keys({deb:null,rpm:null,appimage:null})});function isNodeRuntimeTarget(t){return BU.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 BU,VU=__esmMin(()=>{af(),Xn(),YI(),BU=[`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`${HU[n.getUTCDay()]}, ${pad(n.getUTCDate())} ${UU[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>WU&&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(`
|
|
@@ -1173,55 +1173,55 @@ A misplaced catalogue installs and then shows nothing, which reads exactly like
|
|
|
1173
1173
|
`).map(t=>t.trim()===``?` .`:` ${t}`).join(`
|
|
1174
1174
|
`);return[`Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/`,`Upstream-Name: ${t.name}`,...t.homepage?[`Source: ${t.homepage}`]:[],``,`Files: *`,`Copyright: ${t.maintainer}`,`License: ${t.license}`,S,``].join(`
|
|
1175
1175
|
`)}function planIcons(t){let n=[],S=new Map;for(let C of t.iconFiles){let N=Wn(C),F=iconThemeDir(C),I=isSymbolicIcon(C)?`${t.appId}-symbolic`:t.appId,H=`${_H.icons}/${F}/apps/${I}${N}`,W=S.get(H);if(W!==void 0)throw Error(`gjsify ship: ${C} and ${W} both install as ${H}. An icon is keyed on its context and its size: \`symbolic\` is read from a \`symbolic/\` path component or a \`-symbolic\` filename, the size from the path (\`.../128x128/...\`) or the filename (\`icon-128.png\`). Give them distinguishable sizes, or point \`gjsify.ship.icon\` at a single file.`);S.set(H,C),n.push({path:H,mode:420,source:{kind:`file`,path:C}})}return n}function assertInsidePrefix(t){let n=On.normalize(t);if(On.isAbsolute(n)||n===`..`||n.startsWith(`../`))throw Error(`gjsify ship: \`gjsify.ship.extraFiles\` destination "${t}" escapes the install prefix. Destinations are relative to the prefix, e.g. \`share/applications/extra.desktop\`.`);return n}function isExecutableAsset(t){return/\.(so|node|dylib)(\.\d+)*$/.test(t)}function normalise(t){let n=new Map;for(let S of t)n.set(S.path,S);return[...n.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}var KU=__esmMin(()=>{GU(),gH(),wH(),TU(),vH(),Vd(),Xn()});function isGtkRuntimeTarget(t){return qU.includes(t)}function gtkRuntimePackageName(t){return`@gjsify/gtk-runtime-${t}`}function resolveGtkRuntime(t,n={}){let S=n.env??process.env,C=t.startsWith(`win32-`)?`bin`:`lib`,N=[],F=S.GJSIFY_GTK_RUNTIME;F&&N.push({source:`GJSIFY_GTK_RUNTIME`,dir:F});let I=resolveNodeGiRoot(n);I!==null&&(N.push({source:`${YU}/prebuilds/${t}`,dir:zn(I,`prebuilds`,t,`gtk`)}),N.push({source:`${YU} sibling`,dir:zn(I,`..`,`gtk-runtime-${t}`,`gtk`)}));let H=gtkRuntimePackageName(t),W=resolveStagedPackage(H,n);W!==null&&N.push({source:H,dir:zn(Hn(W),`gtk`)}),n.fetchedGtkRuntimeDir!==void 0&&N.push({source:`${H} (fetched for this ship run)`,dir:zn(n.fetchedGtkRuntimeDir,`gtk`)});for(let t of N){let n=zn(t.dir,C),S=zn(t.dir,`girepository-1.0`);if(!(!existsSync(n)||!existsSync(S)))return{source:t.source,dir:t.dir,libDir:n,typelibDir:S}}return null}function resolveNodeGiAddon(t,n={}){let S=resolveNodeGiRoot(n);if(S===null)return null;let C=zn(S,`prebuilds`,t,JU);return existsSync(C)?{source:YU,addonPath:C}:null}function resolveNodeGiRoot(t){let n=resolveStagedPackage(YU,t);return n===null?null:Hn(n)}function resolveStagedPackage(t,n,{fromCli:S=!0}={}){let C=S?{bundleUrl:import.meta.url}:{};return n.cwd!==void 0&&(C.cwd=n.cwd),n.resolve!==void 0&&(C.resolve=n.resolve),resolveInstalledPackage(t,C)}function quartzBridgePackageName(t){return`${XU}-${t}`}function resolveQuartzBridge(t,n={}){if(!t.startsWith(`darwin-`))return null;let S=quartzBridgePackageName(t),dirOf=(t,n)=>{let S=resolveStagedPackage(`${t}/package.json`,n,{fromCli:!1});return S===null?null:Hn(S)},C=dirOf(S,n),N=null;if(C===null){if(N=dirOf(XU,n),N===null){let t=resolveStagedPackage(`@gjsify/adwaita-app`,n,{fromCli:!1}),S=t===null?null:packageRootOf(t);S!==null&&(N=dirOf(XU,{...n,cwd:S}))}N!==null&&(C=dirOf(S,{...n,cwd:N}))}if(C===null)return N===null?null:{unpopulated:`${S} is not installed`};let F=zn(C,`prebuilds`,t),I=zn(F,ZU),H=zn(F,QU);return!existsSync(I)||!existsSync(H)?{unpopulated:`${S} holds no prebuilds/${t}/{${ZU},${QU}}`}:{source:S,typelibPath:I,libraryPath:H}}function packageRootOf(t){let n=Hn(t);for(;;){if(existsSync(zn(n,`package.json`)))return n;let t=Hn(n);if(t===n)return null;n=t}}function resolveNodeGiPackage(t={}){let n=resolveNodeGiRoot(t);if(n===null)return null;let S=[`package.json`];for(let t of readdirSync(n,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1))t.isFile()&&t.name.endsWith(`.js`)&&S.push(t.name);let C=zn(n,`overrides`);if(existsSync(C))for(let t of listFilesRecursive(C))S.push(On.join(`overrides`,t));return S.length>1?{source:YU,root:n,files:S.sort()}:null}function appRuntimePaths(t,n,S){let C=t.dirs(n),N=On.join(C.native,`node-gi`),F=On.join(N,`prebuilds`,S);return{nodeGiRoot:N,nodeGiPackageDir:On.join(C.bundle,`node_modules`,YU),prebuildDir:F,gtkDir:On.join(F,`gtk`),addonPath:On.join(F,JU),interpreterPath:C.helpers===``?On.join(C.launcher,nodeRuntimeBinaryName(S)):On.join(C.helpers,assertUsableAsHelperName(n.name)),interpreterLicensePath:On.join(C.data,`licenses`,`node`,`LICENSE`)}}function stageAppRuntime(t){let n=appRuntimePaths(t.layout,t.identity,t.target),S=[],C={},N=[],F=[];t.interpreter===null?F.push(`no bundled interpreter — install \`@gjsify/node-runtime-${t.target}\` (or point \`GJSIFY_NODE_RUNTIME\` at a \`bin/\` directory holding \`node\` and its \`LICENSE\`)`):(S.push({path:n.interpreterPath,mode:493,source:{kind:`file`,path:t.interpreter.nodePath}}),S.push({path:n.interpreterLicensePath,mode:420,source:{kind:`file`,path:t.interpreter.licensePath}}),C.interpreter=n.interpreterPath,N.push(`interpreter from ${t.interpreter.source}`));let I=resolveGtkRuntime(t.target,discoveryOptions(t));if(I!==null){for(let t of listFilesRecursive(I.dir)){let C=zn(I.dir,t.split(`/`).join(qn));S.push({path:On.join(n.gtkDir,t),mode:stagedMode(t,C),source:{kind:`file`,path:C}})}C.gtkRuntimeDir=n.gtkDir,N.push(`GTK closure from ${I.source}`);let H=resolveQuartzBridge(t.target,discoveryOptions(t));H!==null&&`unpopulated`in H?F.push(`Dock-click reopen bridge not carried — ${H.unpopulated}`):H!==null&&(S.push({path:On.join(n.gtkDir,`girepository-1.0`,ZU),mode:420,source:{kind:`file`,path:H.typelibPath}}),S.push({path:On.join(n.gtkDir,nativeSubdirOf(t.target),QU),mode:493,source:{kind:`file`,path:H.libraryPath}}),N.push(`Dock-click reopen bridge from ${H.source}`))}else{let n=t.target.startsWith(`win32-`)?`bin`:`lib`,S=t.gtkFetchFailure===void 0?``:` — fetching it failed: ${t.gtkFetchFailure}`;F.push(`no GTK closure${S} — point \`GJSIFY_GTK_RUNTIME\` at a bundle directory holding \`${n}/\` and \`girepository-1.0/\`, or install \`${gtkRuntimePackageName(t.target)}\` where the build can reach it`)}let H=resolveNodeGiPackage(discoveryOptions(t));if(H!==null){for(let t of H.files)S.push({path:On.join(n.nodeGiPackageDir,t),mode:420,source:{kind:`file`,path:zn(H.root,t.split(`/`).join(qn))}});N.push(`node-gi runtime (${H.files.length} file(s)) from ${H.source}`)}else F.push(`no node-gi JavaScript — install \`${YU}\`; a \`--app node\` bundle keeps \`@gjsify/node-gi/*\` external, so the staged bundle would \`require\` a package the artifact does not carry`);let W=resolveNodeGiAddon(t.target,discoveryOptions(t));return W===null?F.push(`no node-gi addon — install \`${YU}\`, whose \`prebuilds/${t.target}/${JU}\` is the binary built against that closure`):(S.push({path:n.addonPath,mode:493,source:{kind:`file`,path:W.addonPath}}),C.nodeGiAddon=n.addonPath,N.push(`node-gi addon from ${W.source}`)),{files:S,launcher:C,found:N,missing:F}}function nativeSubdirOf(t){return t.startsWith(`win32-`)?`bin`:`lib`}function discoveryOptions(t){let n={};return t.cwd!==void 0&&(n.cwd=t.cwd),t.env!==void 0&&(n.env=t.env),t.resolve!==void 0&&(n.resolve=t.resolve),t.fetchedGtkRuntimeDir!==void 0&&(n.fetchedGtkRuntimeDir=t.fetchedGtkRuntimeDir),n}function stagedMode(t,n){if(isExecutableAsset(t)||t.startsWith(`libexec/`)||t.startsWith(`bin/`))return 493;try{if(statSync(n).mode&73)return 493}catch{}return 420}var qU,JU,YU,XU,ZU,QU,$U=__esmMin(()=>{af(),Xn(),zU(),oU(),VU(),KU(),YI(),qU=[`darwin-arm64`,`darwin-x64`,`win32-x64`,`win32-arm64`],JU=`node_gi.node`,YU=`@gjsify/node-gi`,XU=`@gjsify/gtk-quartz-native`,ZU=`GjsifyQuartz-1.0.typelib`,QU=`libgjsifyquartz.dylib`});function stageSubordinates(t){let n=t.layout.dirs(t.identity),S=[],C=[],N=[];for(let N of t.nestedBundles){if(n.plugins===``)throw Error(`gjsify ship: the ${t.layout.name} layout has no \`Contents/PlugIns\` equivalent, so the nested bundle "${N.name}" has nowhere to go. \`gjsify.ship.nestedBundles\` is darwin-only; \`resolveShipNestedBundles\` should have resolved this to \`[]\` already — report this as a gjsify bug if it did not.`);let F=On.join(n.plugins,N.name);for(let t of listFilesRecursive(N.source)){let n=zn(N.source,...t.split(On.sep));S.push({path:On.join(F,t),mode:/^Contents\/MacOS\/[^/]+$/.test(t)?493:stagedMode(t,n),source:{kind:`file`,path:n}})}C.push({path:F,entitlements:N.entitlements})}for(let C of t.helperExecutables){if(n.helpers===``)throw Error(`gjsify ship: the ${t.layout.name} layout has no \`Contents/Helpers\` equivalent, so the helper executable "${C.name}" has nowhere to go. \`gjsify.ship.helperExecutables\` is darwin-only; \`resolveShipHelperExecutables\` should have resolved this to \`[]\` already — report this as a gjsify bug if it did not.`);let F=On.join(n.helpers,C.name);S.push({path:F,mode:493,source:{kind:`file`,path:C.source}}),N.push({path:F,entitlements:C.entitlements})}if(t.mainExecutable!==void 0){if(t.layout.name!==`darwin`)throw Error(`gjsify ship: \`gjsify.ship.mainExecutable\` is darwin-only, but the ${t.layout.name} layout was asked to stage it — report this as a gjsify bug.`);S.push({path:mainExecutablePath(t.layout,t.identity),mode:493,source:{kind:`file`,path:t.mainExecutable}})}return{files:S,nestedBundles:C,helperExecutables:N}}function signedSubordinatesFor(t,n,S){let C=t.dirs(n);return{nestedBundles:S.nestedBundles.map(t=>({path:On.join(C.plugins,t.name),entitlements:t.entitlements})),helperExecutables:S.helperExecutables.map(t=>({path:On.join(C.helpers,t.name),entitlements:t.entitlements}))}}function plistStringValue(t,n){return RegExp(`<key>${n}</key>\\s*<string>([^<]*)</string>`).exec(t)?.[1]}function nestedBundlePlist(t,n){let S=t.find(t=>t.path===On.join(n,`Contents`,`Info.plist`));return S===void 0?void 0:new TextDecoder().decode(S.data)}function recordedNestedBundles(t,n){return n.map(n=>{let S=On.basename(n.path),C=nestedBundlePlist(t,n.path);if(C===void 0)return{name:S};let N=plistStringValue(C,`CFBundleIdentifier`),F=plistStringValue(C,`NSExtensionPointIdentifier`);return{name:S,...N===void 0?{}:{bundleId:N},...F===void 0?{}:{extensionPoint:F}}})}var eW=__esmMin(()=>{Xn(),zU(),$U(),oU()});function readManifest(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf-8`))}catch{return null}}function findInstalled(t,n){let S=n;for(;;){let n=zn(S,`node_modules`,...t.split(`/`));if(existsSync(zn(n,`package.json`)))return n;let C=Hn(S);if(C===S)return null;S=C}}function allows(t,n){let S=typeof t==`string`?[t]:t??[];if(S.includes(`!${n}`))return!1;let C=S.filter(t=>!t.startsWith(`!`));return C.length===0||C.includes(n)}function destinationOf(t){let n=t.split(qn),S=n.indexOf(`node_modules`);return S===-1||S===n.length-1?null:n.slice(S+1).join(`/`)}function resolveNodeModulesClosure(t,n,S={}){let{target:C,exclude:N=[]}=S,F=new Map,I=[],H=[],W=[],visit=(t,n,S,q)=>{if(t===tW)return;if(S.length>0&&N.includes(t)){W.includes(t)||W.push(t);return}let Y=findInstalled(t,n);if(Y===null){if(q){I.includes(t)||I.push(t);return}throw Error(`gjsify ship: \`${t}\` is not installed${S.length>0?` (needed by ${S.join(` > `)})`:``}. `+(S.length===0?"`gjsify.ship.nodeModules` names it, so the artifact must carry it — install it, or remove the entry.":`A package without its required dependency is an artifact that fails at its first import.`))}let X=destinationOf(Y);if(X===null)throw Error(`gjsify ship: ${Y} is not inside a node_modules directory, so it has no place to be staged.`);let Z=realpathSync(Y),te=readManifest(Z);if(te===null)throw Error(`gjsify ship: ${zn(Z,`package.json`)} is unreadable.`);if(S.length>0&&C!==void 0&&!(allows(te.os,C.os)&&allows(te.cpu,C.cpu))){H.includes(t)||H.push(t);return}let ne=F.get(X);if(ne!==void 0){if(ne.dir!==Z)throw Error(`gjsify ship: two installed copies of \`${t}\` would both be staged at node_modules/${X} (${ne.dir} and ${Z}).`);return}F.set(X,{name:t,version:te.version??`0.0.0`,dir:Z,dest:X});let re=[...S,t];for(let t of Object.keys(te.dependencies??{}))visit(t,Y,re,!1);for(let t of Object.keys(te.optionalDependencies??{}))visit(t,Y,re,!0)};for(let S of t)visit(S,n,[],!1);return{packages:[...F.values()].sort((t,n)=>t.dest<n.dest?-1:1),skippedOptional:I.sort(),skippedForTarget:H.sort(),excluded:W.sort(),target:C}}function prebuildPlatformOf(t){let n=/^(?:.*\/)?prebuilds\/([a-z0-9]+)-([a-z0-9_]+)(?:[-+][a-z0-9]+)?$/.exec(t);return n===null?null:[n[1],n[2]]}function listPackageFiles(t,n,S){let C=[],walk=N=>{for(let F of readdirSync(N,{withFileTypes:!0}).sort((t,n)=>t.name<n.name?-1:1)){let I=zn(N,F.name);if(F.isDirectory()){if(F.name===`node_modules`)continue;let C=n===void 0?null:prebuildPlatformOf(On.join(...Bn(t,I).split(qn)));if(C!==null&&(C[0]!==n.os||C[1]!==n.cpu)){S?.push(On.join(...Bn(t,I).split(qn)));continue}walk(I)}else if(F.isSymbolicLink())throw Error(`gjsify ship: ${I} is a symlink. The payload has to be self-contained — a package that links inside itself needs the link replaced by the file.`);else F.isFile()&&C.push(On.join(...Bn(t,I).split(qn)))}};return walk(t),C}function modeOf(t,n){return isExecutableAsset(t)||statSync(n).mode&73?493:420}function stageNodeModules(t,n){let S=[],C=[];t.skippedPrebuilds=C;for(let N of t.packages){let F=C.length;for(let F of listPackageFiles(N.dir,t.target,C)){let t=zn(N.dir,...F.split(`/`));S.push({path:On.join(n,`node_modules`,N.dest,F),mode:modeOf(F,t),source:{kind:`file`,path:t}})}for(let t=F;t<C.length;t++)C[t]=`${N.name}/${C[t]}`}return S}var tW,nW=__esmMin(()=>{af(),Xn(),KU(),tW=`@gjsify/node-gi`});async function acquireGtkRuntime(t){let n=t.discovery??{};if(resolveGtkRuntime(t.target,n)!==null)return{kind:`present`};let S=gtkRuntimePackageName(t.target),C=`${S}@${t.version}`;if((n.env??process.env).GJSIFY_GTK_RUNTIME_FETCH===`0`)return{kind:`failed`,reason:`GJSIFY_GTK_RUNTIME_FETCH=0 turned off the fetch of ${C}`};t.log?.(`${S} is not installed here, and is not meant to be — fetching ${C} into the cache (about 100 MB, once)`);let N;try{N=await t.ensure(C)}catch(t){return{kind:`failed`,reason:t instanceof Error?t.message:String(t)}}return resolveGtkRuntime(t.target,{...n,fetchedGtkRuntimeDir:N})===null?{kind:`failed`,reason:`${C} was fetched to ${N} but holds no complete gtk/ closure`}:{kind:`fetched`,dir:N}}var rW=__esmMin(()=>{$U()});function appDirFor(t){return zn(t,`appimage`,cW)}function appImageHostRequirements(t){let n=interpreterFloor(t),S=new Set(t.optionalNamespaces??[]);return[`${t.app} (>= ${n})`,...hostProvidedNamespaces(t.namespaces,t.bundledTypelibs).map(t=>S.has(t)?`the ${t} typelib (optional)`:`the ${t} typelib`)]}function interpreterFloor(t){return t.app===`node`?t.minNodeVersion??`24`:t.minGjsVersion??`1.86`}function renderAppRun(t,n){let S=rU.linux.dirs(t).launcher,C=interpreterFloor(t),[N=`0`,F=`0`]=C.split(`.`);return[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`here=$(dirname "$(readlink -f "$0")")`,`if ! command -v ${t.app} >/dev/null 2>&1; then`,` echo "${shellSafe(t.name)} needs ${t.app}, and this system has none." >&2`,` echo "This AppImage carries the application, not its runtime. It needs:" >&2`,...n.map(t=>` echo " - ${shellSafe(t)}" >&2`),` exit 127`,`fi`,`found=$(${t.app} --version 2>/dev/null | sed -n 's/[^0-9]*\\([0-9][0-9]*\\)\\.\\([0-9][0-9]*\\).*/\\1 \\2/p' | head -n 1 || true)`,"major=${found% *}","minor=${found#* }",`if [ -n "$major" ]; then`,` if [ "$major" -lt ${N} ] || { [ "$major" -eq ${N} ] && [ "$minor" -lt ${F} ]; }; then`,` echo "${shellSafe(t.name)} needs ${t.app} ${C} or newer, and this system has $major.$minor." >&2`,` echo "This AppImage carries the application, not its runtime. It needs:" >&2`,...n.map(t=>` echo " - ${shellSafe(t)}" >&2`),` exit 126`,` fi`,`fi`,`exec "$here/usr/${S}/${t.binaryName}" "$@"`,``].join(`
|
|
1176
|
-
`)}function shellSafe(t){return t.replace(/(["$`\\])/g,`\\$1`)}function findPinnedRuntime(t,n=process.env,S=existsSync){let C=n.GJSIFY_APPIMAGE_RUNTIME_DIR||`/usr/local/share/gjsify/appimage-runtime`,N=On.join(C,`runtime-${t}`);return S(N)?N:void 0}function appImageRuntimeNotice(t,n){return n===void 0?`NO pinned AppImage runtime for ${t}: appimagetool will fetch runtime-${t} from type2-runtime's rolling \`continuous\` tag, so this pack NEEDS A NETWORK and the ~940 KB of runtime it embeds carries no digest from this tree. Pin one at ${sW}/runtime-${t} (or point ${oW} at a directory holding it).`:`the AppImage runtime is pinned: ${n} — this pack needs no network`}function selectAppDirIcon(t,n){let S;for(let C of t){let t=rootIconRank(C.path,n);t!==void 0&&(S===void 0||t>S.rank)&&(S={entry:C,rank:t})}return S?.entry}function rootIconRank(t,n){if(dW.find(S=>t.endsWith(`${n}${S}`))===void 0||!t.startsWith(`${_H.icons}/`)||t.includes(`/symbolic/`))return;if(t.includes(`/scalable/`))return 2**53-1;let S=/\/(\d+)x\1\//.exec(t);return S===null?1:Number(S[1])}function assertAppImageIsPackable(t,n,S){let C=`${_H.applications}/${n.appId}.desktop`;if(!t.some(t=>t.path===C))throw Error(`gjsify ship: an AppImage needs a desktop entry and this payload has no ${C}. appimagetool refuses an AppDir without one, and the AppImage runtime has nothing to tell a desktop about the application it just mounted. A \`kind: "cli"\` project stages no entry by design — set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`);if(selectAppDirIcon(t,n.appId)===void 0)throw Error(`gjsify ship: an AppImage needs an icon called ${n.appId} beside its desktop entry, and this payload stages none under ${_H.icons}/. The entry's \`Icon=\` names the app id, so a file keeping its own basename is an icon nothing looks up — point \`gjsify.ship.icon\` at a PNG or an SVG and it is renamed into the theme for you.`);if(S===void 0&&t.some(t=>isSchemaSource(t.path)))throw Error(`gjsify ship: this payload stages GSettings schema sources under ${_H.schemas}/ and no ${uU} was compiled for it. An AppImage has NO INSTALL STEP — that is the whole point of the format — so the \`.deb\`/\`.rpm\` postinst that compiles the system schema directory never runs, and GSettings aborts on a directory holding only sources. The AppDir must carry ${uU}; \`compileSchemasForPayload\` produces it from this payload.`)}function appDirPayload(t,n,S,C){assertAppImageIsPackable(n,t,C);let N=selectAppDirIcon(n,t.appId),F=`${_H.applications}/${t.appId}.desktop`,I=n.find(t=>t.path===F);return[...[...n,...C===void 0?[]:[C]].map(t=>({...t,path:`usr/${t.path}`})),{path:lW,mode:493,data:encodeUtf8(renderAppRun(t,S))},{path:`${t.appId}.desktop`,mode:420,data:I.data},{path:N.path.slice(N.path.lastIndexOf(`/`)+1),mode:420,data:N.data},{path:uW,mode:420,data:N.data}]}function appImageToolArgs(t){return[`--no-appstream`,`--comp`,`zstd`,...t.runtimeFile===void 0?[]:[`--runtime-file`,t.runtimeFile],t.appDir,t.target]}function appImageToolEnv(t){return{ARCH:t,[aW]:`1`}}function appImageToolFailureMessage(t,n){let S=n===void 0?`the AppImage RUNTIME could not be downloaded — ${iW} fetches it from github.com/AppImage/type2-runtime when no runtime is pinned, so this pack needs a network and an offline host fails here having written nothing; or `:`the pinned runtime at ${n} is not an AppImage runtime — it is passed through to \`--runtime-file\` unread, so a truncated or wrong-architecture file fails here; or `;return`gjsify ship: ${iW} failed with ${t}. Four causes, measured in this order: ${S}\`file\` is not installed — ${iW} requires file(1) and says so, even though this pack already tells it the architecture; or FUSE is unavailable and the tool on PATH is a wrapper that dropped ${aW}=1, which this pack sets so the extract path is taken instead of a mount; or the work directory is full — the AppDir is copied into a squashfs image beside it.`}async function buildAppImage(t){let n=appImageToolArgs(t),S=appImageToolEnv(t.archLabel);t.verbose&&ge.log(`[gjsify ship] ${Object.entries(S).map(([t,n])=>`${t}=${n}`).join(` `)} ${iW} ${n.join(` `)}`);let C=await spawnToCompletion(iW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,env:{...process.env,...S},notFound:()=>Error(`gjsify ship: ${iW} is not on PATH. Unlike flatpak-builder and msitools it is not packaged by Fedora or Debian: take the release from https://github.com/AppImage/appimagetool/releases, \`chmod +x\` it and put it on PATH as \`${iW}\`. \`gjsify ship linux --stage\` needs none of this — the payload is assembled by this CLI and only the container needs the tool.`)});if(C.code!==0)throw Error(appImageToolFailureMessage(describeExit(C),t.runtimeFile));if(!existsSync(t.target))throw Error(`gjsify ship: ${iW} exited 0 and wrote no file at ${t.target}. An exit code is not an artifact — re-run with \`--verbose\` to see what it was told.`)}function appDirPaths(t){let n=new Set;for(let S of t){let t=S.path.split(`/`);for(let S=1;S<t.length;S++)n.add(t.slice(0,S).join(`/`))}return[...[...n].sort(),...t.map(t=>t.path)]}function stampAppDirTimes(t,n,S){for(let C of appDirPaths(n))utimesSync(zn(t,C.split(`/`).join(qn)),S,S);utimesSync(t,S,S)}var iW,aW,oW,sW,cW,lW,uW,dW,fW=__esmMin(()=>{_e(),af(),Xn(),hv(),rH(),hH(),oU(),dU(),vH(),iW=`appimagetool`,aW=`APPIMAGE_EXTRACT_AND_RUN`,oW=`GJSIFY_APPIMAGE_RUNTIME_DIR`,sW=`/usr/local/share/gjsify/appimage-runtime`,cW=`AppDir`,lW=`AppRun`,uW=`.DirIcon`,dW=[`.png`,`.svg`]});function dmgVolumeName(t){let n=t.name;if(n.trim()===``)throw Error("gjsify ship: the macOS image has no name to call its volume — `gjsify.ship.name` (or the package name it is derived from) is empty. `hdiutil` would accept that and mount the image as `untitled`, which is the name every nameless disk image on the machine has.");if(mW.test(n))throw Error(`gjsify ship: the macOS image would mount a volume called "${n}", and HFS+ cannot hold it: the Finder shows a stored ":" as a "/" and a stored "/" as a ":", so the volume would not be the one this project named. Set \`gjsify.ship.name\` to the display name you want.`);return n}function hdiutilCreateArgs(t){return[`create`,`-format`,`UDZO`,`-fs`,`HFS+J`,`-volname`,t.volumeName,`-srcfolder`,t.sourceDir,`-ov`,`-quiet`,t.target]}async function buildDmgImage(t){let n=hdiutilCreateArgs(t);t.verbose&&ge.log(`[gjsify ship] ${pW} ${n.join(` `)}`);let S=await spawnToCompletion(pW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${pW} is not on PATH. It ships with macOS and cannot be installed anywhere else, so this is either a broken macOS installation or a host that is not macOS at all. A \`.dmg\` is packed on darwin (ADR 0024 § A1); from anywhere else the route is \`gjsify ship darwin --stage\` here and \`gjsify ship --from-stage <dir> --target macos-app-dmg\` there.`)});if(S.code!==0)throw Error(`gjsify ship: ${pW} failed with ${describeExit(S)}.`)}function dmgVolumeDir(t){return zn(t,`dmg`,`volume`)}function addApplicationsLink(t){symlinkSync(hW.target,zn(t,hW.name))}function codesignDmgArgs(t){return[`--force`,`--sign`,t.identity,...t.adhoc?[]:[`--timestamp`],t.file]}async function signDmgImage(t){let n=codesignDmgArgs(t);t.verbose&&ge.log(`[gjsify ship] ${gW} ${n.join(` `)}`);let S=await spawnToCompletion(gW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${gW} is not on PATH, so the image cannot be signed. Install the Xcode Command Line Tools (\`xcode-select --install\`).`)});if(S.code!==0)throw Error(`gjsify ship: ${gW} failed on the image with ${describeExit(S)}.`)}async function stapleBundleBeforeImage(t){t.writeArchive(),await t.notarize(),await t.staple()}var pW,mW,hW,gW,_W=__esmMin(()=>{_e(),af(),Xn(),hv(),pW=`hdiutil`,mW=/[/:]/,hW={name:`Applications`,target:`/Applications`},gW=`codesign`});function renderShipFlatpakManifest(t){let{settings:n,stageDir:S,overlayDir:C}=t,N=n.flatpak,F={id:n.appId,runtime:N.runtime,"runtime-version":N.runtimeVersion,sdk:N.sdk,branch:N.branch,command:n.binaryName,"finish-args":N.finishArgs,"separate-locales":!1};return N.sdkExtensions.length>0&&(F[`sdk-extensions`]=N.sdkExtensions),N.appendPath.length>0&&(F[`build-options`]={"append-path":N.appendPath.join(`:`)}),N.cleanup.length>0&&(F.cleanup=N.cleanup),F.modules=[{name:n.binaryName,buildsystem:`simple`,"build-commands":[`mkdir -p /app`,`cp -a stage/. /app/`,`cp -a overlay/. /app/`],sources:[{type:`dir`,path:S,dest:`stage`,skip:[t.stageManifestFile]},{type:`dir`,path:C,dest:`overlay`}]}],F}async function buildFlatpakBundle(t){let{settings:n,workDir:S,archLabel:C}=t,N=zn(S,`${n.appId}.json`),F=zn(S,`build`),I=zn(S,`repo`),H=zn(S,`state`);mkdirSync(S,{recursive:!0}),rmSync(I,{recursive:!0,force:!0,maxRetries:5}),writeFileSync(N,`${JSON.stringify(renderShipFlatpakManifest(t),null,2)}\n`),await run$1(`flatpak-builder`,[`--force-clean`,`--disable-rofiles-fuse`,`--delete-build-dirs`,`--state-dir=${H}`,`--arch=${C}`,`--repo=${I}`,F,N],t,"flatpak-builder not found. Install it (Fedora: `sudo dnf install flatpak-builder`)."),await run$1(`flatpak`,[`build-bundle`,`--arch=${C}`,I,t.target,n.appId,n.flatpak.branch],t,`flatpak not found. Install it via your distro: see https://flathub.org/setup.`)}async function run$1(t,n,S,C){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let N=await spawnToCompletion(t,n,{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${C}`)});if(N.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(N)}.`)}var vW=__esmMin(()=>{_e(),af(),Xn(),hv(),__name$1(run$1,`run`)});function resolveHandMetainfo(t){let n=(t.configReleases?.length??0)>0,S,C;if(t.shipMetainfo!==void 0){if(S=`gjsify.ship.metainfo`,C=t.shipMetainfo,n)throw Error(`gjsify ship: \`gjsify.ship.metainfo\` and \`gjsify.ship.releases\` both describe the releases. The file is staged verbatim, so the config entries would be dropped without a word — keep the \`<releases>\` in ${C} and remove \`releases\` from the config.`)}else if(t.siteMetainfo!==void 0&&!n)S=`gjsify.site.metainfo`,C=t.siteMetainfo;else return;let N=In(t.projectDir,C);if(!existsSync(N))throw Error(`gjsify ship: \`${S}\` points at ${C}, which does not exist (${N}).`);return{path:C,xml:readFileSync(N,`utf-8`),key:S}}function readFacts(t){let n={releaseVersions:[]},S=[],C=``;for(let N of scanXml(t))if(N.kind===`open`){let t=N.name;t===`release`&&N.attributes.version!==void 0&&n.releaseVersions.push(N.attributes.version),t===`launchable`&&N.attributes.type===`desktop-id`&&!N.selfClosing?(S.push(`launchable`),C=``):t===`id`&&S.length===0&&n.id===void 0&&!N.selfClosing&&(S.push(`id`),C=``)}else if(N.kind===`text`)S.length>0&&(C+=N.text);else if(S.length>0){let t=S.pop();t===`id`?n.id=C.trim():t===`launchable`&&(n.launchable=C.trim())}return n}function checkHandMetainfo(t,n){let S=readFacts(t.xml);if(S.id!==n.appId)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <id>${S.id??``}</id>, but the package's application id is "${n.appId}" (\`gjsify.ship.appId\`). Stores resolve the component by the <id> inside the file, so one of the two is wrong.`);if(n.kind===`app`&&S.launchable!==void 0&&S.launchable!==`${n.appId}.desktop`)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <launchable type="desktop-id">${S.launchable}</launchable>, but \`ship\` stages the desktop entry as ${n.appId}.desktop.`);let C=[];return S.releaseVersions.includes(n.version)||C.push(`${t.path} has no <release version="${n.version}"> — the shipped component will not list the version it is packaged as.`),C}var yW=__esmMin(()=>{af(),Xn(),Ye()});function localeOf(t){return t.split(`/`)[0]??``}function fold(t,n,S,C,N){let F=zn(N,`source${S}`);return writeFileSync(F,n),readFileSync(mergeCatalogues({mode:t,template:F,extension:S,catalogues:C,workDir:N}),`utf-8`)}function localizeMetadata(t,n){if(n.length===0)return t;let S=mkdtempSync(zn(tmpdir(),`gjsify-ship-l10n-`));try{let C=[...n].sort((t,n)=>t.rel<n.rel?-1:+(t.rel>n.rel)),N=new Map;for(let[t,n]of C.entries()){let C=zn(S,`${t}.po`);execFileSync(`msgunfmt`,[n.abs,`--output-file`,C],{stdio:`pipe`});let F=localeOf(n.rel);N.set(F,[...N.get(F)??[],C])}let F=[...N].map(([t,n])=>({locale:t,po:n.length===1?n[0]:msgcat(n,zn(S,`${t}.merged.po`))}));return{metainfo:fold(`--xml`,t.metainfo,`.metainfo.xml`,F,S),desktopEntry:t.desktopEntry===void 0?void 0:fold(`--desktop`,t.desktopEntry,`.desktop`,F,S)}}catch(t){throw Error(describeFailure(t,n.length))}finally{rmSync(S,{recursive:!0,force:!0})}}function msgcat(t,n){return execFileSync(`msgcat`,[`--use-first`,`--output-file`,n,...t],{stdio:`pipe`}),n}function describeFailure(t,n){let S=t;return S?.code===`ENOENT`?`gjsify ship: \`msgfmt\`/\`msgunfmt\`/\`msgcat\` are not on PATH, but the package stages ${n} gettext catalogue(s). Install them (package: gettext) — shipping the metadata untranslated would install an English app menu entry for a translated app, which nothing downstream can detect.`:`gjsify ship: could not fold the gettext catalogues into the freedesktop metadata.${S?.stderr===void 0?``:`\n${String(S.stderr).trim()}`}`}var bW=__esmMin(()=>{cv(),af(),o_(),Xn(),$B()});function base64Encode(t){let n=``,S=32768;for(let C=0;C<t.length;C+=S)n+=String.fromCharCode(...t.subarray(C,C+S));return btoa(n)}function base64Decode(t){let n=atob(t),S=new Uint8Array(n.length);for(let t=0;t<n.length;t++)S[t]=n.charCodeAt(t);return S}var xW=__esmMin(()=>{});function toPackSettings(t){return{binaryName:t.binaryName,appId:t.appId,name:t.name,version:t.version,release:t.release,maintainer:t.maintainer,summary:t.summary,description:t.description,license:t.license,...t.homepage===void 0?{}:{homepage:t.homepage},section:t.section,group:t.group,extraDepends:t.extraDepends,typelibPackages:t.typelibPackages,app:t.app,minGjsVersion:t.minGjsVersion,minNodeVersion:t.minNodeVersion,...t.nodeModulesDirs===void 0||t.nodeModulesDirs.length===0?{}:{nodeModulesDirs:t.nodeModulesDirs},flatpak:t.flatpak,executables:t.executables.map(({name:t,gui:n})=>({name:t,gui:n})),nestedBundles:t.nestedBundles.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),helperExecutables:t.helperExecutables.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),...t.hasMainExecutable===!0?{hasMainExecutable:!0}:{}}}function stageManifestPath(t){return zn(t,SW)}function formatTarget(t){return`${t.os}-${t.arch}`}function writeStageManifest(t){let n={};for(let S of t.formats)n[S.id]=(t.overlay.get(S.id)??[]).map(t=>{if(t.source.kind===`text`)return{path:t.path,mode:t.mode,text:t.source.text};if(t.source.kind===`bytes`)return{path:t.path,mode:t.mode,base64:base64Encode(t.source.data)};throw Error(`gjsify ship: internal error — the ${S.id} overlay entry ${t.path} is a file reference, and a stage manifest may only carry rendered bytes. Render it in \`planOverlay\` instead.`)});let S={schema:6,tool:{name:`@gjsify/cli`,version:cliVersion()},target:{os:t.settings.layoutOs,arch:t.settings.arch},formats:t.formats.map(t=>t.id),mtime:t.mtime,namespaces:[...t.namespaces],optionalNamespaces:[...t.optionalNamespaces??[]],settings:toPackSettings(t.settings),staged:t.staged.map(n=>({path:n.path,mode:n.mode,bytes:statSync(zn(t.stageDir,n.path.split(`/`).join(qn))).size})),overlay:n};return writeFileSync(stageManifestPath(t.stageDir),`${JSON.stringify(S,null,2)}\n`),S}function readStageManifest(t){let n=stageManifestPath(t);if(!existsSync(n))throw Error(`gjsify ship: ${t} has no ${SW}, so it is not a stage this command can pack. A stage is produced by \`gjsify ship --stage\`, which writes that file at the stage root beside the payload. If you pointed --from-stage at a project's \`ship/\` directory, point it at \`ship/stage/\` instead.`);let S;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch(t){throw Error(`gjsify ship: ${n} is not readable JSON (${t.message}). Re-run the \`--stage\` phase; a truncated manifest means the stage transfer was truncated too.`)}if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`gjsify ship: ${n} is not a JSON object. Re-run the \`--stage\` phase.`);let C=S,N=C.schema;if(typeof N!=`number`||!Number.isInteger(N))throw Error(`gjsify ship: ${n} has no integer \`schema\` field, so it was not written by \`gjsify ship --stage\`. Re-run the \`--stage\` phase.`);if(N>6)throw Error(`gjsify ship: ${n} declares schema ${N} and this gjsify understands 6. The stage was assembled by a newer gjsify: upgrade this one (\`gjsify self-update\`), or re-run the \`--stage\` phase with this version. A manifest from the future is refused rather than partially read, because an unknown field could be the one that decides a file's mode.`);if(N<6)throw Error(`gjsify ship: ${n} declares schema ${N} and this gjsify understands 6. Re-run the \`--stage\` phase with this gjsify. A stage is a short-lived intermediate between two jobs of one run, not an archive, so no migration is kept for it.`);let at=t=>`${n} → ${t}`,F=record(C.tool,at(`tool`)),I=record(C.target,at(`target`)),H={schema:N,tool:{name:expectString(F.name,at(`tool.name`)),version:expectString(F.version,at(`tool.version`))},target:{os:expectLayoutOs(expectString(I.os,at(`target.os`)),at(`target.os`)),arch:expectString(I.arch,at(`target.arch`))},formats:expectArray(C.formats,at(`formats`)).map((t,n)=>{let S=expectString(t,at(`formats[${n}]`));if(!XW.includes(S))throw Error(`gjsify ship: ${at(`formats[${n}]`)} is "${S}", which this gjsify does not know. Known formats: ${XW.join(`, `)}.`);return S}),mtime:expectInteger(C.mtime,at(`mtime`)),namespaces:expectArray(C.namespaces,at(`namespaces`)).map((t,n)=>expectString(t,at(`namespaces[${n}]`))),...C.optionalNamespaces===void 0?{}:{optionalNamespaces:expectArray(C.optionalNamespaces,at(`optionalNamespaces`)).map((t,n)=>expectString(t,at(`optionalNamespaces[${n}]`)))},settings:readPackSettings(record(C.settings,at(`settings`)),at(`settings`)),staged:expectArray(C.staged,at(`staged`)).map((t,n)=>{let S=record(t,at(`staged[${n}]`));return{path:expectString(S.path,at(`staged[${n}].path`)),mode:expectInteger(S.mode,at(`staged[${n}].mode`)),bytes:expectInteger(S.bytes,at(`staged[${n}].bytes`))}}),overlay:{}};if(H.staged.length===0)throw Error(`gjsify ship: ${at(`staged`)} is empty, so this stage describes no payload. A stage always carries at least the launcher its plan named. Re-run the \`--stage\` phase; a stage that lost its plan cannot be packed into anything but an empty package.`);let W=record(C.overlay,at(`overlay`));for(let t of H.formats)H.overlay[t]=expectArray(W[t],at(`overlay.${t}`)).map((n,S)=>{let C=record(n,at(`overlay.${t}[${S}]`)),N=at(`overlay.${t}[${S}]`);if(C.text===void 0==(C.base64===void 0))throw Error(`gjsify ship: ${N} must carry exactly one of \`text\` and \`base64\`. An overlay entry is either rendered text or rendered bytes; an entry with neither would pack an empty file at a path the format requires content at.`);return{path:expectString(C.path,at(`overlay.${t}[${S}].path`)),mode:expectInteger(C.mode,at(`overlay.${t}[${S}].mode`)),...C.text===void 0?{base64:expectString(C.base64,at(`overlay.${t}[${S}].base64`))}:{text:expectString(C.text,at(`overlay.${t}[${S}].text`))}}});return H}function expectLayoutOs(t,n){try{return layoutForOs(t).os}catch{let S=iU.map(t=>rU[t].os).join(`, `);throw Error(`gjsify ship: ${n} is "${t}", which is not a layout this gjsify can pack. It carries the \`process.platform\` spelling and only that — ${S}, so \`win32\` and never \`windows\`. A stage holds exactly one OS's layout and every path in it has that OS's shape, so there is nothing to pack here. Re-run the \`--stage\` phase.`)}}function overlayFiles(t,n){return(t.overlay[n]??[]).map(t=>({path:t.path,mode:t.mode,source:t.base64===void 0?{kind:`text`,text:t.text??``}:{kind:`bytes`,data:base64Decode(t.base64)}}))}function assertExpectedTarget(t,n){if(n===void 0)return;let S=formatTarget(t.target);if(n!==S)throw Error(`gjsify ship: --expect-target ${n} but this stage was assembled for ${S}. The stage records the target its \`--arch\` resolved to at stage time, so this is a stage from another matrix leg: download the artifact belonging to ${n}, or drop --expect-target if packing this one is what you meant.`)}function assertFormatsStaged(t,n){let S=n.filter(n=>!t.formats.includes(n.id)).map(t=>t.id);if(S.length!==0)throw Error(`gjsify ship: this stage was assembled for ${t.formats.length===0?`no format at all`:t.formats.join(`, `)}, and --target names ${S.join(`, `)}. Phase one renders each format's overlay — rpm wants the licence at \`share/licenses/<pkg>/LICENSE\`, deb wants a machine-readable copyright at \`share/doc/<pkg>/copyright\` — so a format the stage never saw would pack without it, and Debian Policy § 12.5 makes that a broken package. Re-run \`gjsify ship --stage --target ${[...t.formats,...S].join(`,`)}\` on the assembling host.`)}function resolveStageMtime(t,n=process.env){let S=n.SOURCE_DATE_EPOCH;return S===void 0||Number(S)===t.mtime?{mtime:t.mtime,warnings:[]}:{mtime:t.mtime,warnings:[`SOURCE_DATE_EPOCH is ${S} here and this stage was stamped ${t.mtime}. The stage's stamp wins, because changing it would make this artifact differ from the same stage packed on the assembling host. Set the same value in both jobs, or set it in neither.`]}}function warnOnToolSkew(t){let n=cliVersion();return t.tool.version===n?[]:[`this stage was assembled by ${t.tool.name} ${t.tool.version} and is being packed by ${n}. Both phases run the same packer, so a version difference can change the artifact's bytes. Pin both jobs to one gjsify version.`]}function readPackSettings(t,n){let field=t=>`${n}.${t}`,S=record(t.extraDepends,field(`extraDepends`)),C=record(t.typelibPackages,field(`typelibPackages`));return{binaryName:expectString(t.binaryName,field(`binaryName`)),appId:expectString(t.appId,field(`appId`)),name:expectString(t.name,field(`name`)),version:expectString(t.version,field(`version`)),release:expectString(t.release,field(`release`)),maintainer:expectString(t.maintainer,field(`maintainer`)),summary:expectString(t.summary,field(`summary`)),description:expectArray(t.description,field(`description`)).map((t,n)=>expectString(t,field(`description[${n}]`))),license:expectString(t.license,field(`license`)),...t.homepage===void 0?{}:{homepage:expectString(t.homepage,field(`homepage`))},section:expectString(t.section,field(`section`)),group:expectString(t.group,field(`group`)),extraDepends:{deb:expectArray(S.deb??[],field(`extraDepends.deb`)).map((t,n)=>expectString(t,field(`extraDepends.deb[${n}]`))),rpm:expectArray(S.rpm??[],field(`extraDepends.rpm`)).map((t,n)=>expectString(t,field(`extraDepends.rpm[${n}]`)))},typelibPackages:Object.fromEntries(Object.entries(C).map(([t,n])=>{let S=record(n,field(`typelibPackages.${t}`));return[t,{deb:expectString(S.deb,field(`typelibPackages.${t}.deb`)),rpm:expectString(S.rpm,field(`typelibPackages.${t}.rpm`))}]})),app:expectApp(t.app,field(`app`)),minGjsVersion:expectString(t.minGjsVersion,field(`minGjsVersion`)),minNodeVersion:expectString(t.minNodeVersion,field(`minNodeVersion`)),flatpak:readFlatpakSettings(record(t.flatpak,field(`flatpak`)),field(`flatpak`)),...t.nodeModulesDirs===void 0?{}:{nodeModulesDirs:expectArray(t.nodeModulesDirs,field(`nodeModulesDirs`)).map((t,n)=>expectString(t,field(`nodeModulesDirs[${n}]`)))},executables:expectArray(t.executables??[],field(`executables`)).map((t,n)=>{let S=record(t,field(`executables[${n}]`));if(typeof S.gui!=`boolean`)throw Error(`gjsify ship: ${field(`executables[${n}].gui`)} must be a boolean.`);return{name:expectString(S.name,field(`executables[${n}].name`)),gui:S.gui}}),nestedBundles:expectArray(t.nestedBundles??[],field(`nestedBundles`)).map((t,n)=>{let S=record(t,field(`nestedBundles[${n}]`));return{name:expectString(S.name,field(`nestedBundles[${n}].name`)),entitlements:expectArray(S.entitlements,field(`nestedBundles[${n}].entitlements`)).map((t,S)=>expectString(t,field(`nestedBundles[${n}].entitlements[${S}]`)))}}),helperExecutables:expectArray(t.helperExecutables??[],field(`helperExecutables`)).map((t,n)=>{let S=record(t,field(`helperExecutables[${n}]`));return{name:expectString(S.name,field(`helperExecutables[${n}].name`)),entitlements:expectArray(S.entitlements,field(`helperExecutables[${n}].entitlements`)).map((t,S)=>expectString(t,field(`helperExecutables[${n}].entitlements[${S}]`)))}}),...t.hasMainExecutable===void 0?{}:(()=>{if(typeof t.hasMainExecutable!=`boolean`)throw Error(`gjsify ship: ${field(`hasMainExecutable`)} must be a boolean.`);return t.hasMainExecutable?{hasMainExecutable:!0}:{}})()}}function readFlatpakSettings(t,n){let field=t=>`${n}.${t}`,strings=(t,n)=>expectArray(t,field(n)).map((t,S)=>expectString(t,field(`${n}[${S}]`)));return{runtime:expectString(t.runtime,field(`runtime`)),runtimeVersion:expectString(t.runtimeVersion,field(`runtimeVersion`)),sdk:expectString(t.sdk,field(`sdk`)),branch:expectString(t.branch,field(`branch`)),sdkExtensions:strings(t.sdkExtensions,`sdkExtensions`),appendPath:strings(t.appendPath,`appendPath`),finishArgs:strings(t.finishArgs,`finishArgs`),cleanup:strings(t.cleanup,`cleanup`)}}function record(t,n){if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`gjsify ship: ${n} must be an object. Re-run the \`--stage\` phase.`);return t}function expectArray(t,n){if(!Array.isArray(t))throw Error(`gjsify ship: ${n} must be an array. Re-run the \`--stage\` phase.`);return t}function expectApp(t,n){if(t===`gjs`||t===`node`)return t;throw Error(`gjsify ship: ${n} must be "gjs" or "node", got ${JSON.stringify(t)}.`)}function expectString(t,n){if(typeof t!=`string`)throw Error(`gjsify ship: ${n} must be a string. Re-run the \`--stage\` phase.`);return t}function expectInteger(t,n){if(typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`gjsify ship: ${n} must be a non-negative integer. Re-run the \`--stage\` phase. (Modes are decimal here — JSON has no octal literal, so 0o755 is written 493.)`);return t}var SW,CW=__esmMin(()=>{af(),Xn(),xW(),Ch(),QW(),oU(),SW=`.gjsify-ship-stage.json`});function writeStage(t,n){for(let t of n)if(t.path===`.gjsify-ship-stage.json`)throw Error(`gjsify ship: a payload file may not be called \`${SW}\` — that name belongs to the stage manifest, which sits at the stage root beside the payload and carries what the packing host needs (ADR 0024 § A2). Rename the \`gjsify.ship.extraFiles\` destination.`);rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let S of n){let n=zn(t,S.path.split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0});let C;switch(S.source.kind){case`text`:C=new TextEncoder().encode(S.source.text);break;case`file`:C=new Uint8Array(readFileSync(S.source.path));break;case`bytes`:C=S.source.data;break;default:{let t=S.source;throw Error(`gjsify ship: no writer for the "${JSON.stringify(t)}" source kind.`)}}writeFileSync(n,C),chmodSync(n,S.mode)}}function readStage(t,n){let S=new Map(n.map(t=>[t.path,t])),C=new Map;for(let n of t)for(let t of listFilesRecursive(n)){if(t===`.gjsify-ship-stage.json`)continue;let N=S.get(t);if(N===void 0)throw Error(`gjsify ship: ${zn(n,t.split(`/`).join(qn))} is in the stage and not in its manifest, so nothing knows what mode to give it. Every payload file takes its mode from the plan, never from the filesystem, so a file that arrived some other way would be packed 0644 — unrunnable if it is a program. Remove it, or add it through \`gjsify.ship.extraFiles\` and re-run the \`--stage\` phase.`);let F=new Uint8Array(readFileSync(zn(n,t.split(`/`).join(qn))));if(N.bytes!==void 0&&N.bytes!==F.byteLength)throw Error(`gjsify ship: ${t} is ${F.byteLength} bytes in the stage and ${N.bytes} in its manifest. The stage arrived truncated or was edited after it was assembled. Re-upload it, or re-run the \`--stage\` phase.`);C.set(t,{path:t,mode:N.mode,data:F})}let N=n.filter(t=>!C.has(t.path)).map(t=>t.path);if(N.length>0)throw Error(`gjsify ship: the stage manifest lists ${N.length} file(s) the stage does not contain: ${N.slice(0,5).join(`, `)}${N.length>5?`, …`:``}. A payload has to be complete before it is packed — both formats would pack the rest without complaint and install a package that cannot start. Re-run the \`--stage\` phase, and check that whatever moved the stage between hosts copied every file (an artifact upload that drops empty files or dotfiles is the usual cause).`);return[...C.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function writePayload(t,n,S){let C=S===``?``:`${S}/`;rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let N of n){if(!N.path.startsWith(C))throw Error(`gjsify ship: ${N.path} is outside ${S||`the artifact`}, which this artifact IS — so there is nowhere inside it for the file to go. A payload file that escaped the bundle would ship beside it, unsigned and unfound.`);let n=zn(t,N.path.slice(C.length).split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,N.data),chmodSync(n,N.mode)}}function directorySize(t){let n=0;for(let S of listFilesRecursive(t))n+=statSync(zn(t,S.split(`/`).join(qn))).size;return n}var wW=__esmMin(()=>{af(),Xn(),zU(),CW()});function isSnapName(t){return t.length<=MW&&jW.test(t)}function assertSnapIsPackable(t,n){let S=[];isSnapName(n.binaryName)||S.push(`the binary name "${n.binaryName}" is not a snap name (lowercase letters, digits and single hyphens, at most ${MW} characters, at least one letter)`),n.version.length>NW&&S.push(`the version "${n.version}" is longer than ${NW} characters`),n.summary.length>PW&&S.push(`the summary is ${n.summary.length} characters, the store takes ${PW}`);let C=snapDesktopPath(n);if(t.some(t=>t.path===C)||S.push(`the payload has no ${C}, which the snap's \`desktop:\` key must point at`),S.length>0)throw Error(`gjsify ship: cannot pack a snap: ${S.join(`; `)}.`)}function snapDesktopPath(t){return`${_H.applications}/${t.appId}.desktop`}function renderSnapcraftManifest(t){let{settings:n}=t,S={command:`${AW}/bin/${n.binaryName}`,extensions:[`gnome`],desktop:`${AW}/${snapDesktopPath(n)}`,"common-id":n.appId,environment:{GI_TYPELIB_PATH:OW}},C={name:n.binaryName,title:n.name,base:EW,version:n.version,summary:n.summary,description:n.description.join(`
|
|
1176
|
+
`)}function shellSafe(t){return t.replace(/(["$`\\])/g,`\\$1`)}function findPinnedRuntime(t,n=process.env,S=existsSync){let C=n.GJSIFY_APPIMAGE_RUNTIME_DIR||`/usr/local/share/gjsify/appimage-runtime`,N=On.join(C,`runtime-${t}`);return S(N)?N:void 0}function appImageRuntimeNotice(t,n){return n===void 0?`NO pinned AppImage runtime for ${t}: appimagetool will fetch runtime-${t} from type2-runtime's rolling \`continuous\` tag, so this pack NEEDS A NETWORK and the ~940 KB of runtime it embeds carries no digest from this tree. Pin one at ${sW}/runtime-${t} (or point ${oW} at a directory holding it).`:`the AppImage runtime is pinned: ${n} — this pack needs no network`}function selectAppDirIcon(t,n){let S;for(let C of t){let t=rootIconRank(C.path,n);t!==void 0&&(S===void 0||t>S.rank)&&(S={entry:C,rank:t})}return S?.entry}function rootIconRank(t,n){if(dW.find(S=>t.endsWith(`${n}${S}`))===void 0||!t.startsWith(`${_H.icons}/`)||t.includes(`/symbolic/`))return;if(t.includes(`/scalable/`))return 2**53-1;let S=/\/(\d+)x\1\//.exec(t);return S===null?1:Number(S[1])}function assertAppImageIsPackable(t,n,S){let C=`${_H.applications}/${n.appId}.desktop`;if(!t.some(t=>t.path===C))throw Error(`gjsify ship: an AppImage needs a desktop entry and this payload has no ${C}. appimagetool refuses an AppDir without one, and the AppImage runtime has nothing to tell a desktop about the application it just mounted. A \`kind: "cli"\` project stages no entry by design — set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`);if(selectAppDirIcon(t,n.appId)===void 0)throw Error(`gjsify ship: an AppImage needs an icon called ${n.appId} beside its desktop entry, and this payload stages none under ${_H.icons}/. The entry's \`Icon=\` names the app id, so a file keeping its own basename is an icon nothing looks up — point \`gjsify.ship.icon\` at a PNG or an SVG and it is renamed into the theme for you.`);if(S===void 0&&t.some(t=>isSchemaSource(t.path)))throw Error(`gjsify ship: this payload stages GSettings schema sources under ${_H.schemas}/ and no ${uU} was compiled for it. An AppImage has NO INSTALL STEP — that is the whole point of the format — so the \`.deb\`/\`.rpm\` postinst that compiles the system schema directory never runs, and GSettings aborts on a directory holding only sources. The AppDir must carry ${uU}; \`compileSchemasForPayload\` produces it from this payload.`)}function appDirPayload(t,n,S,C){assertAppImageIsPackable(n,t,C);let N=selectAppDirIcon(n,t.appId),F=`${_H.applications}/${t.appId}.desktop`,I=n.find(t=>t.path===F);return[...[...n,...C===void 0?[]:[C]].map(t=>({...t,path:`usr/${t.path}`})),{path:lW,mode:493,data:encodeUtf8(renderAppRun(t,S))},{path:`${t.appId}.desktop`,mode:420,data:I.data},{path:N.path.slice(N.path.lastIndexOf(`/`)+1),mode:420,data:N.data},{path:uW,mode:420,data:N.data}]}function appImageToolArgs(t){return[`--no-appstream`,`--comp`,`zstd`,...t.runtimeFile===void 0?[]:[`--runtime-file`,t.runtimeFile],t.appDir,t.target]}function appImageToolEnv(t){return{ARCH:t,[aW]:`1`}}function appImageToolFailureMessage(t,n){let S=n===void 0?`the AppImage RUNTIME could not be downloaded — ${iW} fetches it from github.com/AppImage/type2-runtime when no runtime is pinned, so this pack needs a network and an offline host fails here having written nothing; or `:`the pinned runtime at ${n} is not an AppImage runtime — it is passed through to \`--runtime-file\` unread, so a truncated or wrong-architecture file fails here; or `;return`gjsify ship: ${iW} failed with ${t}. Four causes, measured in this order: ${S}\`file\` is not installed — ${iW} requires file(1) and says so, even though this pack already tells it the architecture; or FUSE is unavailable and the tool on PATH is a wrapper that dropped ${aW}=1, which this pack sets so the extract path is taken instead of a mount; or the work directory is full — the AppDir is copied into a squashfs image beside it.`}async function buildAppImage(t){let n=appImageToolArgs(t),S=appImageToolEnv(t.archLabel);t.verbose&&ge.log(`[gjsify ship] ${Object.entries(S).map(([t,n])=>`${t}=${n}`).join(` `)} ${iW} ${n.join(` `)}`);let C=await spawnToCompletion(iW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,env:{...process.env,...S},notFound:()=>Error(`gjsify ship: ${iW} is not on PATH. Unlike flatpak-builder and msitools it is not packaged by Fedora or Debian: take the release from https://github.com/AppImage/appimagetool/releases, \`chmod +x\` it and put it on PATH as \`${iW}\`. \`gjsify ship linux --stage\` needs none of this — the payload is assembled by this CLI and only the container needs the tool.`)});if(C.code!==0)throw Error(appImageToolFailureMessage(describeExit(C),t.runtimeFile));if(!existsSync(t.target))throw Error(`gjsify ship: ${iW} exited 0 and wrote no file at ${t.target}. An exit code is not an artifact — re-run with \`--verbose\` to see what it was told.`)}function appDirPaths(t){let n=new Set;for(let S of t){let t=S.path.split(`/`);for(let S=1;S<t.length;S++)n.add(t.slice(0,S).join(`/`))}return[...[...n].sort(),...t.map(t=>t.path)]}function stampAppDirTimes(t,n,S){for(let C of appDirPaths(n))utimesSync(zn(t,C.split(`/`).join(qn)),S,S);utimesSync(t,S,S)}var iW,aW,oW,sW,cW,lW,uW,dW,fW=__esmMin(()=>{_e(),af(),Xn(),hv(),rH(),hH(),oU(),dU(),vH(),iW=`appimagetool`,aW=`APPIMAGE_EXTRACT_AND_RUN`,oW=`GJSIFY_APPIMAGE_RUNTIME_DIR`,sW=`/usr/local/share/gjsify/appimage-runtime`,cW=`AppDir`,lW=`AppRun`,uW=`.DirIcon`,dW=[`.png`,`.svg`]});function dmgVolumeName(t){let n=t.name;if(n.trim()===``)throw Error("gjsify ship: the macOS image has no name to call its volume — `gjsify.ship.name` (or the package name it is derived from) is empty. `hdiutil` would accept that and mount the image as `untitled`, which is the name every nameless disk image on the machine has.");if(mW.test(n))throw Error(`gjsify ship: the macOS image would mount a volume called "${n}", and HFS+ cannot hold it: the Finder shows a stored ":" as a "/" and a stored "/" as a ":", so the volume would not be the one this project named. Set \`gjsify.ship.name\` to the display name you want.`);return n}function hdiutilCreateArgs(t){return[`create`,`-format`,`UDZO`,`-fs`,`HFS+J`,`-volname`,t.volumeName,`-srcfolder`,t.sourceDir,`-ov`,`-quiet`,t.target]}async function buildDmgImage(t){let n=hdiutilCreateArgs(t);t.verbose&&ge.log(`[gjsify ship] ${pW} ${n.join(` `)}`);let S=await spawnToCompletion(pW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${pW} is not on PATH. It ships with macOS and cannot be installed anywhere else, so this is either a broken macOS installation or a host that is not macOS at all. A \`.dmg\` is packed on darwin (ADR 0024 § A1); from anywhere else the route is \`gjsify ship darwin --stage\` here and \`gjsify ship --from-stage <dir> --target macos-app-dmg\` there.`)});if(S.code!==0)throw Error(`gjsify ship: ${pW} failed with ${describeExit(S)}.`)}function dmgVolumeDir(t){return zn(t,`dmg`,`volume`)}function addApplicationsLink(t){symlinkSync(hW.target,zn(t,hW.name))}function codesignDmgArgs(t){return[`--force`,`--sign`,t.identity,...t.adhoc?[]:[`--timestamp`],t.file]}async function signDmgImage(t){let n=codesignDmgArgs(t);t.verbose&&ge.log(`[gjsify ship] ${gW} ${n.join(` `)}`);let S=await spawnToCompletion(gW,n,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${gW} is not on PATH, so the image cannot be signed. Install the Xcode Command Line Tools (\`xcode-select --install\`).`)});if(S.code!==0)throw Error(`gjsify ship: ${gW} failed on the image with ${describeExit(S)}.`)}async function stapleBundleBeforeImage(t){t.writeArchive(),await t.notarize(),await t.staple()}var pW,mW,hW,gW,_W=__esmMin(()=>{_e(),af(),Xn(),hv(),pW=`hdiutil`,mW=/[/:]/,hW={name:`Applications`,target:`/Applications`},gW=`codesign`});function renderShipFlatpakManifest(t){let{settings:n,stageDir:S,overlayDir:C}=t,N=n.flatpak,F={id:n.appId,runtime:N.runtime,"runtime-version":N.runtimeVersion,sdk:N.sdk,branch:N.branch,command:n.binaryName,"finish-args":N.finishArgs,"separate-locales":!1};return N.sdkExtensions.length>0&&(F[`sdk-extensions`]=N.sdkExtensions),N.appendPath.length>0&&(F[`build-options`]={"append-path":N.appendPath.join(`:`)}),N.cleanup.length>0&&(F.cleanup=N.cleanup),F.modules=[{name:n.binaryName,buildsystem:`simple`,"build-commands":[`mkdir -p /app`,`cp -a stage/. /app/`,`cp -a overlay/. /app/`],sources:[{type:`dir`,path:S,dest:`stage`,skip:[t.stageManifestFile]},{type:`dir`,path:C,dest:`overlay`}]}],F}async function buildFlatpakBundle(t){let{settings:n,workDir:S,archLabel:C}=t,N=zn(S,`${n.appId}.json`),F=zn(S,`build`),I=zn(S,`repo`),H=zn(S,`state`);mkdirSync(S,{recursive:!0}),rmSync(I,{recursive:!0,force:!0,maxRetries:5}),writeFileSync(N,`${JSON.stringify(renderShipFlatpakManifest(t),null,2)}\n`),await run$1(`flatpak-builder`,[`--force-clean`,`--disable-rofiles-fuse`,`--delete-build-dirs`,`--state-dir=${H}`,`--arch=${C}`,`--repo=${I}`,F,N],t,"flatpak-builder not found. Install it (Fedora: `sudo dnf install flatpak-builder`)."),await run$1(`flatpak`,[`build-bundle`,`--arch=${C}`,I,t.target,n.appId,n.flatpak.branch],t,`flatpak not found. Install it via your distro: see https://flathub.org/setup.`)}async function run$1(t,n,S,C){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let N=await spawnToCompletion(t,n,{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${C}`)});if(N.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(N)}.`)}var vW=__esmMin(()=>{_e(),af(),Xn(),hv(),__name$1(run$1,`run`)});function resolveHandMetainfo(t){let n=(t.configReleases?.length??0)>0,S,C;if(t.shipMetainfo!==void 0){if(S=`gjsify.ship.metainfo`,C=t.shipMetainfo,n)throw Error(`gjsify ship: \`gjsify.ship.metainfo\` and \`gjsify.ship.releases\` both describe the releases. The file is staged verbatim, so the config entries would be dropped without a word — keep the \`<releases>\` in ${C} and remove \`releases\` from the config.`)}else if(t.siteMetainfo!==void 0&&!n)S=`gjsify.site.metainfo`,C=t.siteMetainfo;else return;let N=In(t.projectDir,C);if(!existsSync(N))throw Error(`gjsify ship: \`${S}\` points at ${C}, which does not exist (${N}).`);return{path:C,xml:readFileSync(N,`utf-8`),key:S}}function readFacts(t){let n={releaseVersions:[]},S=[],C=``;for(let N of scanXml(t))if(N.kind===`open`){let t=N.name;t===`release`&&N.attributes.version!==void 0&&n.releaseVersions.push(N.attributes.version),t===`launchable`&&N.attributes.type===`desktop-id`&&!N.selfClosing?(S.push(`launchable`),C=``):t===`id`&&S.length===0&&n.id===void 0&&!N.selfClosing&&(S.push(`id`),C=``)}else if(N.kind===`text`)S.length>0&&(C+=N.text);else if(S.length>0){let t=S.pop();t===`id`?n.id=C.trim():t===`launchable`&&(n.launchable=C.trim())}return n}function checkHandMetainfo(t,n){let S=readFacts(t.xml);if(S.id!==n.appId)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <id>${S.id??``}</id>, but the package's application id is "${n.appId}" (\`gjsify.ship.appId\`). Stores resolve the component by the <id> inside the file, so one of the two is wrong.`);if(n.kind===`app`&&S.launchable!==void 0&&S.launchable!==`${n.appId}.desktop`)throw Error(`gjsify ship: ${t.path} (\`${t.key}\`) has <launchable type="desktop-id">${S.launchable}</launchable>, but \`ship\` stages the desktop entry as ${n.appId}.desktop.`);let C=[];return S.releaseVersions.includes(n.version)||C.push(`${t.path} has no <release version="${n.version}"> — the shipped component will not list the version it is packaged as.`),C}var yW=__esmMin(()=>{af(),Xn(),Ye()});function localeOf(t){return t.split(`/`)[0]??``}function fold(t,n,S,C,N){let F=zn(N,`source${S}`);return writeFileSync(F,n),readFileSync(mergeCatalogues({mode:t,template:F,extension:S,catalogues:C,workDir:N}),`utf-8`)}function localizeMetadata(t,n){if(n.length===0)return t;let S=mkdtempSync(zn(tmpdir(),`gjsify-ship-l10n-`));try{let C=[...n].sort((t,n)=>t.rel<n.rel?-1:+(t.rel>n.rel)),N=new Map;for(let[t,n]of C.entries()){let C=zn(S,`${t}.po`);execFileSync(`msgunfmt`,[n.abs,`--output-file`,C],{stdio:`pipe`});let F=localeOf(n.rel);N.set(F,[...N.get(F)??[],C])}let F=[...N].map(([t,n])=>({locale:t,po:n.length===1?n[0]:msgcat(n,zn(S,`${t}.merged.po`))}));return{metainfo:fold(`--xml`,t.metainfo,`.metainfo.xml`,F,S),desktopEntry:t.desktopEntry===void 0?void 0:fold(`--desktop`,t.desktopEntry,`.desktop`,F,S)}}catch(t){throw Error(describeFailure(t,n.length))}finally{rmSync(S,{recursive:!0,force:!0})}}function msgcat(t,n){return execFileSync(`msgcat`,[`--use-first`,`--output-file`,n,...t],{stdio:`pipe`}),n}function describeFailure(t,n){let S=t;return S?.code===`ENOENT`?`gjsify ship: \`msgfmt\`/\`msgunfmt\`/\`msgcat\` are not on PATH, but the package stages ${n} gettext catalogue(s). Install them (package: gettext) — shipping the metadata untranslated would install an English app menu entry for a translated app, which nothing downstream can detect.`:`gjsify ship: could not fold the gettext catalogues into the freedesktop metadata.${S?.stderr===void 0?``:`\n${String(S.stderr).trim()}`}`}var bW=__esmMin(()=>{cv(),af(),o_(),Xn(),$B()});function base64Encode(t){let n=``,S=32768;for(let C=0;C<t.length;C+=S)n+=String.fromCharCode(...t.subarray(C,C+S));return btoa(n)}function base64Decode(t){let n=atob(t),S=new Uint8Array(n.length);for(let t=0;t<n.length;t++)S[t]=n.charCodeAt(t);return S}var xW=__esmMin(()=>{});function toPackSettings(t){return{binaryName:t.binaryName,appId:t.appId,name:t.name,version:t.version,release:t.release,maintainer:t.maintainer,summary:t.summary,description:t.description,license:t.license,...t.homepage===void 0?{}:{homepage:t.homepage},section:t.section,group:t.group,extraDepends:t.extraDepends,typelibPackages:t.typelibPackages,app:t.app,minGjsVersion:t.minGjsVersion,minNodeVersion:t.minNodeVersion,...t.nodeModulesDirs===void 0||t.nodeModulesDirs.length===0?{}:{nodeModulesDirs:t.nodeModulesDirs},flatpak:t.flatpak,...t.snapPlugs===void 0||t.snapPlugs.length===0?{}:{snapPlugs:t.snapPlugs},executables:t.executables.map(({name:t,gui:n})=>({name:t,gui:n})),nestedBundles:t.nestedBundles.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),helperExecutables:t.helperExecutables.map(({name:t,entitlements:n})=>({name:t,entitlements:n})),...t.hasMainExecutable===!0?{hasMainExecutable:!0}:{}}}function stageManifestPath(t){return zn(t,SW)}function formatTarget(t){return`${t.os}-${t.arch}`}function writeStageManifest(t){let n={};for(let S of t.formats)n[S.id]=(t.overlay.get(S.id)??[]).map(t=>{if(t.source.kind===`text`)return{path:t.path,mode:t.mode,text:t.source.text};if(t.source.kind===`bytes`)return{path:t.path,mode:t.mode,base64:base64Encode(t.source.data)};throw Error(`gjsify ship: internal error — the ${S.id} overlay entry ${t.path} is a file reference, and a stage manifest may only carry rendered bytes. Render it in \`planOverlay\` instead.`)});let S={schema:6,tool:{name:`@gjsify/cli`,version:cliVersion()},target:{os:t.settings.layoutOs,arch:t.settings.arch},formats:t.formats.map(t=>t.id),mtime:t.mtime,namespaces:[...t.namespaces],optionalNamespaces:[...t.optionalNamespaces??[]],settings:toPackSettings(t.settings),staged:t.staged.map(n=>({path:n.path,mode:n.mode,bytes:statSync(zn(t.stageDir,n.path.split(`/`).join(qn))).size})),overlay:n};return writeFileSync(stageManifestPath(t.stageDir),`${JSON.stringify(S,null,2)}\n`),S}function readStageManifest(t){let n=stageManifestPath(t);if(!existsSync(n))throw Error(`gjsify ship: ${t} has no ${SW}, so it is not a stage this command can pack. A stage is produced by \`gjsify ship --stage\`, which writes that file at the stage root beside the payload. If you pointed --from-stage at a project's \`ship/\` directory, point it at \`ship/stage/\` instead.`);let S;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch(t){throw Error(`gjsify ship: ${n} is not readable JSON (${t.message}). Re-run the \`--stage\` phase; a truncated manifest means the stage transfer was truncated too.`)}if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`gjsify ship: ${n} is not a JSON object. Re-run the \`--stage\` phase.`);let C=S,N=C.schema;if(typeof N!=`number`||!Number.isInteger(N))throw Error(`gjsify ship: ${n} has no integer \`schema\` field, so it was not written by \`gjsify ship --stage\`. Re-run the \`--stage\` phase.`);if(N>6)throw Error(`gjsify ship: ${n} declares schema ${N} and this gjsify understands 6. The stage was assembled by a newer gjsify: upgrade this one (\`gjsify self-update\`), or re-run the \`--stage\` phase with this version. A manifest from the future is refused rather than partially read, because an unknown field could be the one that decides a file's mode.`);if(N<6)throw Error(`gjsify ship: ${n} declares schema ${N} and this gjsify understands 6. Re-run the \`--stage\` phase with this gjsify. A stage is a short-lived intermediate between two jobs of one run, not an archive, so no migration is kept for it.`);let at=t=>`${n} → ${t}`,F=record(C.tool,at(`tool`)),I=record(C.target,at(`target`)),H={schema:N,tool:{name:expectString(F.name,at(`tool.name`)),version:expectString(F.version,at(`tool.version`))},target:{os:expectLayoutOs(expectString(I.os,at(`target.os`)),at(`target.os`)),arch:expectString(I.arch,at(`target.arch`))},formats:expectArray(C.formats,at(`formats`)).map((t,n)=>{let S=expectString(t,at(`formats[${n}]`));if(!ZW.includes(S))throw Error(`gjsify ship: ${at(`formats[${n}]`)} is "${S}", which this gjsify does not know. Known formats: ${ZW.join(`, `)}.`);return S}),mtime:expectInteger(C.mtime,at(`mtime`)),namespaces:expectArray(C.namespaces,at(`namespaces`)).map((t,n)=>expectString(t,at(`namespaces[${n}]`))),...C.optionalNamespaces===void 0?{}:{optionalNamespaces:expectArray(C.optionalNamespaces,at(`optionalNamespaces`)).map((t,n)=>expectString(t,at(`optionalNamespaces[${n}]`)))},settings:readPackSettings(record(C.settings,at(`settings`)),at(`settings`)),staged:expectArray(C.staged,at(`staged`)).map((t,n)=>{let S=record(t,at(`staged[${n}]`));return{path:expectString(S.path,at(`staged[${n}].path`)),mode:expectInteger(S.mode,at(`staged[${n}].mode`)),bytes:expectInteger(S.bytes,at(`staged[${n}].bytes`))}}),overlay:{}};if(H.staged.length===0)throw Error(`gjsify ship: ${at(`staged`)} is empty, so this stage describes no payload. A stage always carries at least the launcher its plan named. Re-run the \`--stage\` phase; a stage that lost its plan cannot be packed into anything but an empty package.`);let W=record(C.overlay,at(`overlay`));for(let t of H.formats)H.overlay[t]=expectArray(W[t],at(`overlay.${t}`)).map((n,S)=>{let C=record(n,at(`overlay.${t}[${S}]`)),N=at(`overlay.${t}[${S}]`);if(C.text===void 0==(C.base64===void 0))throw Error(`gjsify ship: ${N} must carry exactly one of \`text\` and \`base64\`. An overlay entry is either rendered text or rendered bytes; an entry with neither would pack an empty file at a path the format requires content at.`);return{path:expectString(C.path,at(`overlay.${t}[${S}].path`)),mode:expectInteger(C.mode,at(`overlay.${t}[${S}].mode`)),...C.text===void 0?{base64:expectString(C.base64,at(`overlay.${t}[${S}].base64`))}:{text:expectString(C.text,at(`overlay.${t}[${S}].text`))}}});return H}function expectLayoutOs(t,n){try{return layoutForOs(t).os}catch{let S=iU.map(t=>rU[t].os).join(`, `);throw Error(`gjsify ship: ${n} is "${t}", which is not a layout this gjsify can pack. It carries the \`process.platform\` spelling and only that — ${S}, so \`win32\` and never \`windows\`. A stage holds exactly one OS's layout and every path in it has that OS's shape, so there is nothing to pack here. Re-run the \`--stage\` phase.`)}}function overlayFiles(t,n){return(t.overlay[n]??[]).map(t=>({path:t.path,mode:t.mode,source:t.base64===void 0?{kind:`text`,text:t.text??``}:{kind:`bytes`,data:base64Decode(t.base64)}}))}function assertExpectedTarget(t,n){if(n===void 0)return;let S=formatTarget(t.target);if(n!==S)throw Error(`gjsify ship: --expect-target ${n} but this stage was assembled for ${S}. The stage records the target its \`--arch\` resolved to at stage time, so this is a stage from another matrix leg: download the artifact belonging to ${n}, or drop --expect-target if packing this one is what you meant.`)}function assertFormatsStaged(t,n){let S=n.filter(n=>!t.formats.includes(n.id)).map(t=>t.id);if(S.length!==0)throw Error(`gjsify ship: this stage was assembled for ${t.formats.length===0?`no format at all`:t.formats.join(`, `)}, and --target names ${S.join(`, `)}. Phase one renders each format's overlay — rpm wants the licence at \`share/licenses/<pkg>/LICENSE\`, deb wants a machine-readable copyright at \`share/doc/<pkg>/copyright\` — so a format the stage never saw would pack without it, and Debian Policy § 12.5 makes that a broken package. Re-run \`gjsify ship --stage --target ${[...t.formats,...S].join(`,`)}\` on the assembling host.`)}function resolveStageMtime(t,n=process.env){let S=n.SOURCE_DATE_EPOCH;return S===void 0||Number(S)===t.mtime?{mtime:t.mtime,warnings:[]}:{mtime:t.mtime,warnings:[`SOURCE_DATE_EPOCH is ${S} here and this stage was stamped ${t.mtime}. The stage's stamp wins, because changing it would make this artifact differ from the same stage packed on the assembling host. Set the same value in both jobs, or set it in neither.`]}}function warnOnToolSkew(t){let n=cliVersion();return t.tool.version===n?[]:[`this stage was assembled by ${t.tool.name} ${t.tool.version} and is being packed by ${n}. Both phases run the same packer, so a version difference can change the artifact's bytes. Pin both jobs to one gjsify version.`]}function readPackSettings(t,n){let field=t=>`${n}.${t}`,S=record(t.extraDepends,field(`extraDepends`)),C=record(t.typelibPackages,field(`typelibPackages`));return{binaryName:expectString(t.binaryName,field(`binaryName`)),appId:expectString(t.appId,field(`appId`)),name:expectString(t.name,field(`name`)),version:expectString(t.version,field(`version`)),release:expectString(t.release,field(`release`)),maintainer:expectString(t.maintainer,field(`maintainer`)),summary:expectString(t.summary,field(`summary`)),description:expectArray(t.description,field(`description`)).map((t,n)=>expectString(t,field(`description[${n}]`))),license:expectString(t.license,field(`license`)),...t.homepage===void 0?{}:{homepage:expectString(t.homepage,field(`homepage`))},section:expectString(t.section,field(`section`)),group:expectString(t.group,field(`group`)),extraDepends:{deb:expectArray(S.deb??[],field(`extraDepends.deb`)).map((t,n)=>expectString(t,field(`extraDepends.deb[${n}]`))),rpm:expectArray(S.rpm??[],field(`extraDepends.rpm`)).map((t,n)=>expectString(t,field(`extraDepends.rpm[${n}]`)))},typelibPackages:Object.fromEntries(Object.entries(C).map(([t,n])=>{let S=record(n,field(`typelibPackages.${t}`));return[t,{deb:expectString(S.deb,field(`typelibPackages.${t}.deb`)),rpm:expectString(S.rpm,field(`typelibPackages.${t}.rpm`))}]})),app:expectApp(t.app,field(`app`)),minGjsVersion:expectString(t.minGjsVersion,field(`minGjsVersion`)),minNodeVersion:expectString(t.minNodeVersion,field(`minNodeVersion`)),flatpak:readFlatpakSettings(record(t.flatpak,field(`flatpak`)),field(`flatpak`)),...t.snapPlugs===void 0?{}:{snapPlugs:expectArray(t.snapPlugs,field(`snapPlugs`)).map((t,n)=>expectString(t,field(`snapPlugs[${n}]`)))},...t.nodeModulesDirs===void 0?{}:{nodeModulesDirs:expectArray(t.nodeModulesDirs,field(`nodeModulesDirs`)).map((t,n)=>expectString(t,field(`nodeModulesDirs[${n}]`)))},executables:expectArray(t.executables??[],field(`executables`)).map((t,n)=>{let S=record(t,field(`executables[${n}]`));if(typeof S.gui!=`boolean`)throw Error(`gjsify ship: ${field(`executables[${n}].gui`)} must be a boolean.`);return{name:expectString(S.name,field(`executables[${n}].name`)),gui:S.gui}}),nestedBundles:expectArray(t.nestedBundles??[],field(`nestedBundles`)).map((t,n)=>{let S=record(t,field(`nestedBundles[${n}]`));return{name:expectString(S.name,field(`nestedBundles[${n}].name`)),entitlements:expectArray(S.entitlements,field(`nestedBundles[${n}].entitlements`)).map((t,S)=>expectString(t,field(`nestedBundles[${n}].entitlements[${S}]`)))}}),helperExecutables:expectArray(t.helperExecutables??[],field(`helperExecutables`)).map((t,n)=>{let S=record(t,field(`helperExecutables[${n}]`));return{name:expectString(S.name,field(`helperExecutables[${n}].name`)),entitlements:expectArray(S.entitlements,field(`helperExecutables[${n}].entitlements`)).map((t,S)=>expectString(t,field(`helperExecutables[${n}].entitlements[${S}]`)))}}),...t.hasMainExecutable===void 0?{}:(()=>{if(typeof t.hasMainExecutable!=`boolean`)throw Error(`gjsify ship: ${field(`hasMainExecutable`)} must be a boolean.`);return t.hasMainExecutable?{hasMainExecutable:!0}:{}})()}}function readFlatpakSettings(t,n){let field=t=>`${n}.${t}`,strings=(t,n)=>expectArray(t,field(n)).map((t,S)=>expectString(t,field(`${n}[${S}]`)));return{runtime:expectString(t.runtime,field(`runtime`)),runtimeVersion:expectString(t.runtimeVersion,field(`runtimeVersion`)),sdk:expectString(t.sdk,field(`sdk`)),branch:expectString(t.branch,field(`branch`)),sdkExtensions:strings(t.sdkExtensions,`sdkExtensions`),appendPath:strings(t.appendPath,`appendPath`),finishArgs:strings(t.finishArgs,`finishArgs`),cleanup:strings(t.cleanup,`cleanup`)}}function record(t,n){if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`gjsify ship: ${n} must be an object. Re-run the \`--stage\` phase.`);return t}function expectArray(t,n){if(!Array.isArray(t))throw Error(`gjsify ship: ${n} must be an array. Re-run the \`--stage\` phase.`);return t}function expectApp(t,n){if(t===`gjs`||t===`node`)return t;throw Error(`gjsify ship: ${n} must be "gjs" or "node", got ${JSON.stringify(t)}.`)}function expectString(t,n){if(typeof t!=`string`)throw Error(`gjsify ship: ${n} must be a string. Re-run the \`--stage\` phase.`);return t}function expectInteger(t,n){if(typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`gjsify ship: ${n} must be a non-negative integer. Re-run the \`--stage\` phase. (Modes are decimal here — JSON has no octal literal, so 0o755 is written 493.)`);return t}var SW,CW=__esmMin(()=>{af(),Xn(),xW(),Ch(),$W(),oU(),SW=`.gjsify-ship-stage.json`});function writeStage(t,n){for(let t of n)if(t.path===`.gjsify-ship-stage.json`)throw Error(`gjsify ship: a payload file may not be called \`${SW}\` — that name belongs to the stage manifest, which sits at the stage root beside the payload and carries what the packing host needs (ADR 0024 § A2). Rename the \`gjsify.ship.extraFiles\` destination.`);rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let S of n){let n=zn(t,S.path.split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0});let C;switch(S.source.kind){case`text`:C=new TextEncoder().encode(S.source.text);break;case`file`:C=new Uint8Array(readFileSync(S.source.path));break;case`bytes`:C=S.source.data;break;default:{let t=S.source;throw Error(`gjsify ship: no writer for the "${JSON.stringify(t)}" source kind.`)}}writeFileSync(n,C),chmodSync(n,S.mode)}}function readStage(t,n){let S=new Map(n.map(t=>[t.path,t])),C=new Map;for(let n of t)for(let t of listFilesRecursive(n)){if(t===`.gjsify-ship-stage.json`)continue;let N=S.get(t);if(N===void 0)throw Error(`gjsify ship: ${zn(n,t.split(`/`).join(qn))} is in the stage and not in its manifest, so nothing knows what mode to give it. Every payload file takes its mode from the plan, never from the filesystem, so a file that arrived some other way would be packed 0644 — unrunnable if it is a program. Remove it, or add it through \`gjsify.ship.extraFiles\` and re-run the \`--stage\` phase.`);let F=new Uint8Array(readFileSync(zn(n,t.split(`/`).join(qn))));if(N.bytes!==void 0&&N.bytes!==F.byteLength)throw Error(`gjsify ship: ${t} is ${F.byteLength} bytes in the stage and ${N.bytes} in its manifest. The stage arrived truncated or was edited after it was assembled. Re-upload it, or re-run the \`--stage\` phase.`);C.set(t,{path:t,mode:N.mode,data:F})}let N=n.filter(t=>!C.has(t.path)).map(t=>t.path);if(N.length>0)throw Error(`gjsify ship: the stage manifest lists ${N.length} file(s) the stage does not contain: ${N.slice(0,5).join(`, `)}${N.length>5?`, …`:``}. A payload has to be complete before it is packed — both formats would pack the rest without complaint and install a package that cannot start. Re-run the \`--stage\` phase, and check that whatever moved the stage between hosts copied every file (an artifact upload that drops empty files or dotfiles is the usual cause).`);return[...C.values()].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function writePayload(t,n,S){let C=S===``?``:`${S}/`;rmSync(t,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(t,{recursive:!0});for(let N of n){if(!N.path.startsWith(C))throw Error(`gjsify ship: ${N.path} is outside ${S||`the artifact`}, which this artifact IS — so there is nowhere inside it for the file to go. A payload file that escaped the bundle would ship beside it, unsigned and unfound.`);let n=zn(t,N.path.slice(C.length).split(`/`).join(qn));mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,N.data),chmodSync(n,N.mode)}}function directorySize(t){let n=0;for(let S of listFilesRecursive(t))n+=statSync(zn(t,S.split(`/`).join(qn))).size;return n}var wW=__esmMin(()=>{af(),Xn(),zU(),CW()});function isSnapName(t){return t.length<=MW&&jW.test(t)}function assertSnapIsPackable(t,n){let S=[];isSnapName(n.binaryName)||S.push(`the binary name "${n.binaryName}" is not a snap name (lowercase letters, digits and single hyphens, at most ${MW} characters, at least one letter)`),n.version.length>NW&&S.push(`the version "${n.version}" is longer than ${NW} characters`),n.summary.length>PW&&S.push(`the summary is ${n.summary.length} characters, the store takes ${PW}`);for(let t of n.snapPlugs??[])FW.test(t)||S.push(`gjsify.ship.snap.plugs: "${t}" is not an interface name (lowercase letters, digits, hyphens)`);let C=snapDesktopPath(n);if(t.some(t=>t.path===C)||S.push(`the payload has no ${C}, which the snap's \`desktop:\` key must point at`),S.length>0)throw Error(`gjsify ship: cannot pack a snap: ${S.join(`; `)}.`)}function snapDesktopPath(t){return`${_H.applications}/${t.appId}.desktop`}function renderSnapcraftManifest(t){let{settings:n}=t,S={command:`${AW}/bin/${n.binaryName}`,extensions:[`gnome`],desktop:`${AW}/${snapDesktopPath(n)}`,"common-id":n.appId,environment:{GI_TYPELIB_PATH:OW}};n.snapPlugs!==void 0&&n.snapPlugs.length>0&&(S.plugs=[...n.snapPlugs]);let C={name:n.binaryName,title:n.name,base:EW,version:n.version,summary:n.summary,description:n.description.join(`
|
|
1177
1177
|
|
|
1178
|
-
`),license:n.license,grade:`stable`,confinement:`strict`,apps:{[n.binaryName]:S},parts:{[n.binaryName]:{plugin:`dump`,source:kW}}};return n.homepage!==void 0&&(C.website=n.homepage),C}function renderSnapcraftYaml(t){return`${JSON.stringify(renderSnapcraftManifest(t),null,2)}\n`}function snapcraftArgs(t){let n=[`pack`,`--build-for=${t.archLabel}`,`--output`,t.target];return t.destructive&&n.push(`--destructive-mode`),n}function writeSnapProject(t){assertSnapIsPackable(t.payload,t.settings),rmSync(t.workDir,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(zn(t.workDir,`snap`),{recursive:!0}),writePayload(zn(t.workDir,kW),t.payload.map(t=>({...t,path:`${AW}/${t.path}`})),``),writeFileSync(zn(t.workDir,`snap`,`snapcraft.yaml`),encodeUtf8(renderSnapcraftYaml(t)))}async function buildSnap(t){writeSnapProject(t);let n=process.env[DW]===`1`,S=zn(t.workDir,`out.snap`),C=snapcraftArgs({target:S,archLabel:t.archLabel,destructive:n});t.verbose&&ge.log(`[gjsify ship] ${TW} ${C.join(` `)}`);let N=await spawnToCompletion(TW,C,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${TW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(N.code!==0)throw Error(`gjsify ship: ${TW} failed with ${describeExit(N)}.`);if(!existsSync(S))throw Error(`gjsify ship: ${TW} exited 0 but wrote no snap at ${S}.`);renameSync(S,t.target)}var TW,EW,DW,OW,kW,AW,jW,MW,NW,PW,FW=__esmMin(()=>{_e(),af(),Xn(),hv(),rH(),vH(),wW(),TW=`snapcraft`,EW=`core26`,DW=`GJSIFY_SNAP_DESTRUCTIVE`,OW=`$SNAP/gnome-platform/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR/gjs/girepository-1.0`,kW=`payload`,AW=`usr`,jW=/^(?=.*[a-z])[a-z0-9]+(-[a-z0-9]+)*$/,MW=40,NW=32,PW=78});function lookupArch(t,n,S){let C=t[n];if(!C)throw Error(`gjsify ship: no ${S} architecture is known for \`process.arch\` "${n}". Known: ${Object.keys(t).join(`, `)}.`);return C}function debArch(t,n){return n?`all`:lookupArch(
|
|
1178
|
+
`),license:n.license,grade:`stable`,confinement:`strict`,apps:{[n.binaryName]:S},parts:{[n.binaryName]:{plugin:`dump`,source:kW}}};return n.homepage!==void 0&&(C.website=n.homepage),C}function renderSnapcraftYaml(t){return`${JSON.stringify(renderSnapcraftManifest(t),null,2)}\n`}function snapcraftArgs(t){let n=[`pack`,`--build-for=${t.archLabel}`,`--output`,t.target];return t.destructive&&n.push(`--destructive-mode`),n}function writeSnapProject(t){assertSnapIsPackable(t.payload,t.settings),rmSync(t.workDir,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(zn(t.workDir,`snap`),{recursive:!0}),writePayload(zn(t.workDir,kW),t.payload.map(t=>({...t,path:`${AW}/${t.path}`})),``),writeFileSync(zn(t.workDir,`snap`,`snapcraft.yaml`),encodeUtf8(renderSnapcraftYaml(t)))}async function buildSnap(t){writeSnapProject(t);let n=process.env[DW]===`1`,S=zn(t.workDir,`out.snap`),C=snapcraftArgs({target:S,archLabel:t.archLabel,destructive:n});t.verbose&&ge.log(`[gjsify ship] ${TW} ${C.join(` `)}`);let N=await spawnToCompletion(TW,C,{completion:`return`,cwd:t.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${TW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(N.code!==0)throw Error(`gjsify ship: ${TW} failed with ${describeExit(N)}.`);if(!existsSync(S))throw Error(`gjsify ship: ${TW} exited 0 but wrote no snap at ${S}.`);renameSync(S,t.target)}var TW,EW,DW,OW,kW,AW,jW,MW,NW,PW,FW,IW=__esmMin(()=>{_e(),af(),Xn(),hv(),rH(),vH(),wW(),TW=`snapcraft`,EW=`core26`,DW=`GJSIFY_SNAP_DESTRUCTIVE`,OW=`$SNAP/gnome-platform/usr/lib/$CRAFT_ARCH_TRIPLET_BUILD_FOR/gjs/girepository-1.0`,kW=`payload`,AW=`usr`,jW=/^(?=.*[a-z])[a-z0-9]+(-[a-z0-9]+)*$/,MW=40,NW=32,PW=78,FW=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/});function lookupArch(t,n,S){let C=t[n];if(!C)throw Error(`gjsify ship: no ${S} architecture is known for \`process.arch\` "${n}". Known: ${Object.keys(t).join(`, `)}.`);return C}function debArch(t,n){return n?`all`:lookupArch(LW,t,`Debian`)}function rpmArch(t,n){return n?`noarch`:lookupArch(RW,t,`RPM`)}function flatpakArch(t,n){return lookupArch(zW,t,`Flatpak`)}function appImageArch(t,n){return lookupArch(BW,t,`AppImage`)}function snapArch(t,n){return lookupArch(VW,t,`Snap`)}function linuxTarArch(t,n){return lookupArch(HW,t,`Linux tarball`)}function macosArch(t,n){return lookupArch(UW,t,`macOS`)}function windowsArch(t,n){return lookupArch(WW,t,`Windows`)}function windowsNameIsUnusable(t){return GW.test(t)||KW.test(t)||/[. ]$/.test(t)?!0:[...t].some(t=>(t.codePointAt(0)??0)<32)}function windowsProgramDirName(t){let n=t.name;if(n.trim()===``)throw Error("gjsify ship: the windows layout has no name to call the program directory — `gjsify.ship.name` (or the package name it is derived from) is empty. The artifact IS a directory and its zip expands into one, so an empty name would unpack `app\\`, `share\\` and the launcher loose into whatever folder the user was in.");if(windowsNameIsUnusable(n))throw Error(`gjsify ship: the windows layout would put this app in a directory called "${n}", and Windows cannot hold it: it reserves < > : " / \\ | ? * and the control characters, reserves CON, PRN, AUX, NUL, COM1-9 and LPT1-9 as device names at every path, and silently strips a trailing dot or space.
|
|
1179
1179
|
The artifact would assemble here and be unextractable — or extract under a different name than
|
|
1180
|
-
the launcher resolves against. Set \`gjsify.ship.name\` to the display name you want on disk.`);return n}function requiredToolsOn(t,n){return Array.isArray(t)?t:t[n]??[]}function defaultFormatIds(t){return XW.filter(n=>YW[n].layoutOs===t&&YW[n].host.finishOn===`any`)}function formatIdsFor(t){return XW.filter(n=>YW[n].layoutOs===t)}function assertHostCanFinish(t,n=process.platform){let{finishOn:S}=t.host;if(!(S===`any`||S.includes(n)))throw Error(`gjsify ship: a ${t.id} artifact is packed on ${S.join(` or `)} and this host is ${n} (ADR 0024 § A1: a container is produced where its format's tool lives). Assembly is not host-bound, so the way across is the two-phase split: run \`gjsify ship --stage\` here, move \`ship/stage/\` to a ${S.join(`/`)} runner, and finish with \`gjsify ship --from-stage <dir> --target ${t.id}\`.`)}function assertToolsInstalled(t,n=isOnPath,S=process.platform){let C=requiredToolsOn(t.host.requiredTools,S),N=C.filter(t=>!n(t));if(N.length===0)return;let F=t.host.installHint;throw Error(`gjsify ship: packing a ${t.id} on ${S} needs ${C.join(` and `)}, and ${N.join(`, `)} ${N.length>1?`are`:`is`} not on PATH. ${F===void 0?`Install it`:`Install it (${F})`}, or drop this target — the other formats need no tools at all. \`gjsify ship --stage\` also works without ${N.join(`/`)}: the payload is assembled by this CLI and only the container needs them.`)}function parseFormatNames(t,n){let S=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t.length>0),C=S.filter(t=>!Object.hasOwn(YW,t));if(C.length>0)throw Error(`gjsify ship: unknown target${C.length>1?`s`:``} ${C.join(`, `)} in ${n}. Known targets: ${XW.join(`, `)}.`);let N=[...new Set(S)].sort();if(N.length===0)throw Error(`gjsify ship: ${n} named no format. Known targets: ${XW.join(`, `)}.`);return N}function resolveFormats(t,n){let S=parseFormatNames(t,`--target`),C=S.filter(t=>YW[t].layoutOs!==n.os);if(C.length>0){let t=formatIdsFor(n.os),S=[...new Set(C.map(t=>YW[t].layoutOs))];throw Error(`gjsify ship: ${C.join(`, `)} ${C.length>1?`wrap`:`wraps`} the ${S.join(`/`)} layout and this run assembles the ${n.name} one. `+(t.length===0?`No format wraps the ${n.name} layout — \`gjsify ship ${n.name} --stage\` assembles it and stops.`:`Formats for this layout: ${t.join(`, `)}.`)+` To build ${C.join(`, `)}, name the layout each wraps: ${S.map(t=>`\`gjsify ship ${ZW[t]??t} --target ${C.filter(n=>YW[n].layoutOs===t).join(`,`)}\``).join(`, `)}.`)}return S.map(t=>YW[t])}function configuredFormats(t,n){let S=parseFormatNames(t,"`gjsify.ship.targets`");return{formats:S.filter(t=>YW[t].layoutOs===n.os).map(t=>YW[t]),dropped:S.filter(t=>YW[t].layoutOs!==n.os)}}function assertKindCanPack(t,n){if(n===`app`)return;let S=t.filter(t=>t.requiresDesktopEntry);if(S.length!==0)throw Error(`gjsify ship: ${S.map(t=>t.id).join(`, `)} cannot package a \`kind: "cli"\` project — the container needs a desktop entry at its root and a CLI stages none by design. Set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`)}function canCarryTicket(t){switch(t){case`macos-app`:case`macos-app-dmg`:return!0;case`macos-app-zip`:case`deb`:case`rpm`:case`flatpak`:case`appimage`:case`snap`:case`linux-tar`:case`linux-tar-flatpak`:case`windows-dir`:case`windows-dir-zip`:case`msi`:return!1;default:throw Error(`gjsify ship: no ticket answer for format "${String(t)}".`)}}var IW,LW,RW,zW,BW,VW,HW,UW,WW,GW,KW,qW,JW,SHARE_LICENSE_DEST,WRITTEN_HERE,YW,XW,ZW,QW=__esmMin(()=>{dL(),fW(),FW(),_W(),oU(),dU(),IW={x64:`amd64`,arm64:`arm64`,ia32:`i386`,arm:`armhf`,riscv64:`riscv64`,ppc64:`ppc64el`,s390x:`s390x`},LW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armv7hl`,riscv64:`riscv64`,ppc64:`ppc64le`,s390x:`s390x`},RW={x64:`x86_64`,arm64:`aarch64`,ia32:`i386`,arm:`arm`},zW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armhf`},BW={x64:`amd64`,arm64:`arm64`},VW={x64:`x86_64`,arm64:`aarch64`},HW={x64:`x86_64`,arm64:`arm64`},UW={x64:`x64`,arm64:`arm64`},WW=/[<>:"/\\|?*]/,GW=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,KW=`a distro package declares its interpreter as a dependency instead of carrying one, and every distribution ships both`,qW='a `.app` a stranger downloads has to CARRY its interpreter, and there is no relocatable GJS to put in one — `packages/node-gi/scripts/build-gtk-runtime-darwin.mjs` records "GJS ships no relocation", which is why ADR 0024 § 4 derives Node on macOS and stage 7 is what would change it',JW="there is no GJS host on Windows at all (ADR 0024 § 4) — not a system one to depend on and not a relocatable one to carry — so a `--app gjs` payload cannot be shipped this way. That is why § 4 derives Node here, and why `@gjsify/node-runtime-win32-x64` exists",SHARE_LICENSE_DEST=t=>`share/licenses/${t}/LICENSE`,WRITTEN_HERE=t=>({finishOn:`any`,requiredTools:[],oracle:{readWith:t,readOn:[`linux`],selfReading:!1}}),YW={deb:{id:`deb`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`ar`,`tar`,`dpkg-deb`,`lintian`]),depends:`deb`,interpreters:[`gjs`,`node`],interpreterGap:KW,licenseDest:t=>`share/doc/${t}/copyright`,licenseKind:`debian-copyright`,changelogDest:t=>`share/doc/${t}/changelog.Debian.gz`,archName:debArch,fileName:(t,n)=>`${t.binaryName}_${t.version}-${t.release}_${n}.deb`,artifactKind:`file`},rpm:{id:`rpm`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`rpm`,`rpm2cpio`,`cpio`]),depends:`rpm`,interpreters:[`gjs`,`node`],interpreterGap:KW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:rpmArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.rpm`,artifactKind:`file`},flatpak:{id:`flatpak`,layoutOs:`linux`,prefix:`/app`,host:{finishOn:[`linux`],requiredTools:[`flatpak-builder`,`flatpak`],installHint:"Fedora: `sudo dnf install flatpak flatpak-builder`, Debian/Ubuntu: `sudo apt install flatpak flatpak-builder`",oracle:{readWith:[`flatpak`,`ostree`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a Flatpak runs against `org.gnome.Platform`, which ships `gjs` and no `node`. Node exists only as `org.freedesktop.Sdk.Extension.node2x`, and that extension puts node on the BUILD path, not in the runtime — so the artifact would install and then fail at `exec node`",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:flatpakArch,fileName:(t,n)=>`${t.appId}-${t.version}-${t.release}.${n}.flatpak`,artifactKind:`file`},appimage:{id:`appimage`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[iW,cU],installHint:`no distribution packages appimagetool — take the release from https://github.com/AppImage/appimagetool/releases, \`chmod +x\` it and put it on PATH as \`appimagetool\`; or assemble here with \`gjsify ship linux --stage\` and pack where it is. The schema compiler is packaged: ${lU}`,oracle:{readWith:[`python3`,`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:"an AppImage carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in, so the requirement is printed at pack time and checked by `AppRun` at launch instead",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:appImageArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.AppImage`,artifactKind:`file`,requiresDesktopEntry:!0},snap:{id:`snap`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[TW,cU],installHint:`\`sudo snap install ${TW} --classic\` (snapcraft is a snap; ${EW} builds need Ubuntu 26.04 with \`GJSIFY_SNAP_DESTRUCTIVE=1\`, or LXD without it); or assemble here with \`gjsify ship linux --stage\` and pack where snapcraft is. The schema compiler is packaged: ${lU}`,oracle:{readWith:[`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a snap runs against the `gnome-core26` platform snap, which ships `gjs` and no `node`, and the payload bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:snapArch,fileName:(t,n)=>`${t.binaryName}_${t.version}_${n}.snap`,artifactKind:`file`},"linux-tar":{id:`linux-tar`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[],oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:`a tarball carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in`,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}.tar.gz`,artifactKind:`file`},"linux-tar-flatpak":{id:`linux-tar-flatpak`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[cU],installHint:`The schema compiler is packaged: ${lU}`,oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"the archive is meant to run under `org.gnome.Platform`, which ships `gjs` and no `node`, and it bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}-flatpak.tar.gz`,artifactKind:`file`},"macos-app":{id:`macos-app`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`python3`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:qW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:t=>`${t.name}.app`,artifactKind:`directory`},"macos-app-zip":{id:`macos-app-zip`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:qW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.macos.${n}.zip`,artifactKind:`file`},"macos-app-dmg":{id:`macos-app-dmg`,layoutOs:`darwin`,prefix:``,host:{finishOn:[`darwin`],requiredTools:[pW],installHint:"`hdiutil` is part of macOS and cannot be installed elsewhere — on a Mac it is /usr/bin/hdiutil, so an absent one means a broken installation rather than a missing package",oracle:{readWith:[`7z`,`dmg2img`,`fsck.hfsplus`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:qW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.dmg`,artifactKind:`file`},"windows-dir":{id:`windows-dir`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`cmd`,`python3`],readOn:[`linux`,`win32`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:JW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:t=>windowsProgramDirName(t),artifactKind:`directory`},"windows-dir-zip":{id:`windows-dir-zip`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:JW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.windows.${n}.zip`,artifactKind:`file`},msi:{id:`msi`,layoutOs:`win32`,prefix:``,host:{finishOn:[`linux`,`win32`],requiredTools:{linux:[cU,`wixl`],win32:[cU,`candle.exe`,`light.exe`]},installHint:`${lU}; the MSI compiler is Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 (https://github.com/wixtoolset/wix3/releases) with its \`bin\` directory on PATH`,oracle:{readWith:[`msiexec`,`msiinfo`],readOn:[`win32`,`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:JW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.msi`,artifactKind:`file`}},XW=Object.keys(YW),ZW=Object.fromEntries(iU.map(t=>[rU[t].os,t]))});function uuid5(t,n){let S=t.replace(/-/g,``),C=new Uint8Array(16);for(let t=0;t<16;t+=1)C[t]=Number.parseInt(S.slice(t*2,t*2+2),16);let N=createHash(`sha1`).update(C).update(new TextEncoder().encode(n)).digest(),F=Uint8Array.from(N.subarray(0,16));F[6]=(F[6]??0)&15|80,F[8]=(F[8]??0)&63|128;let I=[...F].map(t=>t.toString(16).padStart(2,`0`)).join(``);return[I.slice(0,8),I.slice(8,12),I.slice(12,16),I.slice(16,20),I.slice(20)].join(`-`)}function msiUpgradeCode(t){return uuid5($W,`upgrade\n${t.appId}`).toUpperCase()}function msiProductCode(t,n){let S=`product\n${t.appId}\n${t.version}\n${t.release}\n${n}`;return uuid5($W,S).toUpperCase()}function msiComponentGuid(t,n){return uuid5($W,`component\n${t.appId}\n${n}`).toUpperCase()}function msiProductVersion(t){let n=/^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(t);if(n===null)throw Error(`gjsify ship: "${t}" is not a version an \`.msi\` can carry. Windows Installer's \`ProductVersion\` is \`major.minor.build\` and nothing else — no prerelease suffix, no build metadata.
|
|
1180
|
+
the launcher resolves against. Set \`gjsify.ship.name\` to the display name you want on disk.`);return n}function requiredToolsOn(t,n){return Array.isArray(t)?t:t[n]??[]}function defaultFormatIds(t){return ZW.filter(n=>XW[n].layoutOs===t&&XW[n].host.finishOn===`any`)}function formatIdsFor(t){return ZW.filter(n=>XW[n].layoutOs===t)}function assertHostCanFinish(t,n=process.platform){let{finishOn:S}=t.host;if(!(S===`any`||S.includes(n)))throw Error(`gjsify ship: a ${t.id} artifact is packed on ${S.join(` or `)} and this host is ${n} (ADR 0024 § A1: a container is produced where its format's tool lives). Assembly is not host-bound, so the way across is the two-phase split: run \`gjsify ship --stage\` here, move \`ship/stage/\` to a ${S.join(`/`)} runner, and finish with \`gjsify ship --from-stage <dir> --target ${t.id}\`.`)}function assertToolsInstalled(t,n=isOnPath,S=process.platform){let C=requiredToolsOn(t.host.requiredTools,S),N=C.filter(t=>!n(t));if(N.length===0)return;let F=t.host.installHint;throw Error(`gjsify ship: packing a ${t.id} on ${S} needs ${C.join(` and `)}, and ${N.join(`, `)} ${N.length>1?`are`:`is`} not on PATH. ${F===void 0?`Install it`:`Install it (${F})`}, or drop this target — the other formats need no tools at all. \`gjsify ship --stage\` also works without ${N.join(`/`)}: the payload is assembled by this CLI and only the container needs them.`)}function parseFormatNames(t,n){let S=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t.length>0),C=S.filter(t=>!Object.hasOwn(XW,t));if(C.length>0)throw Error(`gjsify ship: unknown target${C.length>1?`s`:``} ${C.join(`, `)} in ${n}. Known targets: ${ZW.join(`, `)}.`);let N=[...new Set(S)].sort();if(N.length===0)throw Error(`gjsify ship: ${n} named no format. Known targets: ${ZW.join(`, `)}.`);return N}function resolveFormats(t,n){let S=parseFormatNames(t,`--target`),C=S.filter(t=>XW[t].layoutOs!==n.os);if(C.length>0){let t=formatIdsFor(n.os),S=[...new Set(C.map(t=>XW[t].layoutOs))];throw Error(`gjsify ship: ${C.join(`, `)} ${C.length>1?`wrap`:`wraps`} the ${S.join(`/`)} layout and this run assembles the ${n.name} one. `+(t.length===0?`No format wraps the ${n.name} layout — \`gjsify ship ${n.name} --stage\` assembles it and stops.`:`Formats for this layout: ${t.join(`, `)}.`)+` To build ${C.join(`, `)}, name the layout each wraps: ${S.map(t=>`\`gjsify ship ${QW[t]??t} --target ${C.filter(n=>XW[n].layoutOs===t).join(`,`)}\``).join(`, `)}.`)}return S.map(t=>XW[t])}function configuredFormats(t,n){let S=parseFormatNames(t,"`gjsify.ship.targets`");return{formats:S.filter(t=>XW[t].layoutOs===n.os).map(t=>XW[t]),dropped:S.filter(t=>XW[t].layoutOs!==n.os)}}function assertKindCanPack(t,n){if(n===`app`)return;let S=t.filter(t=>t.requiresDesktopEntry);if(S.length!==0)throw Error(`gjsify ship: ${S.map(t=>t.id).join(`, `)} cannot package a \`kind: "cli"\` project — the container needs a desktop entry at its root and a CLI stages none by design. Set \`gjsify.ship.kind\` to "app" if this is a GUI application, or ship it as a \`.deb\`, an \`.rpm\` or a Flatpak, none of which need one.`)}function canCarryTicket(t){switch(t){case`macos-app`:case`macos-app-dmg`:return!0;case`macos-app-zip`:case`deb`:case`rpm`:case`flatpak`:case`appimage`:case`snap`:case`linux-tar`:case`linux-tar-flatpak`:case`windows-dir`:case`windows-dir-zip`:case`msi`:return!1;default:throw Error(`gjsify ship: no ticket answer for format "${String(t)}".`)}}var LW,RW,zW,BW,VW,HW,UW,WW,GW,KW,qW,JW,YW,SHARE_LICENSE_DEST,WRITTEN_HERE,XW,ZW,QW,$W=__esmMin(()=>{dL(),fW(),IW(),_W(),oU(),dU(),LW={x64:`amd64`,arm64:`arm64`,ia32:`i386`,arm:`armhf`,riscv64:`riscv64`,ppc64:`ppc64el`,s390x:`s390x`},RW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armv7hl`,riscv64:`riscv64`,ppc64:`ppc64le`,s390x:`s390x`},zW={x64:`x86_64`,arm64:`aarch64`,ia32:`i386`,arm:`arm`},BW={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armhf`},VW={x64:`amd64`,arm64:`arm64`},HW={x64:`x86_64`,arm64:`aarch64`},UW={x64:`x86_64`,arm64:`arm64`},WW={x64:`x64`,arm64:`arm64`},GW=/[<>:"/\\|?*]/,KW=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,qW=`a distro package declares its interpreter as a dependency instead of carrying one, and every distribution ships both`,JW='a `.app` a stranger downloads has to CARRY its interpreter, and there is no relocatable GJS to put in one — `packages/node-gi/scripts/build-gtk-runtime-darwin.mjs` records "GJS ships no relocation", which is why ADR 0024 § 4 derives Node on macOS and stage 7 is what would change it',YW="there is no GJS host on Windows at all (ADR 0024 § 4) — not a system one to depend on and not a relocatable one to carry — so a `--app gjs` payload cannot be shipped this way. That is why § 4 derives Node here, and why `@gjsify/node-runtime-win32-x64` exists",SHARE_LICENSE_DEST=t=>`share/licenses/${t}/LICENSE`,WRITTEN_HERE=t=>({finishOn:`any`,requiredTools:[],oracle:{readWith:t,readOn:[`linux`],selfReading:!1}}),XW={deb:{id:`deb`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`ar`,`tar`,`dpkg-deb`,`lintian`]),depends:`deb`,interpreters:[`gjs`,`node`],interpreterGap:qW,licenseDest:t=>`share/doc/${t}/copyright`,licenseKind:`debian-copyright`,changelogDest:t=>`share/doc/${t}/changelog.Debian.gz`,archName:debArch,fileName:(t,n)=>`${t.binaryName}_${t.version}-${t.release}_${n}.deb`,artifactKind:`file`},rpm:{id:`rpm`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`rpm`,`rpm2cpio`,`cpio`]),depends:`rpm`,interpreters:[`gjs`,`node`],interpreterGap:qW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:rpmArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.rpm`,artifactKind:`file`},flatpak:{id:`flatpak`,layoutOs:`linux`,prefix:`/app`,host:{finishOn:[`linux`],requiredTools:[`flatpak-builder`,`flatpak`],installHint:"Fedora: `sudo dnf install flatpak flatpak-builder`, Debian/Ubuntu: `sudo apt install flatpak flatpak-builder`",oracle:{readWith:[`flatpak`,`ostree`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a Flatpak runs against `org.gnome.Platform`, which ships `gjs` and no `node`. Node exists only as `org.freedesktop.Sdk.Extension.node2x`, and that extension puts node on the BUILD path, not in the runtime — so the artifact would install and then fail at `exec node`",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:flatpakArch,fileName:(t,n)=>`${t.appId}-${t.version}-${t.release}.${n}.flatpak`,artifactKind:`file`},appimage:{id:`appimage`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[iW,cU],installHint:`no distribution packages appimagetool — take the release from https://github.com/AppImage/appimagetool/releases, \`chmod +x\` it and put it on PATH as \`appimagetool\`; or assemble here with \`gjsify ship linux --stage\` and pack where it is. The schema compiler is packaged: ${lU}`,oracle:{readWith:[`python3`,`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:"an AppImage carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in, so the requirement is printed at pack time and checked by `AppRun` at launch instead",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:appImageArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.AppImage`,artifactKind:`file`,requiresDesktopEntry:!0},snap:{id:`snap`,layoutOs:`linux`,prefix:`/usr`,host:{finishOn:[`linux`],requiredTools:[TW,cU],installHint:`\`sudo snap install ${TW} --classic\` (snapcraft is a snap; ${EW} builds need Ubuntu 26.04 with \`GJSIFY_SNAP_DESTRUCTIVE=1\`, or LXD without it); or assemble here with \`gjsify ship linux --stage\` and pack where snapcraft is. The schema compiler is packaged: ${lU}`,oracle:{readWith:[`unsquashfs`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a snap runs against the `gnome-core26` platform snap, which ships `gjs` and no `node`, and the payload bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:snapArch,fileName:(t,n)=>`${t.binaryName}_${t.version}_${n}.snap`,artifactKind:`file`},"linux-tar":{id:`linux-tar`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[],oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`,`node`],interpreterGap:`a tarball carries the application and takes its interpreter from the host, exactly as a distro package does — but with no dependency field to declare it in`,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}.tar.gz`,artifactKind:`file`},"linux-tar-flatpak":{id:`linux-tar-flatpak`,layoutOs:`linux`,prefix:``,host:{finishOn:[`linux`],requiredTools:[cU],installHint:`The schema compiler is packaged: ${lU}`,oracle:{readWith:[`tar`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"the archive is meant to run under `org.gnome.Platform`, which ships `gjs` and no `node`, and it bundles no interpreter",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:linuxTarArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-linux-${n}-flatpak.tar.gz`,artifactKind:`file`},"macos-app":{id:`macos-app`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`python3`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:JW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:t=>`${t.name}.app`,artifactKind:`directory`},"macos-app-zip":{id:`macos-app-zip`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:JW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.macos.${n}.zip`,artifactKind:`file`},"macos-app-dmg":{id:`macos-app-dmg`,layoutOs:`darwin`,prefix:``,host:{finishOn:[`darwin`],requiredTools:[pW],installHint:"`hdiutil` is part of macOS and cannot be installed elsewhere — on a Mac it is /usr/bin/hdiutil, so an absent one means a broken installation rather than a missing package",oracle:{readWith:[`7z`,`dmg2img`,`fsck.hfsplus`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:JW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.dmg`,artifactKind:`file`},"windows-dir":{id:`windows-dir`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`cmd`,`python3`],readOn:[`linux`,`win32`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:YW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:t=>windowsProgramDirName(t),artifactKind:`directory`},"windows-dir-zip":{id:`windows-dir-zip`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[cU],installHint:lU,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:YW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.windows.${n}.zip`,artifactKind:`file`},msi:{id:`msi`,layoutOs:`win32`,prefix:``,host:{finishOn:[`linux`,`win32`],requiredTools:{linux:[cU,`wixl`],win32:[cU,`candle.exe`,`light.exe`]},installHint:`${lU}; the MSI compiler is Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 (https://github.com/wixtoolset/wix3/releases) with its \`bin\` directory on PATH`,oracle:{readWith:[`msiexec`,`msiinfo`],readOn:[`win32`,`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:YW,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(t,n)=>`${t.binaryName}-${t.version}-${t.release}.${n}.msi`,artifactKind:`file`}},ZW=Object.keys(XW),QW=Object.fromEntries(iU.map(t=>[rU[t].os,t]))});function uuid5(t,n){let S=t.replace(/-/g,``),C=new Uint8Array(16);for(let t=0;t<16;t+=1)C[t]=Number.parseInt(S.slice(t*2,t*2+2),16);let N=createHash(`sha1`).update(C).update(new TextEncoder().encode(n)).digest(),F=Uint8Array.from(N.subarray(0,16));F[6]=(F[6]??0)&15|80,F[8]=(F[8]??0)&63|128;let I=[...F].map(t=>t.toString(16).padStart(2,`0`)).join(``);return[I.slice(0,8),I.slice(8,12),I.slice(12,16),I.slice(16,20),I.slice(20)].join(`-`)}function msiUpgradeCode(t){return uuid5(eG,`upgrade\n${t.appId}`).toUpperCase()}function msiProductCode(t,n){let S=`product\n${t.appId}\n${t.version}\n${t.release}\n${n}`;return uuid5(eG,S).toUpperCase()}function msiComponentGuid(t,n){return uuid5(eG,`component\n${t.appId}\n${n}`).toUpperCase()}function msiProductVersion(t){let n=/^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(t);if(n===null)throw Error(`gjsify ship: "${t}" is not a version an \`.msi\` can carry. Windows Installer's \`ProductVersion\` is \`major.minor.build\` and nothing else — no prerelease suffix, no build metadata.
|
|
1181
1181
|
Dropping the suffix is not an option this command will take silently: \`1.2.0~rc.1\` and \`1.2.0\` would
|
|
1182
1182
|
become the same version, \`MajorUpgrade\` could not tell them apart, and installing one over the other
|
|
1183
1183
|
would leave both on the machine. Set \`gjsify.ship.version\` to a plain \`x.y.z\`, or drop \`msi\` from the targets.`);let[S,C,N]=[Number(n[1]),Number(n[2]),Number(n[3]??`0`)];if(S>255||C>255||N>65535)throw Error(`gjsify ship: version "${t}" is outside what Windows Installer compares — \`major\` and \`minor\` are at most 255 and \`build\` at most 65535. A field over the limit is not rejected by the installer, it is
|
|
1184
|
-
TRUNCATED, so the artifact would carry a version that is not the one it was built from. Set \`gjsify.ship.version\`.`);return`${S}.${C}.${N}`}function msiIdentifier(t,n,S=``){let C=createHash(`sha1`).update(new TextEncoder().encode(n)).digest(`hex`).slice(0,12),N=n.replace(/[^A-Za-z0-9_.]/g,`_`),F=72-t.length-2-C.length-S.length;return`${t}_${N.length>F?N.slice(N.length-F):N}_${C}${S}`}function assertNameIsAddressable(t,n){if(t===`.`||t===`..`||t.length===0||
|
|
1184
|
+
TRUNCATED, so the artifact would carry a version that is not the one it was built from. Set \`gjsify.ship.version\`.`);return`${S}.${C}.${N}`}function msiIdentifier(t,n,S=``){let C=createHash(`sha1`).update(new TextEncoder().encode(n)).digest(`hex`).slice(0,12),N=n.replace(/[^A-Za-z0-9_.]/g,`_`),F=72-t.length-2-C.length-S.length;return`${t}_${N.length>F?N.slice(N.length-F):N}_${C}${S}`}function assertNameIsAddressable(t,n){if(t===`.`||t===`..`||t.length===0||tG.test(t))throw Error(`gjsify ship: the payload holds "${n}", and Windows Installer cannot address the path segment "${t}". A \`FileName\` or \`DefaultDir\` cell reserves < > : " / \\ | ? * and ; (its own list separator), and
|
|
1185
1185
|
\`.\` and \`..\` are not names. The \`.msi\` would build and install the file somewhere else, or not at all.`);if(t.length>255)throw Error(`gjsify ship: the payload holds "${n}", whose segment "${t.slice(0,40)}…" is ${t.length} characters. Windows Installer's \`FileName\` column is 255.`)}function directoryTree(t){let n={path:``,name:``,children:new Map,files:[]};for(let S of[...t].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))){let t=S.path.split(`/`),C=t.pop();if(C===void 0)throw Error(`gjsify ship: the payload holds an empty path.`);let N=n;for(let n of t){assertNameIsAddressable(n,S.path);let t=N.children.get(n)??{path:N.path===``?n:`${N.path}/${n}`,name:n,children:new Map,files:[]};N.children.set(n,t),N=t}assertNameIsAddressable(C,S.path),N.files.push(S)}return n}function renderWxs(t){let{settings:n,programDirName:S,archLabel:C}=t,N=C!==`x86`,F=C===`arm64`?500:200,I=msiProductVersion(n.version),H=n.maintainer.replace(/\s*<[^>]*>\s*$/,``).trim()||n.maintainer,W=windowsGuiLauncherPath(n),q=new Map,claim=(t,n)=>{let S=q.get(t);if(S!==void 0)throw Error(`gjsify ship: the MSI identifier "${t}" would be shared by ${S} and ${n}. Two rows cannot carry one id — one would silently replace the other.`);return q.set(t,n),t},Y=claim(msiIdentifier(`i`,W,`.exe`),`the launcher icon`),X=[],Z=[],te=!1,ne,emitDir=(t,S)=>{for(let C of t.files){let t=claim(msiIdentifier(`c`,C.path),C.path),F=claim(msiIdentifier(`f`,C.path),C.path);Z.push(t);let I=msiComponentGuid(n,C.path),H=xmlEscape(On.basename(C.path));X.push(`${S}<Component Id="${t}" Guid="${I}" Win64="${N?`yes`:`no`}">`),C.path===W?(te=!0,ne=C.source,X.push(`${S} <File Id="${F}" Name="${H}" Source="${xmlEscape(C.source)}" KeyPath="yes">`),X.push(`${S} <Shortcut Id="${claim(`s_startmenu`,`the Start-Menu shortcut`)}" Directory="ProgramMenuFolder" Name="${xmlEscape(n.name)}" WorkingDirectory="INSTALLDIR" Description="${xmlEscape(n.summary)}" Icon="${Y}" IconIndex="0" Advertise="yes" />`),X.push(`${S} </File>`)):X.push(`${S} <File Id="${F}" Name="${H}" Source="${xmlEscape(C.source)}" KeyPath="yes" />`),X.push(`${S}</Component>`)}for(let n of[...t.children.values()].sort((t,n)=>t.name<n.name?-1:1)){let t=claim(msiIdentifier(`d`,n.path),`the directory ${n.path}`);X.push(`${S}<Directory Id="${t}" Name="${xmlEscape(n.name)}">`),emitDir(n,`${S} `),X.push(`${S}</Directory>`)}};if(emitDir(directoryTree(t.files),` `),Z.length===0)throw Error("gjsify ship: the windows payload is empty, so there is nothing for an `.msi` to install.");if(!te||ne===void 0)throw Error(`gjsify ship: the windows payload carries no "${W}" at the root of the program directory, so the installer would have nothing to point a Start-Menu shortcut at — an application a user installs and
|
|
1186
1186
|
cannot start. \`windows-dir\` puts the launcher there; a payload without one is a stage assembled for another layout.`);let re=n.homepage===void 0?[]:[` <Property Id="ARPURLINFOABOUT" Value="${xmlEscape(n.homepage)}" />`];return[`<?xml version="1.0" encoding="utf-8"?>`,"<!-- Generated by `gjsify ship` (ADR 0024 stage 5). Do not edit; edit utils/ship/msi.ts. -->",`<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">`,` <Product Id="${msiProductCode(n,C)}" Name="${xmlEscape(n.name)}" Language="1033" Version="${I}" Manufacturer="${xmlEscape(H)}" UpgradeCode="${msiUpgradeCode(n)}">`,` <Package InstallerVersion="${F}" Compressed="yes" InstallScope="perMachine" Manufacturer="${xmlEscape(H)}" Description="${xmlEscape(n.summary)}" />`,` <MajorUpgrade DowngradeErrorMessage="A newer version of ${xmlEscape(n.name)} is already installed." />`,` <Media Id="1" Cabinet="app.cab" EmbedCab="yes" />`,` <Icon Id="${Y}" SourceFile="${xmlEscape(ne)}" />`,` <Property Id="ARPPRODUCTICON" Value="${Y}" />`,...re,` <Directory Id="TARGETDIR" Name="SourceDir">`,` <Directory Id="ProgramFiles64Folder">`,` <Directory Id="INSTALLDIR" Name="${xmlEscape(S)}">`,...X,` <Component Id="AddToPathComponent" Guid="${msiComponentGuid(n,`:path`)}" Win64="${N?`yes`:`no`}">`,` <CreateFolder />`,` <Environment Id="GjsifyPath" Name="PATH" Action="set" Part="last" System="yes" Permanent="no" Value="[INSTALLDIR]" />`,` </Component>`,` </Directory>`,` </Directory>`,` <Directory Id="ProgramMenuFolder" />`,` </Directory>`,` <Feature Id="Main" Title="${xmlEscape(n.name)}" Level="1">`,...Z.map(t=>` <ComponentRef Id="${t}" />`),` </Feature>`,` <Feature Id="AddToPath" Title="Add ${xmlEscape(n.name)} to PATH" Level="2">`,` <ComponentRef Id="AddToPathComponent" />`,` <Condition Level="1">ADDTOPATH=1</Condition>`,` </Feature>`,` </Product>`,`</Wix>`,``].join(`
|
|
1187
|
-
`)}function msiBackendFor(t){if(t===`linux`)return`wixl`;if(t===`win32`)return`wix3`;throw Error(`gjsify ship: no MSI compiler is wired for ${t}. \`wixl\` (msitools) is used on linux and WiX v3 on win32; assembly is not host-bound, so \`gjsify ship windows --stage\` here and \`gjsify ship --from-stage <dir> --target msi\` there is the way across.`)}async function buildMsi(t){let n=msiBackendFor(t.host??process.platform);mkdirSync(t.workDir,{recursive:!0});let S=zn(t.workDir,`${t.settings.binaryName}.wxs`);if(writeFileSync(S,renderWxs(t)),n===`wixl`)return await run(`wixl`,[`-a`,t.archLabel,`-o`,t.target,S],t),S;let C=zn(t.workDir,`obj`);return rmSync(C,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(C,{recursive:!0}),await run(`candle.exe`,[`-nologo`,`-arch`,t.archLabel,`-out`,`${C}\\`,S],t),await run(`light.exe`,[`-nologo`,`-out`,t.target,zn(C,`${t.settings.binaryName}.wixobj`)],t),S}async function run(t,n,S){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let C=await spawnToCompletion(t,[...n],{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${t} not found. It is the MSI compiler for this host — Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 with its \`bin\` directory on PATH.`)});if(C.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(C)}.`)}var
|
|
1188
|
-
Either ship this target the \`--app ${t.interpreter}\` build of the app — \`gjsify.ship.bundle.${t.layoutOs}\` selects the entry per target, the way \`gjsify.ship.app.${t.layoutOs}\` selects the runtime —\n or set \`gjsify.ship.app.${t.layoutOs}\` to "${C}" if this bundle is the one that should ship.`)}var fG,pG=__esmMin(()=>{fP(),fG=new Set([`system`,`gettext`])});function releaseRecordPath(t){return`${t}${mG}`}function recordedSignature(t,n){return t===void 0?{kind:`none`}:t===n?{kind:`adhoc`}:{kind:`identity`,identity:t}}function buildReleaseRecord(t){let n=readFileSync(t.file);return{schema:1,artifact:Un(t.file),sha256:createHash(`sha256`).update(n).digest(`hex`),size:n.length,format:t.format,os:t.os,arch:t.arch,signature:t.signature,notarized:t.notarized,stapled:t.stapled,nestedBundles:t.nestedBundles,generator:t.generator}}function writeReleaseRecord(t){let n=releaseRecordPath(t.file);return writeFileSync(n,`${JSON.stringify(buildReleaseRecord(t),null,4)}\n`),n}var mG,hG=__esmMin(()=>{gl(),af(),Xn(),mG=`.gjsify-release.json`});function asciiCodesignIdentifier(t){let n=Un(t);if([...n].every(t=>(t.codePointAt(0)??0)<128))return;let S=n.normalize(`NFD`).replace(/\p{M}+/gu,``).replace(/[^A-Za-z0-9.-]+/g,`-`).replace(/^-+|-+$/g,``);return/[A-Za-z0-9]/.test(S)?S:`x-${[...new TextEncoder().encode(n)].map(t=>t.toString(16).padStart(2,`0`)).join(``)}`}function resolveSignPlan(t){let n=gG[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --sign has nothing to sign in the ${t.layoutOs} layout. A .deb and an .rpm carry no per-file signature — the artifact is signed as a whole by the repository that serves it (\`debsigs\`, \`rpmsign\`), with that repository's key and not with a build-time identity. Drop --sign, or assemble the darwin or windows layout.`);return{kind:`unsupported`}}let S=t.config?.[t.layoutOs]?.identity,[C,N]=t.flag===void 0?[S,`config`]:[t.flag,`flag`];return C===void 0||C===``?{kind:`skip`,message:`${C===``?`an empty identity was ${N===`flag`?`passed to --sign`:`set in \`${n.configKey}\``}`:`no identity was given`} — skipping ${n.tool}. An unsigned artifact is the default path and a legitimate deliverable (ADR 0024 § A13). Pass \`--sign <identity>\` or set \`${n.configKey}\` to sign; \`--sign -\` signs ad-hoc and needs no developer identity.`}:{kind:`sign`,identity:C,signer:n,source:N}}function assertHostCanSign(t){let n=process.platform;if(!t.signOn.includes(n))throw Error(`gjsify ship: signing the ${t.layoutOs} layout needs ${t.tool}, which runs on ${t.signOn.join(`, `)} and this host is ${n}. Assembly is not host-bound — \`gjsify ship <os> --stage\` here, then \`gjsify ship --from-stage <dir> --sign <identity>\` on a host that has both the tool and the identity (ADR 0024 § A1, § A14).`);if(!isOnPath(t.tool))throw Error(`gjsify ship: --sign was given and \`${t.tool}\` is not on PATH, so nothing can make the signature — ${t.installHint}. Dropping --sign produces an unsigned artifact, which is a legitimate output (ADR 0024 § A13); silently producing one while --sign was asked for is not.`)}function partitionSignedFileSet(t){let n=new Set(t.planned),S=new Set(t.arrived),C=[...S].filter(t=>!n.has(t)).sort(),N=t.sealPrefixes??[],underAnyPrefix=t=>N.some(n=>t.startsWith(n));return{sealed:N.length===0?[]:C.filter(underAnyPrefix),unexpected:N.length===0?C:C.filter(t=>!underAnyPrefix(t)),removed:[...n].filter(t=>!S.has(t)).sort()}}async function signPayload(t){let{payload:n,signer:S,workDir:C}=t,N=t.nestedBundles??[],F=t.helperExecutables??[];if((N.length>0||F.length>0)&&!S.sealsBundle)throw Error(`gjsify ship: this payload declares a nested bundle or helper executable, and the ${S.layoutOs} signer has no bundle to embed one in — \`signtool\` signs loose images, never a bundle tree. Nested bundles and helper executables are a darwin-only feature.`);writePayload(C,n,``);let I=t.identity===`-`,H=new Map,entitlementsFileFor=(n,S)=>{if(S.length===0)return;let C=H.get(n);if(C!==void 0)return C;let N=n===``?t.entitlementsPath:`${t.entitlementsPath}.${n}.plist`;return mkdirSync(Hn(N),{recursive:!0}),writeFileSync(N,renderEntitlements(S)),H.set(n,N),N},run=async(n,N,F,H)=>{let W=S.args({identity:t.identity,file:n,adhoc:I,seal:F,...H?{entitlements:H}:{}});t.verbose&&t.log(`${S.tool} ${W.join(` `)}`);let q=await spawnToCompletion(S.tool,W,{completion:`return`,cwd:C,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(q.code!==0)throw Error(`gjsify ship: ${S.tool} failed on ${N} with ${describeExit(q)}. Nothing is packed from a payload whose signature failed: an artifact that is half signed installs and is refused at first launch, which is worse than not shipping.`)},W=entitlementsFileFor(``,S.entitlements(I)),q=N.map(t=>`${t.path}/`),Y=new Set(F.map(t=>t.path)),underSubordinate=t=>q.some(n=>t.startsWith(n)),X=[],Z=0;for(let t of N){let N=entitlementsFileFor(t.path,t.entitlements),F=n.filter(n=>n.path.startsWith(`${t.path}/`)&&classifyBinary(n.data)===S.signs);for(let t of F)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,N);Z+=F.length,await run(zn(C,t.path.split(`/`).join(qn)),`${t.path} (nested bundle seal)`,!0,N),X.push(S.sealAddPrefix(t.path))}for(let t of F){let n=entitlementsFileFor(t.path,t.entitlements);await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,n)}let te=n.filter(t=>classifyBinary(t.data)===S.signs&&!underSubordinate(t.path)&&!Y.has(t.path));if(te.length===0&&!S.sealsBundle)return t.log(`nothing in this payload is a ${S.signs===`macho`?`Mach-O`:`PE`} image, so ${S.tool} signed 0 file(s). The artifact carries no signature.`),[...n];for(let t of te)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,W);let ne;if(S.sealsBundle){if(t.bundleRoot===``)throw Error(`gjsify ship: the ${S.layoutOs} signer seals a bundle and this layout has no root to seal. \`Layout.root\` is what names the artifact directory; a signer that sealed the whole stage would sign the payload of every other format beside it.`);ne=S.sealAddPrefix(t.bundleRoot),await run(zn(C,t.bundleRoot.split(`/`).join(qn)),`${t.bundleRoot} (bundle seal)`,!0,W)}let re=[...ne===void 0?[]:[ne],...X],ie=partitionSignedFileSet({arrived:listFilesRecursive(C),planned:n.map(t=>t.path),sealPrefixes:re});if(ie.unexpected.length>0||ie.removed.length>0)throw Error(`gjsify ship: ${S.tool} changed the payload's file set — ${ie.unexpected.length} added (${ie.unexpected.slice(0,3).join(`, `)||`—`}), ${ie.removed.length} removed (${ie.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly each seal's own directory${re.length===0?``:` (${re.map(t=>`\`${t}\``).join(`, `)})`}.`);let ae=ie.sealed;t.log(`${S.tool} signed ${te.length+Z+F.length} of ${n.length} payload file(s) as ${I?"ad-hoc (`-`)":`\`${t.identity}\``}${ne===void 0?``:` and sealed ${t.bundleRoot} (${ae.length} seal file(s))`}${N.length===0?``:`, nested: ${N.map(t=>t.path).join(`, `)}`} — ${S.gap}.`);let read=t=>new Uint8Array(readFileSync(zn(C,t.split(`/`).join(qn))));return[...n.map(t=>({path:t.path,mode:t.mode,data:read(t.path)})),...ae.map(t=>({path:t,mode:420,data:read(t)}))].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function resolveNotaryPlan(t){let n=_G[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --notarize has no meaning in the ${t.layoutOs} layout. Notarisation is Apple's pre-clearance of a signed artifact and nothing else asks for it — Windows SmartScreen accrues reputation per file hash instead (ADR 0024 § A5).`);return{kind:`unsupported`}}if(t.flag===void 0||t.flag===``)return{kind:`skip`,message:`no notarisation credential was given — skipping ${n.tool} notarytool. Pass \`--notarize <keychain-profile>\`, naming a profile a prior \`notarytool store-credentials\` put in this host's keychain.`};if(t.sign.kind!==`sign`)throw Error("gjsify ship: --notarize was given without an identity to sign with. Notarisation is a check ON a signature, so submitting an unsigned artifact has nothing to clear. Pass `--sign <identity>` as well, or drop --notarize.");return{kind:`notarize`,credential:t.flag,notary:n}}async function notarizeArtifact(t){let{notary:n,credential:S}=t.plan,C=process.platform;if(!n.notarizeOn.includes(C))throw Error(`gjsify ship: notarising the ${n.layoutOs} layout needs ${n.tool}, which runs on ${n.notarizeOn.join(`, `)} and this host is ${C}.`);let N=n.args(S,t.artifact);t.verbose&&t.log(`${n.tool} ${N.join(` `)}`);let F=await spawnToCompletion(n.tool,N,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${n.tool}\` is not on PATH — ${n.installHint}.`)});if(F.code!==0)throw Error(`gjsify ship: ${n.tool} notarytool failed with ${describeExit(F)}.`);t.log(`${n.tool} notarytool accepted ${t.artifact}.`)}async function stapleArtifact(t){let n=[`stapler`,`staple`,t.artifact];t.verbose&&t.log(`${t.notary.tool} ${n.join(` `)}`);let S=await spawnToCompletion(t.notary.tool,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${t.notary.tool}\` is not on PATH — ${t.notary.installHint}.`)});if(S.code!==0)throw Error(`gjsify ship: ${t.notary.tool} stapler failed with ${describeExit(S)}. The artifact is notarised and NOT stapled, which means every launch asks Gatekeeper to check online — and fails closed on a machine with no network. Re-run the finish phase; \`stapler\` requires internet access and the ticket may not have propagated yet.`);t.log(`${t.notary.tool} stapler attached the ticket to ${t.artifact}.`)}var gG,_G,vG=__esmMin(()=>{af(),Xn(),dL(),hv(),zU(),xU(),eU(),wW(),gG={darwin:{layoutOs:`darwin`,tool:`codesign`,signOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",signs:`macho`,args:({identity:t,file:n,entitlements:S,adhoc:C,seal:N})=>{let F=N?void 0:asciiCodesignIdentifier(n);return[`--force`,`--sign`,t,`--options`,`runtime`,...S===void 0?[]:[`--entitlements`,S],...C?[]:[`--timestamp`],...F===void 0?[]:[`--identifier`,F],n]},entitlements:t=>[`com.apple.security.cs.allow-jit`,`com.apple.security.cs.allow-unsigned-executable-memory`,`com.apple.security.cs.disable-executable-page-protection`,`com.apple.security.cs.allow-dyld-environment-variables`,...t?[`com.apple.security.cs.disable-library-validation`]:[]],sealsBundle:!0,sealAddPrefix:t=>`${t}/Contents/_CodeSignature/`,configKey:`gjsify.ship.sign.darwin.identity`,gap:"the images are signed and the bundle is sealed, and the seal survives both the `.zip` and the `.dmg` round trip; § A16 stands measured in ONE direction only — library validation refuses an ad-hoc-signed dylib, so the ad-hoc identity grants `disable-library-validation` while a named one does not; a named Developer ID was signed and notarised on 2026-10-30 for an ASCII-named app, and a non-ASCII image name verifies only with the explicit ASCII `--identifier` this signer now passes"},win32:{layoutOs:`win32`,tool:`signtool`,signOn:[`win32`],installHint:"install the Windows SDK (signtool.exe ships in its `bin/<version>/x64` directory)",signs:`pe`,args:({identity:t,file:n})=>[`sign`,`/n`,t,`/fd`,`sha256`,n],entitlements:()=>[],sealsBundle:!1,sealAddPrefix:()=>``,configKey:`gjsify.ship.sign.win32.identity`,gap:`no timestamp countersignature is requested, so the signature expires with the certificate (UNVERIFIED: no run in this repository has ever invoked signtool)`}},_G={darwin:{layoutOs:`darwin`,tool:`xcrun`,notarizeOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",args:(t,n)=>[`notarytool`,`submit`,`--keychain-profile`,t,`--wait`,n]}}});function stagedFontDir(t,n){return`${t}/${On.basename(_H.fonts)}/${n}`}function shellQuote(t){return`'${t.replace(/'/g,`'\\''`)}'`}function cmdQuote(t){let n=/["%!\r\n]/.exec(t);if(n!==null)throw Error(`gjsify ship: \`gjsify.ship.execArgs\` contains ${JSON.stringify(t)}, and cmd.exe has no way to pass ${JSON.stringify(n[0])} through a Windows launcher literally — \`%\` expands at parse time and \`"\` ends the quoted run. Move the value into the app (it can read it from its own config) or drop the character.`);return`"${t}"`}function renderLauncher(t,n,S,C={}){switch(S.name){case`linux`:return renderPrefixLauncher(t,n,S);case`darwin`:return renderAppBundleLauncher(t,n,S,C);case`windows`:return renderWindowsLauncher(t,n,S,C);default:{let t=S.name;throw Error(`gjsify ship: no launcher is wired for the "${String(t)}" layout.`)}}}function renderPrefixLauncher(t,n,S){let C=S.dirs(t),N=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`self=$(readlink -f "$0")`,`prefix=$(dirname "$(dirname "$self")")`,`XDG_DATA_DIRS="$prefix/${C.data}:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"`,`export XDG_DATA_DIRS`];if(t.typelibFiles.length>0){let t=`"$prefix"/${C.native}`;for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(`${n}=${t}\${${n}:+:$${n}}`,`export ${n}`)}else if(Object.values(t.formatFiles).some(t=>t.typelibFiles.length>0)){let t=`"$prefix"/${C.native}`;N.push(`if [ -d ${t} ]; then`);for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(` ${n}=${t}\${${n}:+:$${n}}`,` export ${n}`);N.push(`fi`)}return t.localeFiles.length>0&&N.push(`GJSIFY_LOCALE_DIR="$prefix"/${C.data}/locale`,`export GJSIFY_LOCALE_DIR`),t.fontFiles.length>0&&N.push(`GJSIFY_FONT_DIR="$prefix"/${stagedFontDir(C.data,t.appId)}`,`export GJSIFY_FONT_DIR`),N.push(`exec ${execLine(S,`"$prefix"/${C.bundle}/${n}`,t)} "$@"`,``),N.join(`
|
|
1187
|
+
`)}function msiBackendFor(t){if(t===`linux`)return`wixl`;if(t===`win32`)return`wix3`;throw Error(`gjsify ship: no MSI compiler is wired for ${t}. \`wixl\` (msitools) is used on linux and WiX v3 on win32; assembly is not host-bound, so \`gjsify ship windows --stage\` here and \`gjsify ship --from-stage <dir> --target msi\` there is the way across.`)}async function buildMsi(t){let n=msiBackendFor(t.host??process.platform);mkdirSync(t.workDir,{recursive:!0});let S=zn(t.workDir,`${t.settings.binaryName}.wxs`);if(writeFileSync(S,renderWxs(t)),n===`wixl`)return await run(`wixl`,[`-a`,t.archLabel,`-o`,t.target,S],t),S;let C=zn(t.workDir,`obj`);return rmSync(C,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(C,{recursive:!0}),await run(`candle.exe`,[`-nologo`,`-arch`,t.archLabel,`-out`,`${C}\\`,S],t),await run(`light.exe`,[`-nologo`,`-out`,t.target,zn(C,`${t.settings.binaryName}.wixobj`)],t),S}async function run(t,n,S){S.verbose&&ge.log(`[gjsify ship] ${t} ${n.join(` `)}`);let C=await spawnToCompletion(t,[...n],{completion:`return`,cwd:S.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${t} not found. It is the MSI compiler for this host — Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 with its \`bin\` directory on PATH.`)});if(C.code!==0)throw Error(`gjsify ship: ${t} failed with ${describeExit(C)}.`)}var eG,tG,nG,rG=__esmMin(()=>{_e(),gl(),af(),Xn(),hv(),oU(),CU(),eG=`7b3a1f6e-0c4d-4a2b-9e51-3d8c6f2a0b14`,tG=/[<>:"/\\|?*;]/,nG=`root`});function tarballTopDir(t,n){return`${t.binaryName}-${t.version}-linux-${n}`}function inDeclaredClosure(t,n){return n.some(n=>t.startsWith(`${n}/`)?!t.slice(n.length+1).split(`/`).includes(`node_modules`):!1)}function assertTarballHygiene(t,n){let S=[];for(let C of t){let t=C.path.split(`/`),N=t[t.length-1];N===`.env`||N.startsWith(`.env.`)?S.push(`${C.path} (environment file)`):t.includes(`.git`)?S.push(`${C.path} (version-control data)`):N.endsWith(`.log`)?S.push(`${C.path} (log file)`):t.includes(`node_modules`)&&n.app!==`node`&&!inDeclaredClosure(C.path,n.nodeModulesDirs??[])&&S.push(`${C.path} (node_modules in a non-Node payload)`)}if(S.length!==0)throw Error(`gjsify ship: refusing to pack a tarball that would contain ${S.slice(0,5).join(`, `)}${S.length>5?` and ${S.length-5} more`:``}.`)}async function buildLinuxTarball(t){assertTarballHygiene(t.payload,t.settings);let n=tarballTopDir(t.settings,t.archLabel),S=new Set([`${n}/`]);for(let C of t.payload){let t=On.dirname(C.path),N=t===`.`?[]:t.split(`/`),F=n;for(let t of N)F=`${F}/${t}`,S.add(`${F}/`)}return gzipDeterministic(createTarball([...[...S].sort().map(n=>({name:n,mode:493,mtime:t.mtime,directory:!0})),...t.payload.map(S=>({name:`${n}/${S.path}`,body:S.data,mode:S.mode,mtime:t.mtime}))]))}var iG=__esmMin(()=>{Xn(),oz(),gH()});function getCrcTable(){if(dG!==null)return dG;let t=new Uint32Array(256);for(let n=0;n<256;n++){let S=n;for(let t=0;t<8;t++)S=S&1?3988292384^S>>>1:S>>>1;t[n]=S>>>0}return dG=t,t}function crc32(t){let n=getCrcTable(),S=4294967295;for(let C=0;C<t.length;C++)S=n[(S^t[C])&255]^S>>>8;return(S^4294967295)>>>0}function dosDateTime(t){let n=new Date(Math.max(t,315532800)*1e3);return{date:(n.getUTCFullYear()-1980&127)<<9|n.getUTCMonth()+1<<5|n.getUTCDate(),time:n.getUTCHours()<<11|n.getUTCMinutes()<<5|Math.floor(n.getUTCSeconds()/2)}}function buildZip(t,n){let S=[...t].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path)),{date:C,time:N}=dosDateTime(n),F=new TextEncoder;if(S.length>65535)throw Error(`gjsify ship: this archive would hold ${S.length} entries and a non-ZIP64 central directory records the count in 16 bits, so it would silently wrap. Nothing here writes ZIP64 yet; the payload has to shrink, or this writer has to grow the ZIP64 records.`);let I=new Writer,H=new Writer,W=0;for(let t of S){let n=F.encode(t.path),S=crc32(t.data),q=t.data.byteLength,Y=I.offset;if(Y>4294967295||q>4294967295)throw Error(`gjsify ship: ${t.path} would push this archive past 4 GiB, which a non-ZIP64 header records in 32 bits and therefore truncates. Nothing here writes ZIP64 yet.`);I.u32(aG),I.u16(uG),I.u16(2048),I.u16(cG),I.u16(N),I.u16(C),I.u32(S),I.u32(q),I.u32(q),I.u16(n.byteLength),I.u16(0),I.bytes(n),I.bytes(t.data),H.u32(oG),H.u16(lG),H.u16(uG),H.u16(2048),H.u16(cG),H.u16(N),H.u16(C),H.u32(S),H.u32(q),H.u32(q),H.u16(n.byteLength),H.u16(0),H.u16(0),H.u16(0),H.u16(0),H.u32(((32768|t.mode&4095)>>>0)*65536),H.u32(Y),H.bytes(n),W+=1}let q=H.finish(),Y=new Writer;Y.bytes(I.finish());let X=Y.offset;return Y.bytes(q),Y.u32(sG),Y.u16(0),Y.u16(0),Y.u16(W),Y.u16(W),Y.u32(q.byteLength),Y.u32(X),Y.u16(0),Y.finish()}function zipEntriesFromPayload(t,n=``){let S=n===``?``:`${n}/`;return t.map(t=>({path:`${S}${t.path}`,mode:t.mode,data:t.data}))}var aG,oG,sG,cG,lG,uG,dG,Writer,fG=__esmMin(()=>{aG=67324752,oG=33639248,sG=101010256,cG=0,lG=788,uG=20,dG=null,Writer=class{parts=[];length=0;get offset(){return this.length}u16(t){this.push(new Uint8Array([t&255,t>>>8&255]))}u32(t){this.push(new Uint8Array([t&255,t>>>8&255,t>>>16&255,t>>>24&255]))}bytes(t){this.push(t)}push(t){this.parts.push(t),this.length+=t.byteLength}finish(){let t=new Uint8Array(this.length),n=0;for(let S of this.parts)t.set(S,n),n+=S.byteLength;return t}}});function entryEvidence(t){let n=new Set,S=new Set;return walkModuleAst(t,t=>{let C=importedSpecifier(t);C!==null&&(C.startsWith(`gi://`)||pG.has(C)?n.add(C):C.startsWith(`node:`)&&t.type!==`ImportExpression`&&S.add(C))}),{gi:[...n].sort(),node:[...S].sort()}}function assertEntryRunsUnder(t){let n=entryEvidence(t.source),S=t.interpreter===`node`?n.gi:n.node;if(S.length===0)return;let C=t.interpreter===`node`?`gjs`:`node`,N=t.interpreter===`gjs`?`GJS's loader refuses it: ImportError, "Unsupported URI scheme for importing: node"`:S.some(t=>t.startsWith(`gi://`))?`node's ESM loader refuses it: ERR_UNSUPPORTED_ESM_URL_SCHEME, "Only URLs with a scheme in: file, data, and node are supported by the default ESM loader"`:`node's ESM loader refuses it: ERR_MODULE_NOT_FOUND — a GJS built-in is not a package`,F=S.slice(0,3).join(`, `),I=S.length>3?`, and ${S.length-3} more`:``;throw Error(`gjsify ship: this target execs \`${t.interpreter}\` (\`${t.appKey}\`), and the entry it would ship — ${t.entry} (\`${t.bundleKey}\`) — imports ${F}${I}.\n ${N}, before a line of application code runs.\n The artifact would be built, reported as built, and fail at launch on every machine.
|
|
1188
|
+
Either ship this target the \`--app ${t.interpreter}\` build of the app — \`gjsify.ship.bundle.${t.layoutOs}\` selects the entry per target, the way \`gjsify.ship.app.${t.layoutOs}\` selects the runtime —\n or set \`gjsify.ship.app.${t.layoutOs}\` to "${C}" if this bundle is the one that should ship.`)}var pG,mG=__esmMin(()=>{fP(),pG=new Set([`system`,`gettext`])});function releaseRecordPath(t){return`${t}${hG}`}function recordedSignature(t,n){return t===void 0?{kind:`none`}:t===n?{kind:`adhoc`}:{kind:`identity`,identity:t}}function buildReleaseRecord(t){let n=readFileSync(t.file);return{schema:1,artifact:Un(t.file),sha256:createHash(`sha256`).update(n).digest(`hex`),size:n.length,format:t.format,os:t.os,arch:t.arch,signature:t.signature,notarized:t.notarized,stapled:t.stapled,nestedBundles:t.nestedBundles,generator:t.generator}}function writeReleaseRecord(t){let n=releaseRecordPath(t.file);return writeFileSync(n,`${JSON.stringify(buildReleaseRecord(t),null,4)}\n`),n}var hG,gG=__esmMin(()=>{gl(),af(),Xn(),hG=`.gjsify-release.json`});function asciiCodesignIdentifier(t){let n=Un(t);if([...n].every(t=>(t.codePointAt(0)??0)<128))return;let S=n.normalize(`NFD`).replace(/\p{M}+/gu,``).replace(/[^A-Za-z0-9.-]+/g,`-`).replace(/^-+|-+$/g,``);return/[A-Za-z0-9]/.test(S)?S:`x-${[...new TextEncoder().encode(n)].map(t=>t.toString(16).padStart(2,`0`)).join(``)}`}function resolveSignPlan(t){let n=_G[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --sign has nothing to sign in the ${t.layoutOs} layout. A .deb and an .rpm carry no per-file signature — the artifact is signed as a whole by the repository that serves it (\`debsigs\`, \`rpmsign\`), with that repository's key and not with a build-time identity. Drop --sign, or assemble the darwin or windows layout.`);return{kind:`unsupported`}}let S=t.config?.[t.layoutOs]?.identity,[C,N]=t.flag===void 0?[S,`config`]:[t.flag,`flag`];return C===void 0||C===``?{kind:`skip`,message:`${C===``?`an empty identity was ${N===`flag`?`passed to --sign`:`set in \`${n.configKey}\``}`:`no identity was given`} — skipping ${n.tool}. An unsigned artifact is the default path and a legitimate deliverable (ADR 0024 § A13). Pass \`--sign <identity>\` or set \`${n.configKey}\` to sign; \`--sign -\` signs ad-hoc and needs no developer identity.`}:{kind:`sign`,identity:C,signer:n,source:N}}function assertHostCanSign(t){let n=process.platform;if(!t.signOn.includes(n))throw Error(`gjsify ship: signing the ${t.layoutOs} layout needs ${t.tool}, which runs on ${t.signOn.join(`, `)} and this host is ${n}. Assembly is not host-bound — \`gjsify ship <os> --stage\` here, then \`gjsify ship --from-stage <dir> --sign <identity>\` on a host that has both the tool and the identity (ADR 0024 § A1, § A14).`);if(!isOnPath(t.tool))throw Error(`gjsify ship: --sign was given and \`${t.tool}\` is not on PATH, so nothing can make the signature — ${t.installHint}. Dropping --sign produces an unsigned artifact, which is a legitimate output (ADR 0024 § A13); silently producing one while --sign was asked for is not.`)}function partitionSignedFileSet(t){let n=new Set(t.planned),S=new Set(t.arrived),C=[...S].filter(t=>!n.has(t)).sort(),N=t.sealPrefixes??[],underAnyPrefix=t=>N.some(n=>t.startsWith(n));return{sealed:N.length===0?[]:C.filter(underAnyPrefix),unexpected:N.length===0?C:C.filter(t=>!underAnyPrefix(t)),removed:[...n].filter(t=>!S.has(t)).sort()}}async function signPayload(t){let{payload:n,signer:S,workDir:C}=t,N=t.nestedBundles??[],F=t.helperExecutables??[];if((N.length>0||F.length>0)&&!S.sealsBundle)throw Error(`gjsify ship: this payload declares a nested bundle or helper executable, and the ${S.layoutOs} signer has no bundle to embed one in — \`signtool\` signs loose images, never a bundle tree. Nested bundles and helper executables are a darwin-only feature.`);writePayload(C,n,``);let I=t.identity===`-`,H=new Map,entitlementsFileFor=(n,S)=>{if(S.length===0)return;let C=H.get(n);if(C!==void 0)return C;let N=n===``?t.entitlementsPath:`${t.entitlementsPath}.${n}.plist`;return mkdirSync(Hn(N),{recursive:!0}),writeFileSync(N,renderEntitlements(S)),H.set(n,N),N},run=async(n,N,F,H)=>{let W=S.args({identity:t.identity,file:n,adhoc:I,seal:F,...H?{entitlements:H}:{}});t.verbose&&t.log(`${S.tool} ${W.join(` `)}`);let q=await spawnToCompletion(S.tool,W,{completion:`return`,cwd:C,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(q.code!==0)throw Error(`gjsify ship: ${S.tool} failed on ${N} with ${describeExit(q)}. Nothing is packed from a payload whose signature failed: an artifact that is half signed installs and is refused at first launch, which is worse than not shipping.`)},W=entitlementsFileFor(``,S.entitlements(I)),q=N.map(t=>`${t.path}/`),Y=new Set(F.map(t=>t.path)),underSubordinate=t=>q.some(n=>t.startsWith(n)),X=[],Z=0;for(let t of N){let N=entitlementsFileFor(t.path,t.entitlements),F=n.filter(n=>n.path.startsWith(`${t.path}/`)&&classifyBinary(n.data)===S.signs);for(let t of F)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,N);Z+=F.length,await run(zn(C,t.path.split(`/`).join(qn)),`${t.path} (nested bundle seal)`,!0,N),X.push(S.sealAddPrefix(t.path))}for(let t of F){let n=entitlementsFileFor(t.path,t.entitlements);await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,n)}let te=n.filter(t=>classifyBinary(t.data)===S.signs&&!underSubordinate(t.path)&&!Y.has(t.path));if(te.length===0&&!S.sealsBundle)return t.log(`nothing in this payload is a ${S.signs===`macho`?`Mach-O`:`PE`} image, so ${S.tool} signed 0 file(s). The artifact carries no signature.`),[...n];for(let t of te)await run(zn(C,t.path.split(`/`).join(qn)),t.path,!1,W);let ne;if(S.sealsBundle){if(t.bundleRoot===``)throw Error(`gjsify ship: the ${S.layoutOs} signer seals a bundle and this layout has no root to seal. \`Layout.root\` is what names the artifact directory; a signer that sealed the whole stage would sign the payload of every other format beside it.`);ne=S.sealAddPrefix(t.bundleRoot),await run(zn(C,t.bundleRoot.split(`/`).join(qn)),`${t.bundleRoot} (bundle seal)`,!0,W)}let re=[...ne===void 0?[]:[ne],...X],ie=partitionSignedFileSet({arrived:listFilesRecursive(C),planned:n.map(t=>t.path),sealPrefixes:re});if(ie.unexpected.length>0||ie.removed.length>0)throw Error(`gjsify ship: ${S.tool} changed the payload's file set — ${ie.unexpected.length} added (${ie.unexpected.slice(0,3).join(`, `)||`—`}), ${ie.removed.length} removed (${ie.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly each seal's own directory${re.length===0?``:` (${re.map(t=>`\`${t}\``).join(`, `)})`}.`);let ae=ie.sealed;t.log(`${S.tool} signed ${te.length+Z+F.length} of ${n.length} payload file(s) as ${I?"ad-hoc (`-`)":`\`${t.identity}\``}${ne===void 0?``:` and sealed ${t.bundleRoot} (${ae.length} seal file(s))`}${N.length===0?``:`, nested: ${N.map(t=>t.path).join(`, `)}`} — ${S.gap}.`);let read=t=>new Uint8Array(readFileSync(zn(C,t.split(`/`).join(qn))));return[...n.map(t=>({path:t.path,mode:t.mode,data:read(t.path)})),...ae.map(t=>({path:t,mode:420,data:read(t)}))].sort((t,n)=>t.path<n.path?-1:+(t.path>n.path))}function resolveNotaryPlan(t){let n=vG[t.layoutOs];if(n===void 0){if(t.flag!==void 0)throw Error(`gjsify ship: --notarize has no meaning in the ${t.layoutOs} layout. Notarisation is Apple's pre-clearance of a signed artifact and nothing else asks for it — Windows SmartScreen accrues reputation per file hash instead (ADR 0024 § A5).`);return{kind:`unsupported`}}if(t.flag===void 0||t.flag===``)return{kind:`skip`,message:`no notarisation credential was given — skipping ${n.tool} notarytool. Pass \`--notarize <keychain-profile>\`, naming a profile a prior \`notarytool store-credentials\` put in this host's keychain.`};if(t.sign.kind!==`sign`)throw Error("gjsify ship: --notarize was given without an identity to sign with. Notarisation is a check ON a signature, so submitting an unsigned artifact has nothing to clear. Pass `--sign <identity>` as well, or drop --notarize.");return{kind:`notarize`,credential:t.flag,notary:n}}async function notarizeArtifact(t){let{notary:n,credential:S}=t.plan,C=process.platform;if(!n.notarizeOn.includes(C))throw Error(`gjsify ship: notarising the ${n.layoutOs} layout needs ${n.tool}, which runs on ${n.notarizeOn.join(`, `)} and this host is ${C}.`);let N=n.args(S,t.artifact);t.verbose&&t.log(`${n.tool} ${N.join(` `)}`);let F=await spawnToCompletion(n.tool,N,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${n.tool}\` is not on PATH — ${n.installHint}.`)});if(F.code!==0)throw Error(`gjsify ship: ${n.tool} notarytool failed with ${describeExit(F)}.`);t.log(`${n.tool} notarytool accepted ${t.artifact}.`)}async function stapleArtifact(t){let n=[`stapler`,`staple`,t.artifact];t.verbose&&t.log(`${t.notary.tool} ${n.join(` `)}`);let S=await spawnToCompletion(t.notary.tool,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${t.notary.tool}\` is not on PATH — ${t.notary.installHint}.`)});if(S.code!==0)throw Error(`gjsify ship: ${t.notary.tool} stapler failed with ${describeExit(S)}. The artifact is notarised and NOT stapled, which means every launch asks Gatekeeper to check online — and fails closed on a machine with no network. Re-run the finish phase; \`stapler\` requires internet access and the ticket may not have propagated yet.`);t.log(`${t.notary.tool} stapler attached the ticket to ${t.artifact}.`)}var _G,vG,yG=__esmMin(()=>{af(),Xn(),dL(),hv(),zU(),xU(),eU(),wW(),_G={darwin:{layoutOs:`darwin`,tool:`codesign`,signOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",signs:`macho`,args:({identity:t,file:n,entitlements:S,adhoc:C,seal:N})=>{let F=N?void 0:asciiCodesignIdentifier(n);return[`--force`,`--sign`,t,`--options`,`runtime`,...S===void 0?[]:[`--entitlements`,S],...C?[]:[`--timestamp`],...F===void 0?[]:[`--identifier`,F],n]},entitlements:t=>[`com.apple.security.cs.allow-jit`,`com.apple.security.cs.allow-unsigned-executable-memory`,`com.apple.security.cs.disable-executable-page-protection`,`com.apple.security.cs.allow-dyld-environment-variables`,...t?[`com.apple.security.cs.disable-library-validation`]:[]],sealsBundle:!0,sealAddPrefix:t=>`${t}/Contents/_CodeSignature/`,configKey:`gjsify.ship.sign.darwin.identity`,gap:"the images are signed and the bundle is sealed, and the seal survives both the `.zip` and the `.dmg` round trip; § A16 stands measured in ONE direction only — library validation refuses an ad-hoc-signed dylib, so the ad-hoc identity grants `disable-library-validation` while a named one does not; a named Developer ID was signed and notarised on 2026-10-30 for an ASCII-named app, and a non-ASCII image name verifies only with the explicit ASCII `--identifier` this signer now passes"},win32:{layoutOs:`win32`,tool:`signtool`,signOn:[`win32`],installHint:"install the Windows SDK (signtool.exe ships in its `bin/<version>/x64` directory)",signs:`pe`,args:({identity:t,file:n})=>[`sign`,`/n`,t,`/fd`,`sha256`,n],entitlements:()=>[],sealsBundle:!1,sealAddPrefix:()=>``,configKey:`gjsify.ship.sign.win32.identity`,gap:`no timestamp countersignature is requested, so the signature expires with the certificate (UNVERIFIED: no run in this repository has ever invoked signtool)`}},vG={darwin:{layoutOs:`darwin`,tool:`xcrun`,notarizeOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",args:(t,n)=>[`notarytool`,`submit`,`--keychain-profile`,t,`--wait`,n]}}});function stagedFontDir(t,n){return`${t}/${On.basename(_H.fonts)}/${n}`}function shellQuote(t){return`'${t.replace(/'/g,`'\\''`)}'`}function cmdQuote(t){let n=/["%!\r\n]/.exec(t);if(n!==null)throw Error(`gjsify ship: \`gjsify.ship.execArgs\` contains ${JSON.stringify(t)}, and cmd.exe has no way to pass ${JSON.stringify(n[0])} through a Windows launcher literally — \`%\` expands at parse time and \`"\` ends the quoted run. Move the value into the app (it can read it from its own config) or drop the character.`);return`"${t}"`}function renderLauncher(t,n,S,C={}){switch(S.name){case`linux`:return renderPrefixLauncher(t,n,S);case`darwin`:return renderAppBundleLauncher(t,n,S,C);case`windows`:return renderWindowsLauncher(t,n,S,C);default:{let t=S.name;throw Error(`gjsify ship: no launcher is wired for the "${String(t)}" layout.`)}}}function renderPrefixLauncher(t,n,S){let C=S.dirs(t),N=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`self=$(readlink -f "$0")`,`prefix=$(dirname "$(dirname "$self")")`,`XDG_DATA_DIRS="$prefix/${C.data}:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"`,`export XDG_DATA_DIRS`];if(t.typelibFiles.length>0){let t=`"$prefix"/${C.native}`;for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(`${n}=${t}\${${n}:+:$${n}}`,`export ${n}`)}else if(Object.values(t.formatFiles).some(t=>t.typelibFiles.length>0)){let t=`"$prefix"/${C.native}`;N.push(`if [ -d ${t} ]; then`);for(let n of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])N.push(` ${n}=${t}\${${n}:+:$${n}}`,` export ${n}`);N.push(`fi`)}return t.localeFiles.length>0&&N.push(`GJSIFY_LOCALE_DIR="$prefix"/${C.data}/locale`,`export GJSIFY_LOCALE_DIR`),t.fontFiles.length>0&&N.push(`GJSIFY_FONT_DIR="$prefix"/${stagedFontDir(C.data,t.appId)}`,`export GJSIFY_FONT_DIR`),N.push(`exec ${execLine(S,`"$prefix"/${C.bundle}/${n}`,t)} "$@"`,``),N.join(`
|
|
1189
1189
|
`)}function renderAppBundleLauncher(t,n,S,C){let N=`${S.root(t)}/Contents`,F=S.dirs(t),under=t=>On.relative(N,t),beside=t=>On.relative(F.launcher,t),I=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`here=$(cd -- "$(dirname -- "$0")" && pwd)`,`contents=$(dirname -- "$here")`,`XDG_DATA_DIRS="$contents/${under(F.data)}"\${XDG_DATA_DIRS:+:$XDG_DATA_DIRS}`,`export XDG_DATA_DIRS`];C.gtkRuntimeDir!==void 0&&I.push(`GJSIFY_GTK_RUNTIME="$contents/${under(C.gtkRuntimeDir)}"`,`export GJSIFY_GTK_RUNTIME`),C.nodeGiAddon!==void 0&&I.push(`NODE_GI_NATIVE="$contents/${under(C.nodeGiAddon)}"`,`export NODE_GI_NATIVE`),t.typelibFiles.length>0&&(I.push(`GI_TYPELIB_PATH="$contents/${under(F.native)}"\${GI_TYPELIB_PATH:+:$GI_TYPELIB_PATH}`,`export GI_TYPELIB_PATH`),I.push(`GJSIFY_GI_LIBRARY_PATH="$contents/${under(F.native)}"\${GJSIFY_GI_LIBRARY_PATH:+:$GJSIFY_GI_LIBRARY_PATH}`,`export GJSIFY_GI_LIBRARY_PATH`)),t.localeFiles.length>0&&I.push(`GJSIFY_LOCALE_DIR="$contents/${under(F.data)}/locale"`,`export GJSIFY_LOCALE_DIR`),t.fontFiles.length>0&&I.push(`GJSIFY_FONT_DIR="$contents/${stagedFontDir(under(F.data),t.appId)}"`,`export GJSIFY_FONT_DIR`);let H=C.interpreter===void 0?void 0:`"$here/${beside(C.interpreter)}"`;return I.push(`exec ${execLine(S,`"$contents/${under(F.bundle)}/${n}"`,t,H)} "$@"`,``),I.join(`
|
|
1190
1190
|
`)}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
|
|
1191
|
-
`)}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
|
|
1191
|
+
`)}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 bG=__esmMin(()=>{Xn(),vH()});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=xG+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!==SG)throw Error(`gjsify ship: internal error — cpio header is ${n.length} bytes, expected ${SG}.`);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 xG,SG,CG,wG,TG=__esmMin(()=>{rH(),xG=`070701`,SG=110,CG=32768,wG=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=kG[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,-(DG*H),OG)),F+=DG;let W=new Uint8Array(EG.byteLength+8+H*DG+F),q=new DataView(W.buffer);W.set(EG,0),q.setUint32(8,H),q.setUint32(12,F);let Y=16;W.set(indexEntry(n,7,I,OG),Y),Y+=DG;for(let t of C)W.set(indexEntry(t.tag,t.type,t.offset,t.count),Y),Y+=DG;for(let t of N)W.set(t,Y),Y+=t.byteLength;return W}function indexEntry(t,n,S,C){let N=new Uint8Array(DG),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 EG,DG,OG,kG,AG=__esmMin(()=>{EG=Uint8Array.from([142,173,232,1,0,0,0,0]),DG=16,OG=16,kG={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:CG|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}`,IG.has(S)||C.add(S)}for(let t of C)S.push({path:t,mode:wG|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:jG.HEADERI18NTABLE,type:8,value:[`C`]},{tag:jG.NAME,type:6,value:N.binaryName},{tag:jG.VERSION,type:6,value:N.version},{tag:jG.RELEASE,type:6,value:N.release},{tag:jG.SUMMARY,type:9,value:[N.summary]},{tag:jG.DESCRIPTION,type:9,value:[N.description.join(`
|
|
1192
1192
|
|
|
1193
|
-
`)]},{tag:AG.BUILDTIME,type:4,value:[t.mtime]},{tag:AG.BUILDHOST,type:6,value:`localhost`},{tag:AG.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:AG.LICENSE,type:6,value:N.license},{tag:AG.GROUP,type:9,value:[N.group]},{tag:AG.OS,type:6,value:`linux`},{tag:AG.ARCH,type:6,value:t.archLabel},{tag:AG.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:AG.RPMVERSION,type:6,value:`4.20.0`},{tag:AG.ENCODING,type:6,value:`utf-8`},{tag:AG.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:AG.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:AG.FILERDEVS,type:3,value:n.map(()=>0)},{tag:AG.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:AG.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:AG.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:AG.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:AG.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:AG.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:AG.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:AG.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:AG.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:AG.FILELANGS,type:8,value:n.map(()=>``)},{tag:AG.FILEDIGESTALGO,type:4,value:[NG]},{tag:AG.DIRINDEXES,type:4,value:H},{tag:AG.BASENAMES,type:8,value:W},{tag:AG.DIRNAMES,type:8,value:I},{tag:AG.PROVIDENAME,type:8,value:[N.binaryName]},{tag:AG.PROVIDEFLAGS,type:4,value:[MG.EQUAL]},{tag:AG.PROVIDEVERSION,type:8,value:[F]},{tag:AG.REQUIRENAME,type:8,value:Y.names},{tag:AG.REQUIREFLAGS,type:4,value:Y.flags},{tag:AG.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:AG.RECOMMENDNAME,type:8,value:X.names},{tag:AG.RECOMMENDFLAGS,type:4,value:X.flags},{tag:AG.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:AG.PAYLOADFORMAT,type:6,value:`cpio`},{tag:AG.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:AG.PAYLOADFLAGS,type:6,value:`9`},{tag:AG.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:AG.PAYLOADDIGESTALGO,type:4,value:[NG]},{tag:AG.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:AG.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:AG.POSTIN,type:6,value:q.post}),Z.push({tag:AG.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:AG.POSTUN,type:6,value:q.postun}),Z.push({tag:AG.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([AG.FILESIZES,AG.FILEMODES,AG.FILERDEVS,AG.FILEMTIMES,AG.FILEDIGESTS,AG.FILELINKTOS,AG.FILEFLAGS,AG.FILEUSERNAME,AG.FILEGROUPNAME,AG.FILEVERIFYFLAGS,AG.FILEDEVICES,AG.FILEINODES,AG.FILELANGS,AG.DIRINDEXES,AG.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(MG.INTERP|MG.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(MG.INTERP|MG.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(MG.FIND_REQUIRES),F.push(``);for(let[t,n]of PG)C.push(t),N.push(MG.RPMLIB|MG.LESS|MG.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 MG.GREATER|MG.EQUAL;case`>`:return MG.GREATER;case`<=`:return MG.LESS|MG.EQUAL;case`<`:return MG.LESS;case`=`:return MG.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 AG,jG,MG,NG,PG,FG,IG=__esmMin(()=>{gl(),rH(),wG(),hH(),xU(),kG(),gH(),yH(),vH(),AG={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},jG={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},MG={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},NG=8,PG=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],FG=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${_H.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${_H.metainfo}`,`/usr/share/glib-2.0`,`/usr/${_H.schemas}`,`/usr/${_H.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(`${LG} 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(`${LG} \`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=>YW[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${LG} ${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(`${LG} 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(`${LG} ${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()},ue=resolveHandMetainfo({shipMetainfo:N.metainfo,siteMetainfo:C.site?.metainfo,configReleases:N.releases,projectDir:n});if(ue!==void 0){for(let t of checkHandMetainfo(ue,{appId:ae.appId,kind:ae.kind,version:ae.version}))ge.warn(`${LG} ${t}`);ge.log(`${LG} AppStream metainfo from ${ue.path} (\`${ue.key}\`), staged as written`);for(let t of await lintMetainfo(ue.xml))ge.warn(`${LG} ${formatFinding(t,!1)}`)}if(ue===void 0)for(let t of validateAppMetadata(le))ge.warn(`${LG} ${t.field} is not set — ${t.hint}`);ae.licenseFile!==void 0&&Hn(ae.licenseFile)!==n&&ge.log(`${LG} licence text from ${Bn(n,ae.licenseFile)} (this package carries none of its own)`);let de=ue?.xml,fe=localizeMetadata({metainfo:ae.kind===`app`?renderMetainfoApp$1(le):renderMetainfoCli$1(le),desktopEntry:ae.kind===`app`?renderDesktopEntry(le):void 0},ae.localeFiles),pe=await resolveCarriedRuntime(S,ae,n),me=carryNodeModules(pe,S,ae,n,N.nodeModules,N.nodeModulesExclude);me.length>0&&(ae.nodeModulesDirs=me);let he=stageSubordinates({layout:S,identity:ae,nestedBundles:ae.nestedBundles,helperExecutables:ae.helperExecutables,mainExecutable:ae.mainExecutableSource}),_e={bundleFiles:ie.bundleFiles,launcher:renderLauncher(ae,Un(ae.bundlePath),S,pe.launcher),executableLaunchers:Object.fromEntries(ae.executables.map(t=>[t.name,renderLauncher(ae,t.entry,S,pe.launcher)])),metainfo:de??fe.metainfo,desktopEntry:fe.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},ve=In(n,ae.outDir),ye=zn(ve,`stage`),be=[...planStage(ae,_e),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:ae.schemaFiles,workDir:zn(ve,`schemas`)})],xe=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;xe!==void 0&&ge.log(`${LG} icon: ${iconSizes(xe).join(`/`)} px, ${xe.source}`);let Se=placeStage(S,{...ae,icon:xe,categories:oe.categories},be,[...pe.files,...he.files]);if(writeStage(ye,Se),ge.log(`${LG} staged ${Se.length} file(s) for ${S.name} in ${Bn(n,ye)}/`),t.verbose)for(let t of Se)ge.log(`${LG} ${t.path}`);if(assertPayloadMatchesArch(readStage([ye],Se),ae.arch,{exempt:payloadArchExemptions(S.os,ae)}),S.os!==`linux`){let t=linuxInstallDependent(be);if(t.length>0){ge.warn(`${LG} 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(`${LG} ${n[C]??``}${S} — ${N}`)}for(let t of pe.found)ge.log(`${LG} carries its own ${t}`);for(let t of pe.missing)ge.warn(`${LG} ${t}`);pe.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${LG} ${S.runtimeGap}`),S.fontGap!==void 0&&be.some(t=>isUnder(t.path,_H.fonts))&&ge.warn(`${LG} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(ae.arch)&&ge.warn(`${LG} 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 Ce=scanGiRequirements(se),we=Ce.namespaces,Te=Ce.optional;if(t.verbose){let t=we.filter(t=>!Te.includes(t));ge.log(`${LG} gi namespaces: ${we.join(`, `)||`(none)`}`),Te.length>0&&(ge.log(`${LG} gi optional namespaces: ${Te.join(`, `)}`),ge.log(`${LG} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let Ee=new Map;for(let t of q)Ee.set(t.id,(await planOverlay(ae,t,_e)).map(t=>({...t,path:place(S,ae,t.path)})));let De=readPayloadFacts(be);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:we,optionalNamespaces:Te,hasIcons:De.hasIcons,hasSchemas:De.hasSchemas,interpreter:ae.app,extra:ae.extraDepends[t.depends],typelibPackages:ae.typelibPackages,bundledTypelibs:De.bundledTypelibs,minGjsVersion:ae.minGjsVersion,minNodeVersion:ae.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${LG} 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(`${LG} ${t}`)}let Oe=writeStageManifest({stageDir:ye,settings:ae,formats:q,mtime:ce,namespaces:we,optionalNamespaces:Te,staged:Se,overlay:Ee});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=Oe.formats.join(`, `)||t;ge.log(`${LG} stage manifest: ${formatTarget(Oe.target)}, formats ${n}`);return}let ke=[];for(let n of q)ke.push(await packOne({format:n,settings:ae,arch:ae.arch,staged:Se,overlay:Ee.get(n.id)??[],stageDir:ye,outRoot:ve,namespaces:we,optionalNamespaces:Te,mtime:ce,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,ke)}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(`${LG} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${LG} ${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:zG,frozen:!1,platform:{os:t.os,cpu:n.arch}})).pkgDir,log:t=>ge.log(`${LG} ${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}),H=n.dirs(S).bundle;return t.files.push(...stageNodeModules(I,H)),t.found.push(`node_modules: ${I.packages.length} package(s) for ${N.join(`, `)}`),I.skippedPrebuilds!==void 0&&I.skippedPrebuilds.length>0&&ge.log(`${LG} node_modules: left out, prebuilds for another platform than ${n.os}-${S.arch}: `+I.skippedPrebuilds.join(`, `)),I.excluded.length>0&&ge.log(`${LG} node_modules: left out by gjsify.ship.nodeModulesExclude: ${I.excluded.join(`, `)}`),I.skippedForTarget.length>0&&ge.log(`${LG} node_modules: left out, installed but built for another platform than ${n.os}-${S.arch}: `+I.skippedForTarget.join(`, `)),I.skippedOptional.length>0&&ge.log(`${LG} node_modules: ${I.skippedOptional.length} optional dependenc(ies) not installed, so not carried (other platforms' builds): ${I.skippedOptional.join(`, `)}`),I.packages.map(t=>On.join(H,`node_modules`,t.dest))}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=>YW[t]),F,`stage`,defaultFormatIds(F.os).map(t=>YW[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(`${LG} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${LG} ${t}`);if(ge.log(`${LG} 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(`${LG} ${t.path}`);ge.log(`${LG} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${LG} 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(`${LG} ${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(`${LG} ${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:SW,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(`${LG} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(re);ge.log(`${LG} ${appImageRuntimeNotice(re,H)}`),await buildAppImage({appDir:C,target:oe,archLabel:re,runtimeFile:H,workDir:Hn(C),verbose:t.verbose});break}case`snap`:{let n=await compileSchemasForPayload({payload:ne,workDir:zn(N,`snap-schemas`)});await buildSnap({settings:S,payload:n===void 0?ne:[...ne,n],workDir:zn(N,`snap`),target:oe,archLabel:re,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(`${LG} ${t}`)}),staple:()=>stapleArtifact({notary:C.notary,artifact:N,verbose:t.verbose,log:t=>ge.log(`${LG} ${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,tG),ne,Z.root(S)),await buildMsi({settings:S,files:ne.map(t=>({path:t.path,source:`${tG}/${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(`${LG} ${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(`${LG} ${t}`)}),se=!0,canCarryTicket(n.id)?(await stapleArtifact({notary:t.notarize.notary,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${LG} ${t}`)}),ce=!0):ge.warn(`${LG} ${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(`${LG} release record: ${S}`)}return{format:n.id,path:oe,size:Q}}function printArtifacts(t,n){for(let S of n)ge.log(`${LG} ${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.
|
|
1193
|
+
`)]},{tag:jG.BUILDTIME,type:4,value:[t.mtime]},{tag:jG.BUILDHOST,type:6,value:`localhost`},{tag:jG.SIZE,type:4,value:[n.reduce((t,n)=>t+n.data.byteLength,0)]},{tag:jG.LICENSE,type:6,value:N.license},{tag:jG.GROUP,type:9,value:[N.group]},{tag:jG.OS,type:6,value:`linux`},{tag:jG.ARCH,type:6,value:t.archLabel},{tag:jG.SOURCERPM,type:6,value:`${N.binaryName}-${F}.src.rpm`},{tag:jG.RPMVERSION,type:6,value:`4.20.0`},{tag:jG.ENCODING,type:6,value:`utf-8`},{tag:jG.FILESIZES,type:4,value:n.map(t=>t.data.byteLength)},{tag:jG.FILEMODES,type:3,value:n.map(t=>t.mode)},{tag:jG.FILERDEVS,type:3,value:n.map(()=>0)},{tag:jG.FILEMTIMES,type:4,value:n.map(()=>t.mtime)},{tag:jG.FILEDIGESTS,type:8,value:n.map(t=>t.isDirectory?``:hashHex(`sha256`,t.data))},{tag:jG.FILELINKTOS,type:8,value:n.map(()=>``)},{tag:jG.FILEFLAGS,type:4,value:n.map(()=>0)},{tag:jG.FILEUSERNAME,type:8,value:n.map(()=>`root`)},{tag:jG.FILEGROUPNAME,type:8,value:n.map(()=>`root`)},{tag:jG.FILEVERIFYFLAGS,type:4,value:n.map(()=>4294967295)},{tag:jG.FILEDEVICES,type:4,value:n.map(()=>1)},{tag:jG.FILEINODES,type:4,value:n.map((t,n)=>n+1)},{tag:jG.FILELANGS,type:8,value:n.map(()=>``)},{tag:jG.FILEDIGESTALGO,type:4,value:[PG]},{tag:jG.DIRINDEXES,type:4,value:H},{tag:jG.BASENAMES,type:8,value:W},{tag:jG.DIRNAMES,type:8,value:I},{tag:jG.PROVIDENAME,type:8,value:[N.binaryName]},{tag:jG.PROVIDEFLAGS,type:4,value:[NG.EQUAL]},{tag:jG.PROVIDEVERSION,type:8,value:[F]},{tag:jG.REQUIRENAME,type:8,value:Y.names},{tag:jG.REQUIREFLAGS,type:4,value:Y.flags},{tag:jG.REQUIREVERSION,type:8,value:Y.versions},...X.names.length>0?[{tag:jG.RECOMMENDNAME,type:8,value:X.names},{tag:jG.RECOMMENDFLAGS,type:4,value:X.flags},{tag:jG.RECOMMENDVERSION,type:8,value:X.versions}]:[],{tag:jG.PAYLOADFORMAT,type:6,value:`cpio`},{tag:jG.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:jG.PAYLOADFLAGS,type:6,value:`9`},{tag:jG.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,C)]},{tag:jG.PAYLOADDIGESTALGO,type:4,value:[PG]},{tag:jG.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,S)]}];return assertParallelFileArrays(Z,n.length),N.homepage&&Z.push({tag:jG.URL,type:6,value:N.homepage}),q.post!==void 0&&(Z.push({tag:jG.POSTIN,type:6,value:q.post}),Z.push({tag:jG.POSTINPROG,type:6,value:`/bin/sh`})),q.postun!==void 0&&(Z.push({tag:jG.POSTUN,type:6,value:q.postun}),Z.push({tag:jG.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(t,n){let S=new Set([jG.FILESIZES,jG.FILEMODES,jG.FILERDEVS,jG.FILEMTIMES,jG.FILEDIGESTS,jG.FILELINKTOS,jG.FILEFLAGS,jG.FILEUSERNAME,jG.FILEGROUPNAME,jG.FILEVERIFYFLAGS,jG.FILEDEVICES,jG.FILEINODES,jG.FILELANGS,jG.DIRINDEXES,jG.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(NG.INTERP|NG.SCRIPT_POST),F.push(``)),n.postun!==void 0&&(C.push(`/bin/sh`),N.push(NG.INTERP|NG.SCRIPT_POSTUN),F.push(``));for(let t of S)C.push(t),N.push(NG.FIND_REQUIRES),F.push(``);for(let[t,n]of FG)C.push(t),N.push(NG.RPMLIB|NG.LESS|NG.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 NG.GREATER|NG.EQUAL;case`>`:return NG.GREATER;case`<=`:return NG.LESS|NG.EQUAL;case`<`:return NG.LESS;case`=`:return NG.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 jG,MG,NG,PG,FG,IG,LG=__esmMin(()=>{gl(),rH(),TG(),hH(),xU(),AG(),gH(),yH(),vH(),jG={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},NG={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},PG=8,FG=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],IG=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${_H.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${_H.metainfo}`,`/usr/share/glib-2.0`,`/usr/${_H.schemas}`,`/usr/${_H.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(`${RG} 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(`${RG} \`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=>XW[t]);q=t.filter(t=>t.interpreters.includes(H)),Y=t.filter(t=>!t.interpreters.includes(H)),Y.length>0&&ge.log(`${RG} ${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(`${RG} 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(`${RG} ${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()},ue=resolveHandMetainfo({shipMetainfo:N.metainfo,siteMetainfo:C.site?.metainfo,configReleases:N.releases,projectDir:n});if(ue!==void 0){for(let t of checkHandMetainfo(ue,{appId:ae.appId,kind:ae.kind,version:ae.version}))ge.warn(`${RG} ${t}`);ge.log(`${RG} AppStream metainfo from ${ue.path} (\`${ue.key}\`), staged as written`);for(let t of await lintMetainfo(ue.xml))ge.warn(`${RG} ${formatFinding(t,!1)}`)}if(ue===void 0)for(let t of validateAppMetadata(le))ge.warn(`${RG} ${t.field} is not set — ${t.hint}`);ae.licenseFile!==void 0&&Hn(ae.licenseFile)!==n&&ge.log(`${RG} licence text from ${Bn(n,ae.licenseFile)} (this package carries none of its own)`);let de=ue?.xml,fe=localizeMetadata({metainfo:ae.kind===`app`?renderMetainfoApp$1(le):renderMetainfoCli$1(le),desktopEntry:ae.kind===`app`?renderDesktopEntry(le):void 0},ae.localeFiles),pe=await resolveCarriedRuntime(S,ae,n),me=carryNodeModules(pe,S,ae,n,N.nodeModules,N.nodeModulesExclude);me.length>0&&(ae.nodeModulesDirs=me);let he=stageSubordinates({layout:S,identity:ae,nestedBundles:ae.nestedBundles,helperExecutables:ae.helperExecutables,mainExecutable:ae.mainExecutableSource}),_e={bundleFiles:ie.bundleFiles,launcher:renderLauncher(ae,Un(ae.bundlePath),S,pe.launcher),executableLaunchers:Object.fromEntries(ae.executables.map(t=>[t.name,renderLauncher(ae,t.entry,S,pe.launcher)])),metainfo:de??fe.metainfo,desktopEntry:fe.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},ve=In(n,ae.outDir),ye=zn(ve,`stage`),be=[...planStage(ae,_e),...S.os===`linux`?[]:await compileSchemasForStage({schemaFiles:ae.schemaFiles,workDir:zn(ve,`schemas`)})],xe=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;xe!==void 0&&ge.log(`${RG} icon: ${iconSizes(xe).join(`/`)} px, ${xe.source}`);let Se=placeStage(S,{...ae,icon:xe,categories:oe.categories},be,[...pe.files,...he.files]);if(writeStage(ye,Se),ge.log(`${RG} staged ${Se.length} file(s) for ${S.name} in ${Bn(n,ye)}/`),t.verbose)for(let t of Se)ge.log(`${RG} ${t.path}`);if(assertPayloadMatchesArch(readStage([ye],Se),ae.arch,{exempt:payloadArchExemptions(S.os,ae)}),S.os!==`linux`){let t=linuxInstallDependent(be);if(t.length>0){ge.warn(`${RG} 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(`${RG} ${n[C]??``}${S} — ${N}`)}for(let t of pe.found)ge.log(`${RG} carries its own ${t}`);for(let t of pe.missing)ge.warn(`${RG} ${t}`);pe.launcher.interpreter===void 0&&S.runtimeGap!==void 0&&ge.warn(`${RG} ${S.runtimeGap}`),S.fontGap!==void 0&&be.some(t=>isUnder(t.path,_H.fonts))&&ge.warn(`${RG} ${S.fontGap}`),S.arches!==null&&!S.arches.only.includes(ae.arch)&&ge.warn(`${RG} 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 Ce=scanGiRequirements(se),we=Ce.namespaces,Te=Ce.optional;if(t.verbose){let t=we.filter(t=>!Te.includes(t));ge.log(`${RG} gi namespaces: ${we.join(`, `)||`(none)`}`),Te.length>0&&(ge.log(`${RG} gi optional namespaces: ${Te.join(`, `)}`),ge.log(`${RG} gi required namespaces: ${t.join(`, `)||`(none)`}`))}let Ee=new Map;for(let t of q)Ee.set(t.id,(await planOverlay(ae,t,_e)).map(t=>({...t,path:place(S,ae,t.path)})));let De=readPayloadFacts(be);for(let t of q){if(t.depends===null)continue;let n=deriveDepends(t.depends,{namespaces:we,optionalNamespaces:Te,hasIcons:De.hasIcons,hasSchemas:De.hasSchemas,interpreter:ae.app,extra:ae.extraDepends[t.depends],typelibPackages:ae.typelibPackages,bundledTypelibs:De.bundledTypelibs,minGjsVersion:ae.minGjsVersion,minNodeVersion:ae.minNodeVersion});for(let S of n.unmappedOptional)ge.warn(`${RG} 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(`${RG} ${t}`)}let Oe=writeStageManifest({stageDir:ye,settings:ae,formats:q,mtime:ce,namespaces:we,optionalNamespaces:Te,staged:Se,overlay:Ee});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=Oe.formats.join(`, `)||t;ge.log(`${RG} stage manifest: ${formatTarget(Oe.target)}, formats ${n}`);return}let ke=[];for(let n of q)ke.push(await packOne({format:n,settings:ae,arch:ae.arch,staged:Se,overlay:Ee.get(n.id)??[],stageDir:ye,outRoot:ve,namespaces:we,optionalNamespaces:Te,mtime:ce,sign:X,notarize:Z,verbose:t.verbose}));printArtifacts(n,ke)}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(`${RG} ${t.message}`),n.kind===`skip`&&t.kind===`sign`&&ge.warn(`${RG} ${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:BG,frozen:!1,platform:{os:t.os,cpu:n.arch}})).pkgDir,log:t=>ge.log(`${RG} ${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}),H=n.dirs(S).bundle;return t.files.push(...stageNodeModules(I,H)),t.found.push(`node_modules: ${I.packages.length} package(s) for ${N.join(`, `)}`),I.skippedPrebuilds!==void 0&&I.skippedPrebuilds.length>0&&ge.log(`${RG} node_modules: left out, prebuilds for another platform than ${n.os}-${S.arch}: `+I.skippedPrebuilds.join(`, `)),I.excluded.length>0&&ge.log(`${RG} node_modules: left out by gjsify.ship.nodeModulesExclude: ${I.excluded.join(`, `)}`),I.skippedForTarget.length>0&&ge.log(`${RG} node_modules: left out, installed but built for another platform than ${n.os}-${S.arch}: `+I.skippedForTarget.join(`, `)),I.skippedOptional.length>0&&ge.log(`${RG} node_modules: ${I.skippedOptional.length} optional dependenc(ies) not installed, so not carried (other platforms' builds): ${I.skippedOptional.join(`, `)}`),I.packages.map(t=>On.join(H,`node_modules`,t.dest))}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=>XW[t]),F,`stage`,defaultFormatIds(F.os).map(t=>XW[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(`${RG} ${t}`);let{mtime:q,warnings:Y}=resolveStageMtime(N);for(let t of Y)ge.warn(`${RG} ${t}`);if(ge.log(`${RG} 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(`${RG} ${t.path}`);ge.log(`${RG} gi namespaces: ${N.namespaces.join(`, `)||`(none)`}`),(N.optionalNamespaces??[]).length>0&&ge.log(`${RG} 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(`${RG} ${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(`${RG} ${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:SW,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(`${RG} the AppImage takes these from the host: ${n.join(`, `)}`);let H=findPinnedRuntime(re);ge.log(`${RG} ${appImageRuntimeNotice(re,H)}`),await buildAppImage({appDir:C,target:oe,archLabel:re,runtimeFile:H,workDir:Hn(C),verbose:t.verbose});break}case`snap`:{let n=await compileSchemasForPayload({payload:ne,workDir:zn(N,`snap-schemas`)});await buildSnap({settings:S,payload:n===void 0?ne:[...ne,n],workDir:zn(N,`snap`),target:oe,archLabel:re,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(`${RG} ${t}`)}),staple:()=>stapleArtifact({notary:C.notary,artifact:N,verbose:t.verbose,log:t=>ge.log(`${RG} ${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,nG),ne,Z.root(S)),await buildMsi({settings:S,files:ne.map(t=>({path:t.path,source:`${nG}/${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(`${RG} ${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(`${RG} ${t}`)}),se=!0,canCarryTicket(n.id)?(await stapleArtifact({notary:t.notarize.notary,artifact:oe,verbose:t.verbose,log:t=>ge.log(`${RG} ${t}`)}),ce=!0):ge.warn(`${RG} ${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(`${RG} release record: ${S}`)}return{format:n.id,path:oe,size:Q}}function printArtifacts(t,n){for(let S of n)ge.log(`${RG} ${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.
|
|
1194
1194
|
\`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,
|
|
1195
1195
|
so a configured list naming only another OS's formats leaves this one empty and says so at stage time.
|
|
1196
|
-
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(`${
|
|
1196
|
+
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(`${RG} 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[Oh]=n),S!==void 0&&(C[jh]=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 RG,zG,BG,VG=__esmMin(()=>{_e(),kh(),Mh(),af(),Xn(),_R(),EB(),gV(),KI(),bB(),Ch(),hv(),SU(),hH(),$U(),eW(),nW(),rW(),zU(),fW(),_W(),pV(),vW(),wH(),UV(),yW(),bW(),$W(),oU(),VU(),vH(),dU(),rG(),IW(),iG(),fG(),mG(),fP(),xU(),KU(),gG(),yG(),bG(),LG(),PU(),CW(),wW(),RG=`[gjsify ship]`,zG={command:`ship [os]`,description:`Build installable artifacts (${ZW.join(`, `)}) from the current project.`,builder:t=>t.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${iU.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:[...Eh],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:[...Ah],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)}},BG=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 \`${UG}\` in ${t.dir}. The URL, sha256 and size come from \`<artifact>${hG}\`, which \`gjsify ship --target ${UG}\` 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=WG[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(WG).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
|
|
1197
1197
|
set -eu
|
|
1198
1198
|
|
|
1199
1199
|
extra_root="\${EXTRA_ROOT:-/app/extra}"
|
|
1200
1200
|
cd "$extra_root"
|
|
1201
1201
|
|
|
1202
|
-
[ -f ${
|
|
1202
|
+
[ -f ${HG} ] || { echo "missing extra-data: ${HG}" >&2; exit 1; }
|
|
1203
1203
|
|
|
1204
1204
|
rm -rf stage app
|
|
1205
1205
|
mkdir stage
|
|
1206
|
-
bsdtar --no-same-owner -xf ${
|
|
1206
|
+
bsdtar --no-same-owner -xf ${HG} -C stage
|
|
1207
1207
|
|
|
1208
1208
|
top="$(find stage -mindepth 1 -maxdepth 1 -type d)"
|
|
1209
1209
|
[ "$(printf '%s\\n' "$top" | wc -l)" -eq 1 ] || { echo "expected one top-level directory" >&2; exit 1; }
|
|
1210
1210
|
mv "$top" app
|
|
1211
1211
|
[ -x app/bin/${shellWord(t)} ] || { echo "${shellWord(t)} launcher not found in the tarball" >&2; exit 1; }
|
|
1212
1212
|
|
|
1213
|
-
rm -rf stage ${
|
|
1213
|
+
rm -rf stage ${HG}
|
|
1214
1214
|
`}function renderWrapper(t){return`#!/bin/sh
|
|
1215
1215
|
set -eu
|
|
1216
1216
|
exec /app/extra/app/bin/${shellWord(t)} "$@"
|
|
1217
|
-
`}function shellWord(t){if(!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(t))throw Error(`gjsify flatpark: binary name "${t}" is not a plain file name.`);return t}function yamlString(t){return/^[A-Za-z0-9_./@+=-][A-Za-z0-9_./@+=: -]*$/.test(t)&&!/^(?:true|false|null|yes|no|on|off|~)$/i.test(t)&&!/^[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(t)&&!/: |:$| $|^- /.test(t)&&!/^0[xo]/i.test(t)?t:JSON.stringify(t)}function renderManifest(t){let{appId:n,binaryName:S}=t,C=[`apply_extra.sh`,`${S}-wrapper`,`${n}.desktop`,`${n}.metainfo.xml`,`${n}.png`];return`${[`id: ${yamlString(n)}`,`runtime: ${yamlString(t.flatpak.runtime)}`,`runtime-version: ${JSON.stringify(t.flatpak.runtimeVersion)}`,`sdk: ${yamlString(t.flatpak.sdk)}`,`command: ${yamlString(S)}`,`separate-locales: false`,`build-options:`,` no-debuginfo: true`,`finish-args:`,...t.flatpak.finishArgs.map(t=>` - ${yamlString(t)}`),`modules:`,` - name: ${yamlString(S)}`,` buildsystem: simple`,` build-commands:`,` - install -Dm755 apply_extra.sh /app/bin/apply_extra`,` - install -Dm755 ${S}-wrapper /app/bin/${S}`,` - install -Dm644 ${n}.desktop /app/share/applications/${n}.desktop`,` - install -Dm644 ${n}.metainfo.xml /app/share/metainfo/${n}.metainfo.xml`,` - install -Dm644 ${n}.png /app/share/icons/hicolor/${t.icon.size}x${t.icon.size}/apps/${n}.png`,` sources:`,` # BEGIN MANAGED EXTRA-DATA`,...t.sources.flatMap(t=>[` - type: extra-data`,` filename: ${
|
|
1217
|
+
`}function shellWord(t){if(!/^[A-Za-z0-9][A-Za-z0-9._+-]*$/.test(t))throw Error(`gjsify flatpark: binary name "${t}" is not a plain file name.`);return t}function yamlString(t){return/^[A-Za-z0-9_./@+=-][A-Za-z0-9_./@+=: -]*$/.test(t)&&!/^(?:true|false|null|yes|no|on|off|~)$/i.test(t)&&!/^[-+]?(?:\d[\d_]*(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i.test(t)&&!/: |:$| $|^- /.test(t)&&!/^0[xo]/i.test(t)?t:JSON.stringify(t)}function renderManifest(t){let{appId:n,binaryName:S}=t,C=[`apply_extra.sh`,`${S}-wrapper`,`${n}.desktop`,`${n}.metainfo.xml`,`${n}.png`];return`${[`id: ${yamlString(n)}`,`runtime: ${yamlString(t.flatpak.runtime)}`,`runtime-version: ${JSON.stringify(t.flatpak.runtimeVersion)}`,`sdk: ${yamlString(t.flatpak.sdk)}`,`command: ${yamlString(S)}`,`separate-locales: false`,`build-options:`,` no-debuginfo: true`,`finish-args:`,...t.flatpak.finishArgs.map(t=>` - ${yamlString(t)}`),`modules:`,` - name: ${yamlString(S)}`,` buildsystem: simple`,` build-commands:`,` - install -Dm755 apply_extra.sh /app/bin/apply_extra`,` - install -Dm755 ${S}-wrapper /app/bin/${S}`,` - install -Dm644 ${n}.desktop /app/share/applications/${n}.desktop`,` - install -Dm644 ${n}.metainfo.xml /app/share/metainfo/${n}.metainfo.xml`,` - install -Dm644 ${n}.png /app/share/icons/hicolor/${t.icon.size}x${t.icon.size}/apps/${n}.png`,` sources:`,` # BEGIN MANAGED EXTRA-DATA`,...t.sources.flatMap(t=>[` - type: extra-data`,` filename: ${HG}`,` only-arches:`,` - ${t.arch}`,` url: ${yamlString(t.url)}`,` sha256: ${t.sha256}`,` size: ${t.size}`]),` # END MANAGED EXTRA-DATA`,...C.flatMap(t=>[` - type: file`,` path: ${yamlString(t)}`])].join(`
|
|
1218
1218
|
`)}\n`}function firstCategory(t){return/<category>([^<]+)<\/category>/.exec(t)?.[1]?.trim()??`Utility`}function keywords(t){return[...t.matchAll(/<keyword>([^<]+)<\/keyword>/g)].map(t=>t[1].trim())}function renderDescriptor(t){let n=keywords(t.metainfo);return`${[`id: ${yamlString(t.appId)}`,`name: ${yamlString(t.name)}`,`summary: ${yamlString(t.summary)}`,`website: ${yamlString(t.homepage??`https://github.com/${t.repo}`)}`,`source_url: https://github.com/${t.repo}`,`build:`,` manifest: ${t.appId}.yml`,` branch: stable`,` mode: extra-data`,` arches: [${t.sources.map(t=>t.arch).join(`, `)}]`,`catalog:`,` category: ${yamlString(firstCategory(t.metainfo))}`,` upstream_approved: false`,...n.length===0?[]:[` tags:`,...n.map(t=>` - ${yamlString(t)}`)],`update:`,` command: ./resolve-update.sh`,`policy:`,` proprietary: false`,` dangerous_permissions: []`].join(`
|
|
1219
|
-
`)}\n`}function assetPattern(t,n){let escaped=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),S=t.artifact.indexOf(n);if(S<0)throw Error(`gjsify flatpark: ${t.artifact} does not contain the version ${n}.`);return`^${escaped(t.artifact.slice(0,S))}[0-9][0-9A-Za-z.+~-]*${escaped(t.artifact.slice(S+n.length))}$`}function renderResolveUpdate(t){let n=t.sources.map(n=>({source:n,key:n.arch.replace(/[^a-z0-9]/g,`_`),pattern:assetPattern(n,t.version).replace(/\\/g,`\\\\`)})),S=n.map(({key:t,pattern:n})=>`url_${t}="$(jq -r '.assets[] | select(.name | test("${n}")) | .browser_download_url' <<<"$rel" | head -n1)"\n[ -n "$url_${t}" ] || { echo "no ${t} asset in this release" >&2; exit 1; }`),C=n.map(({source:t,key:n})=>`{filename:"${
|
|
1219
|
+
`)}\n`}function assetPattern(t,n){let escaped=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),S=t.artifact.indexOf(n);if(S<0)throw Error(`gjsify flatpark: ${t.artifact} does not contain the version ${n}.`);return`^${escaped(t.artifact.slice(0,S))}[0-9][0-9A-Za-z.+~-]*${escaped(t.artifact.slice(S+n.length))}$`}function renderResolveUpdate(t){let n=t.sources.map(n=>({source:n,key:n.arch.replace(/[^a-z0-9]/g,`_`),pattern:assetPattern(n,t.version).replace(/\\/g,`\\\\`)})),S=n.map(({key:t,pattern:n})=>`url_${t}="$(jq -r '.assets[] | select(.name | test("${n}")) | .browser_download_url' <<<"$rel" | head -n1)"\n[ -n "$url_${t}" ] || { echo "no ${t} asset in this release" >&2; exit 1; }`),C=n.map(({source:t,key:n})=>`{filename:"${HG}", arch:"${t.arch}", url:$u_${n}}`),N=n.map(({key:t})=>`--arg u_${t} "$url_${t}"`);return`#!/usr/bin/env bash
|
|
1220
1220
|
# Update resolver for ${t.name}, written by \`gjsify flatpark\`.
|
|
1221
1221
|
#
|
|
1222
1222
|
# Prints the latest release on stdout as JSON:
|
|
1223
1223
|
# { "version": "…", "releaseDate": "YYYY-MM-DD",
|
|
1224
|
-
# "sources": [ { "filename": "${
|
|
1224
|
+
# "sources": [ { "filename": "${HG}", "arch": "…", "url": "…" } ] }
|
|
1225
1225
|
# Logs go to stderr. No hashing and no manifest rewriting: FlatPark downloads
|
|
1226
1226
|
# each URL and computes the extra-data sha256 and size itself.
|
|
1227
1227
|
set -euo pipefail
|
|
@@ -1244,8 +1244,8 @@ echo "resolved ${t.name} $version ($date)" >&2
|
|
|
1244
1244
|
|
|
1245
1245
|
jq -n --arg v "$version" --arg d "$date" ${N.join(` `)} \\
|
|
1246
1246
|
'{version:$v, releaseDate:$d, sources:[${C.join(`, `)}]}'
|
|
1247
|
-
`}function withRelease(t,n,S){if(/<releases[\s>]/.test(t))return t;let C=` <releases>\n <release version="${xmlEscape(n)}" date="${S}" />\n </releases>\n`,N=t.lastIndexOf(`</component>`);if(N<0)throw Error(`gjsify flatpark: the staged metainfo has no </component>.`);return`${t.slice(0,N)}${C}${t.slice(N)}`}function renderFlatparkPackage(t){let{appId:n,binaryName:S}=t;if(t.sources.length===0)throw Error(`gjsify flatpark: no sources to pin.`);return[{path:`${n}.yml`,mode:420,data:renderManifest(t)},{path:`apply_extra.sh`,mode:493,data:renderApplyExtra(S)},{path:`${S}-wrapper`,mode:493,data:renderWrapper(S)},{path:`${n}.desktop`,mode:420,data:t.desktopEntry},{path:`${n}.metainfo.xml`,mode:420,data:withRelease(t.metainfo,t.version,t.releaseDate)},{path:`${n}.png`,mode:420,data:t.icon.bytes},{path:`flatpark.yml`,mode:420,data:renderDescriptor(t)},{path:`resolve-update.sh`,mode:493,data:renderResolveUpdate(t)}]}var VG,HG,UG,WG=__esmMin(()=>{af(),Xn(),hG(),CU(),VG=`app.tar.gz`,HG=`linux-tar-flatpak`,UG={x64:`x86_64`,arm64:`aarch64`}});function resolveRepo(t,n){let S=[];t!==void 0&&S.push([`--repo`,t]);let C=n;for(let t=0;t<5;t++){let n=readPackageJson$2(zn(C,`package.json`));if(n!=null){let N=typeof n.repository==`string`?n.repository:n.repository?.url;t===0&&S.push([`${zn(C,`package.json`)} repository`,N]),S.push([`${zn(C,`package.json`)} gjsify.site.repository`,n.gjsify?.site?.repository])}if(Hn(C)===C)break;C=Hn(C)}for(let[t,n]of S){if(n===void 0)continue;let S=parseGithubRepo(n);if(S===void 0)throw Error(`${GG} ${t} is "${n}", which is not a GitHub repository.`);return S}throw Error(`${GG} no GitHub repository to download from. Pass --repo owner/name, or set \`repository\` in package.json or \`gjsify.site.repository\`.`)}function pickIcon(t,n){let S=zn(t,`share`,`icons`,`hicolor`),C=existsSync(S)?readdirSync(S).map(t=>/^(\d+)x\1$/.exec(t)?.[1]).filter(t=>t!==void 0).map(Number).filter(t=>t<=512&&existsSync(zn(S,`${t}x${t}`,`apps`,`${n}.png`))).sort((t,n)=>t-n):[],N=C.includes(128)?128:C[C.length-1];if(N===void 0)throw Error(`${GG} the stage has no PNG icon for ${n} up to 512 px under share/icons/hicolor/. FlatPark takes a PNG or an SVG, and an SVG can fail AppStream compose, so this command wants a raster.`);return{bytes:readFileSync(zn(S,`${N}x${N}`,`apps`,`${n}.png`)),size:N}}var GG,KG,qG=__esmMin(()=>{_e(),af(),Xn(),_R(),KI(),WG(),CW(),GG=`[gjsify flatpark]`,KG={command:`flatpark [project]`,description:"Write the FlatPark package directory (registry/<app-id>/) for a project that ran `gjsify ship`.",builder:t=>t.positional(`project`,{type:`string`,description:`The project directory. Default: the current directory.`}).option(`out`,{type:`string`,demandOption:!0,requiresArg:!0,description:"The package directory to write, e.g. `<flatpark>/registry/eu.example.App`."}).option(`stage`,{type:`string`,requiresArg:!0,description:"A `gjsify ship --stage` directory. Default: `<out dir of ship>/stage` of the project."}).option(`release-dir`,{type:`string`,requiresArg:!0,description:"The directory holding `<artifact>.gjsify-release.json`. Default: `out/` of the ship out dir."}).option(`repo`,{type:`string`,requiresArg:!0,description:"GitHub `owner/name` the releases are published on. Default: read from the project."}).option(`tag-prefix`,{type:`string`,default:`v`,description:`What precedes the version in the release tag.`}),handler:async t=>{let n=In(t.project??process.cwd()),S=In(n,(await new Config().forCommand(n)).ship?.outDir??`ship`),C=In(n,t.stage??zn(S,`stage`)),N=In(n,t[`release-dir`]??zn(S,`out`)),F=In(t.out),I=readStageManifest(C),H=I.settings,staged=t=>{let n=zn(C,t);if(!existsSync(n))throw Error(`${GG} the stage has no ${t}. A FlatPark package needs a desktop application: stage it with \`gjsify ship --stage\` on a project of \`kind: app\`.`);return n},W=resolveRepo(t.repo,n),q=pickIcon(C,H.appId),Y=readFlatparkSources({dir:N,repo:W,version:H.version,tagPrefix:t[`tag-prefix`],stageArch:I.target.arch}),X=renderFlatparkPackage({appId:H.appId,name:H.name,binaryName:H.binaryName,summary:H.summary,version:H.version,...H.homepage===void 0?{}:{homepage:H.homepage},repo:W,flatpak:H.flatpak,sources:Y,desktopEntry:readFileSync(staged(`share/applications/${H.appId}.desktop`),`utf-8`),metainfo:readFileSync(staged(`share/metainfo/${H.appId}.metainfo.xml`),`utf-8`),icon:q,releaseDate:releaseDateOf(I.mtime)});mkdirSync(F,{recursive:!0});for(let t of X)writeFileSync(zn(F,t.path),t.data,{mode:t.mode});ge.log(`${GG} wrote ${X.length} file(s) for ${H.appId} ${H.version} to ${F}`);for(let t of Y)ge.log(`${GG} ${t.arch}: ${t.url}`);ge.log(`${GG} next: ${Bn(process.cwd(),zn(F,`flatpark.yml`))||`flatpark.yml`} has \`upstream_approved: false\`; a row in FlatPark's docs/reference/upstream-approvals.md is the maintainer's.`)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var JG=__esmMin(()=>{P_()});function workspaceLinkTarget(t,n){return YG===`junction`?In(n):Bn(Hn(t),n)}function applyPlatformConfigFromFlags(t){for(let[n,S]of[[`os`,`npm_config_os`],[`cpu`,`npm_config_cpu`],[`libc`,`npm_config_libc`]]){let C=t[n];if(typeof C!=`string`)continue;let N=C.trim();N!==``&&(process.env[S]=N)}t.force&&(process.env.npm_config_force=`true`)}function isAbortedFromOverallTimeout(t){if(!t||typeof t!=`object`)return!1;let n=t.name;if(n===`AbortError`)return!0;let S=t.message;return!!(typeof S==`string`&&S.includes(`install-overall-timeout`)||n===`RegistryTimeoutError`)}function readCliVersionFrom(t){try{if(!existsSync(t))return null;let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===QG&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=Hn(In(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==Hn(t);n++){let n=readCliVersionFrom(zn(t,`package.json`));if(n)return n;t=Hn(t)}}catch{}return null}function readWorkspaceCliVersion(t){let n=readPackageJson$1(zn(t,`package.json`)),S=!1;for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n?.[t]?.[QG];typeof C==`string`&&(S=!0);let N=typeof C==`string`?/^[\^~=v]*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(C.trim()):null;if(N)return N[1]}if(!S){let n=readCliVersionFrom(zn(t,`node_modules`,QG,`package.json`));if(n)return n}return readCliVersionFrom(zn(t,`packages`,`infra`,`cli`,`package.json`))}function warnOnCliVersionSkew(t){if(process.env.GJSIFY_NO_VERSION_SKEW_WARNING===`1`)return;let n=readRunningCliVersion(),S=readWorkspaceCliVersion(t);!n||!S||n===S||ge.warn(`gjsify install: version skew — you are running @gjsify/cli v${n}, but this workspace pins v${S}.\n A mismatched CLI can stall the install (lock discarded → full re-resolve) or silently produce a wrong build.\n Align them: run \`gjsify self-update\` (global CLI) or use the workspace-local \`node_modules/.bin/gjsify\`.\n Suppress this with GJSIFY_NO_VERSION_SKEW_WARNING=1.`)}function isWorkspaceRoot(t){let n=readPackageJson$1(zn(t,`package.json`));return n?n.workspaces!==void 0:!1}function optionalDependencyNames(t){let n=new Set,S=new Set;for(let C of t){let t=new Set(Object.keys(C.optionalDependencies??{}));for(let S of t)n.add(S);for(let n of[`dependencies`,`devDependencies`])for(let N of Object.keys(C[n]??{}))t.has(N)||S.add(N)}for(let t of S)n.delete(t);return n}function depKindFromArgs(t){return t[`save-dev`]?`devDependencies`:t[`save-peer`]?`peerDependencies`:t[`save-optional`]?`optionalDependencies`:`dependencies`}function activateDevLinks(t,n){let S=prepareDevLinks(devLinkRoot(t));if(!S)return null;let C=applyDevLinks(S.links);if(!n)return S;ge.log(`gjsify install: development link ACTIVE (${S.overridePath}) — ${S.links.length} package(s) come from ${S.checkout}, linked rather than fetched (${C.length} (re)written, ${S.links.length-C.length} already current):`);let N=S.links.map(t=>t.name),F=N.slice(0,12);return ge.log(` ${F.join(`, `)}${N.length>F.length?`, +${N.length-F.length} more`:``}`),ge.log(" `gjsify unlink` restores the registry copies; `gjsify install --immutable` refuses while it exists."),S}function reportRewiredDevLinks(t){if(!t)return;let n=applyDevLinks(t.links);n.length!==0&&ge.log(`gjsify install: re-applied ${n.length} development link(s) the install had replaced: ${n.map(t=>t.name).join(`, `)}`)}async function projectInstallNative(t,n){let S=process.cwd(),C=zn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(zn(S,t)));if(N.length>0)throw Error(`gjsify install uses the node_modules linker and cannot run in a Yarn PnP project (found ${N.join(`, `)} in ${S}).\n\n• If this project uses \`gjsify install\` to manage dependencies, these PnP files are stale residue from an earlier \`yarn install\` — remove them and re-run:\n rm -f .pnp.cjs .pnp.loader.mjs && rm -rf .yarn/cache .yarn/unplugged\n gjsify install\n\n• If instead you want Yarn to manage dependencies, set \`nodeLinker: node-modules\` in .yarnrc.yml and run \`yarn install\` (not \`gjsify install\`).`);if(!t.packages||t.packages.length===0){let C=isWorkspaceRoot(S)?S:findWorkspaceRoot(S);if(C){C!==S&&ge.log(`gjsify install: resolved workspace root ${C} (from ${S}); installing the workspace.`),await workspaceInstall(C,t,n);return}}let F,I=readPackageJson$1(C),H=I?projectSpecsFromPackageJson(I):[];if(t.packages&&t.packages.length>0){let n=new Set(t.packages.map(t=>parseSpec$2(t).name));F=[...H.filter(t=>!n.has(parseSpec$2(t).name)),...t.packages]}else{if(!I)throw Error(`gjsify install: no package.json in ${S}`);if(F=H,F.length===0){ge.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(S,{recursive:!0});let W=makeProgressReporter({enabled:!t.verbose&&!t.quiet&&t.progress!==!1}),q=await acquireInstallLock(S,{signal:n});try{let N=activateDevLinks(S,!0),H=await installPackages({prefix:S,specs:F,verbose:t.verbose,lockfile:!t.immutable,frozen:t.immutable,refreshLockfile:t[`refresh-lockfile`],signal:n,progress:W,optionalSpecs:new Set([...optionalDependencyNames(I?[I]:[]),...t[`save-optional`]?(t.packages??[]).map(t=>parseSpec$2(t).name):[]]),linkedNames:N?.names});if(reportRewiredDevLinks(N),t.packages&&t.packages.length>0&&I){let n=depKindFromArgs(t);for(let S of t.packages){let{name:t,range:C}=parseSpec$2(S),N=H.installed.find(n=>n.name===t);addDependencyEntry(I,t,C??(N?defaultRangeFromVersion(N.version):`latest`),n)}writePackageJson(C,I),t.immutable||syncLockfileRequested(S,projectSpecsFromPackageJson(I))}}finally{q.release()}}function syncLockfileRequested(t,n){let S=zn(t,`gjsify-lock.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`)),C=[...n].sort(),N=[...t.requested??[]].sort();if(C.length===N.length&&C.every((t,n)=>t===N[n]))return;t.requested=n,atomicWriteStrict(S,JSON.stringify(t,null,2)+`
|
|
1248
|
-
`)}catch{}}async function workspaceInstall(t,n,S){let C=await acquireInstallLock(t,{signal:S});try{await workspaceInstallLocked(t,n,S)}finally{C.release()}}async function workspaceInstallLocked(t,n,S){let C=discoverWorkspaces(t,{includeRoot:!0});if(C.length===0)throw Error(`gjsify install: ${t} has a "workspaces" field but no workspaces were discovered`);let N=new Map(C.map(t=>[t.name,t])),F=n.focus&&n.focus.length>0?planFocus(C,n.focus,`gjsify install`):void 0,I=F?new Set(F.workspaces):void 0,H=new Set,W=new Map,q=[];for(let t of C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){if(typeof S!=`string`)continue;let C=N.get(n);if(C&&!/^(link|file|portal|git\+|https?):/.test(S)){if(I&&!I.has(t))continue;q.push({fromWorkspaceName:t.name,depName:n,targetLocation:C.location});continue}if(S.startsWith(`workspace:`))throw Error(`gjsify install: ${t.name} declares "${n}: ${S}" but no workspace with that name exists`);if(/^(link|file|portal|git\+|https?):/.test(S))continue;let F=`${n}@${S}`;H.add(F);let Y=W.get(F);Y||(Y=new Set,W.set(F,Y)),Y.add(t.name)}}}ge.log(`gjsify install: ${C.length} workspace(s), ${H.size} external dep spec(s), ${q.length} workspace symlink(s)`);let Y=activateDevLinks(t,!0);writeWorkspaceBinShims(t,F?.workspaces??C);let wireWorkspaceSymlinks=async()=>{if(q.length>0){let t=await Promise.resolve().then(()=>(Vd(),Rd)),n=new Set,S=[];for(let t of q){let C=N.get(t.fromWorkspaceName);if(!C)continue;let F=zn(C.location,`node_modules`,t.depName);n.add(Hn(F));let I=workspaceLinkTarget(F,t.targetLocation);S.push({linkPath:F,relTarget:I})}await Promise.all([...n].map(n=>t.mkdir(n,{recursive:!0})));let C=0,F=[],wireOne=async(n,S)=>{try{await t.rm(n,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}await t.symlink(S,n,
|
|
1247
|
+
`}function withRelease(t,n,S){if(/<releases[\s>]/.test(t))return t;let C=` <releases>\n <release version="${xmlEscape(n)}" date="${S}" />\n </releases>\n`,N=t.lastIndexOf(`</component>`);if(N<0)throw Error(`gjsify flatpark: the staged metainfo has no </component>.`);return`${t.slice(0,N)}${C}${t.slice(N)}`}function renderFlatparkPackage(t){let{appId:n,binaryName:S}=t;if(t.sources.length===0)throw Error(`gjsify flatpark: no sources to pin.`);return[{path:`${n}.yml`,mode:420,data:renderManifest(t)},{path:`apply_extra.sh`,mode:493,data:renderApplyExtra(S)},{path:`${S}-wrapper`,mode:493,data:renderWrapper(S)},{path:`${n}.desktop`,mode:420,data:t.desktopEntry},{path:`${n}.metainfo.xml`,mode:420,data:withRelease(t.metainfo,t.version,t.releaseDate)},{path:`${n}.png`,mode:420,data:t.icon.bytes},{path:`flatpark.yml`,mode:420,data:renderDescriptor(t)},{path:`resolve-update.sh`,mode:493,data:renderResolveUpdate(t)}]}var HG,UG,WG,GG=__esmMin(()=>{af(),Xn(),gG(),CU(),HG=`app.tar.gz`,UG=`linux-tar-flatpak`,WG={x64:`x86_64`,arm64:`aarch64`}});function resolveRepo(t,n){let S=[];t!==void 0&&S.push([`--repo`,t]);let C=n;for(let t=0;t<5;t++){let n=readPackageJson$2(zn(C,`package.json`));if(n!=null){let N=typeof n.repository==`string`?n.repository:n.repository?.url;t===0&&S.push([`${zn(C,`package.json`)} repository`,N]),S.push([`${zn(C,`package.json`)} gjsify.site.repository`,n.gjsify?.site?.repository])}if(Hn(C)===C)break;C=Hn(C)}for(let[t,n]of S){if(n===void 0)continue;let S=parseGithubRepo(n);if(S===void 0)throw Error(`${KG} ${t} is "${n}", which is not a GitHub repository.`);return S}throw Error(`${KG} no GitHub repository to download from. Pass --repo owner/name, or set \`repository\` in package.json or \`gjsify.site.repository\`.`)}function pickIcon(t,n){let S=zn(t,`share`,`icons`,`hicolor`),C=existsSync(S)?readdirSync(S).map(t=>/^(\d+)x\1$/.exec(t)?.[1]).filter(t=>t!==void 0).map(Number).filter(t=>t<=512&&existsSync(zn(S,`${t}x${t}`,`apps`,`${n}.png`))).sort((t,n)=>t-n):[],N=C.includes(128)?128:C[C.length-1];if(N===void 0)throw Error(`${KG} the stage has no PNG icon for ${n} up to 512 px under share/icons/hicolor/. FlatPark takes a PNG or an SVG, and an SVG can fail AppStream compose, so this command wants a raster.`);return{bytes:readFileSync(zn(S,`${N}x${N}`,`apps`,`${n}.png`)),size:N}}var KG,qG,JG=__esmMin(()=>{_e(),af(),Xn(),_R(),KI(),GG(),CW(),KG=`[gjsify flatpark]`,qG={command:`flatpark [project]`,description:"Write the FlatPark package directory (registry/<app-id>/) for a project that ran `gjsify ship`.",builder:t=>t.positional(`project`,{type:`string`,description:`The project directory. Default: the current directory.`}).option(`out`,{type:`string`,demandOption:!0,requiresArg:!0,description:"The package directory to write, e.g. `<flatpark>/registry/eu.example.App`."}).option(`stage`,{type:`string`,requiresArg:!0,description:"A `gjsify ship --stage` directory. Default: `<out dir of ship>/stage` of the project."}).option(`release-dir`,{type:`string`,requiresArg:!0,description:"The directory holding `<artifact>.gjsify-release.json`. Default: `out/` of the ship out dir."}).option(`repo`,{type:`string`,requiresArg:!0,description:"GitHub `owner/name` the releases are published on. Default: read from the project."}).option(`tag-prefix`,{type:`string`,default:`v`,description:`What precedes the version in the release tag.`}),handler:async t=>{let n=In(t.project??process.cwd()),S=In(n,(await new Config().forCommand(n)).ship?.outDir??`ship`),C=In(n,t.stage??zn(S,`stage`)),N=In(n,t[`release-dir`]??zn(S,`out`)),F=In(t.out),I=readStageManifest(C),H=I.settings,staged=t=>{let n=zn(C,t);if(!existsSync(n))throw Error(`${KG} the stage has no ${t}. A FlatPark package needs a desktop application: stage it with \`gjsify ship --stage\` on a project of \`kind: app\`.`);return n},W=resolveRepo(t.repo,n),q=pickIcon(C,H.appId),Y=readFlatparkSources({dir:N,repo:W,version:H.version,tagPrefix:t[`tag-prefix`],stageArch:I.target.arch}),X=renderFlatparkPackage({appId:H.appId,name:H.name,binaryName:H.binaryName,summary:H.summary,version:H.version,...H.homepage===void 0?{}:{homepage:H.homepage},repo:W,flatpak:H.flatpak,sources:Y,desktopEntry:readFileSync(staged(`share/applications/${H.appId}.desktop`),`utf-8`),metainfo:readFileSync(staged(`share/metainfo/${H.appId}.metainfo.xml`),`utf-8`),icon:q,releaseDate:releaseDateOf(I.mtime)});mkdirSync(F,{recursive:!0});for(let t of X)writeFileSync(zn(F,t.path),t.data,{mode:t.mode});ge.log(`${KG} wrote ${X.length} file(s) for ${H.appId} ${H.version} to ${F}`);for(let t of Y)ge.log(`${KG} ${t.arch}: ${t.url}`);ge.log(`${KG} next: ${Bn(process.cwd(),zn(F,`flatpark.yml`))||`flatpark.yml`} has \`upstream_approved: false\`; a row in FlatPark's docs/reference/upstream-approvals.md is the maintainer's.`)}}});function forceExit(t){if(process.exitCode=t,!gjsExit(t))return process.exit(t)}var YG=__esmMin(()=>{P_()});function workspaceLinkTarget(t,n){return XG===`junction`?In(n):Bn(Hn(t),n)}function applyPlatformConfigFromFlags(t){for(let[n,S]of[[`os`,`npm_config_os`],[`cpu`,`npm_config_cpu`],[`libc`,`npm_config_libc`]]){let C=t[n];if(typeof C!=`string`)continue;let N=C.trim();N!==``&&(process.env[S]=N)}t.force&&(process.env.npm_config_force=`true`)}function isAbortedFromOverallTimeout(t){if(!t||typeof t!=`object`)return!1;let n=t.name;if(n===`AbortError`)return!0;let S=t.message;return!!(typeof S==`string`&&S.includes(`install-overall-timeout`)||n===`RegistryTimeoutError`)}function readCliVersionFrom(t){try{if(!existsSync(t))return null;let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===$G&&typeof n.version==`string`)return n.version}catch{}return null}function readRunningCliVersion(){try{let t=Hn(In(fileURLToPath(import.meta.url)));for(let n=0;n<8&&t!==Hn(t);n++){let n=readCliVersionFrom(zn(t,`package.json`));if(n)return n;t=Hn(t)}}catch{}return null}function readWorkspaceCliVersion(t){let n=readPackageJson$1(zn(t,`package.json`)),S=!1;for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n?.[t]?.[$G];typeof C==`string`&&(S=!0);let N=typeof C==`string`?/^[\^~=v]*(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(C.trim()):null;if(N)return N[1]}if(!S){let n=readCliVersionFrom(zn(t,`node_modules`,$G,`package.json`));if(n)return n}return readCliVersionFrom(zn(t,`packages`,`infra`,`cli`,`package.json`))}function warnOnCliVersionSkew(t){if(process.env.GJSIFY_NO_VERSION_SKEW_WARNING===`1`)return;let n=readRunningCliVersion(),S=readWorkspaceCliVersion(t);!n||!S||n===S||ge.warn(`gjsify install: version skew — you are running @gjsify/cli v${n}, but this workspace pins v${S}.\n A mismatched CLI can stall the install (lock discarded → full re-resolve) or silently produce a wrong build.\n Align them: run \`gjsify self-update\` (global CLI) or use the workspace-local \`node_modules/.bin/gjsify\`.\n Suppress this with GJSIFY_NO_VERSION_SKEW_WARNING=1.`)}function isWorkspaceRoot(t){let n=readPackageJson$1(zn(t,`package.json`));return n?n.workspaces!==void 0:!1}function optionalDependencyNames(t){let n=new Set,S=new Set;for(let C of t){let t=new Set(Object.keys(C.optionalDependencies??{}));for(let S of t)n.add(S);for(let n of[`dependencies`,`devDependencies`])for(let N of Object.keys(C[n]??{}))t.has(N)||S.add(N)}for(let t of S)n.delete(t);return n}function depKindFromArgs(t){return t[`save-dev`]?`devDependencies`:t[`save-peer`]?`peerDependencies`:t[`save-optional`]?`optionalDependencies`:`dependencies`}function activateDevLinks(t,n){let S=prepareDevLinks(devLinkRoot(t));if(!S)return null;let C=applyDevLinks(S.links);if(!n)return S;ge.log(`gjsify install: development link ACTIVE (${S.overridePath}) — ${S.links.length} package(s) come from ${S.checkout}, linked rather than fetched (${C.length} (re)written, ${S.links.length-C.length} already current):`);let N=S.links.map(t=>t.name),F=N.slice(0,12);return ge.log(` ${F.join(`, `)}${N.length>F.length?`, +${N.length-F.length} more`:``}`),ge.log(" `gjsify unlink` restores the registry copies; `gjsify install --immutable` refuses while it exists."),S}function reportRewiredDevLinks(t){if(!t)return;let n=applyDevLinks(t.links);n.length!==0&&ge.log(`gjsify install: re-applied ${n.length} development link(s) the install had replaced: ${n.map(t=>t.name).join(`, `)}`)}async function projectInstallNative(t,n){let S=process.cwd(),C=zn(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(t=>existsSync(zn(S,t)));if(N.length>0)throw Error(`gjsify install uses the node_modules linker and cannot run in a Yarn PnP project (found ${N.join(`, `)} in ${S}).\n\n• If this project uses \`gjsify install\` to manage dependencies, these PnP files are stale residue from an earlier \`yarn install\` — remove them and re-run:\n rm -f .pnp.cjs .pnp.loader.mjs && rm -rf .yarn/cache .yarn/unplugged\n gjsify install\n\n• If instead you want Yarn to manage dependencies, set \`nodeLinker: node-modules\` in .yarnrc.yml and run \`yarn install\` (not \`gjsify install\`).`);if(!t.packages||t.packages.length===0){let C=isWorkspaceRoot(S)?S:findWorkspaceRoot(S);if(C){C!==S&&ge.log(`gjsify install: resolved workspace root ${C} (from ${S}); installing the workspace.`),await workspaceInstall(C,t,n);return}}let F,I=readPackageJson$1(C),H=I?projectSpecsFromPackageJson(I):[];if(t.packages&&t.packages.length>0){let n=new Set(t.packages.map(t=>parseSpec$2(t).name));F=[...H.filter(t=>!n.has(parseSpec$2(t).name)),...t.packages]}else{if(!I)throw Error(`gjsify install: no package.json in ${S}`);if(F=H,F.length===0){ge.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(S,{recursive:!0});let W=makeProgressReporter({enabled:!t.verbose&&!t.quiet&&t.progress!==!1}),q=await acquireInstallLock(S,{signal:n});try{let N=activateDevLinks(S,!0),H=await installPackages({prefix:S,specs:F,verbose:t.verbose,lockfile:!t.immutable,frozen:t.immutable,refreshLockfile:t[`refresh-lockfile`],signal:n,progress:W,optionalSpecs:new Set([...optionalDependencyNames(I?[I]:[]),...t[`save-optional`]?(t.packages??[]).map(t=>parseSpec$2(t).name):[]]),linkedNames:N?.names});if(reportRewiredDevLinks(N),t.packages&&t.packages.length>0&&I){let n=depKindFromArgs(t);for(let S of t.packages){let{name:t,range:C}=parseSpec$2(S),N=H.installed.find(n=>n.name===t);addDependencyEntry(I,t,C??(N?defaultRangeFromVersion(N.version):`latest`),n)}writePackageJson(C,I),t.immutable||syncLockfileRequested(S,projectSpecsFromPackageJson(I))}}finally{q.release()}}function syncLockfileRequested(t,n){let S=zn(t,`gjsify-lock.json`);if(existsSync(S))try{let t=JSON.parse(readFileSync(S,`utf-8`)),C=[...n].sort(),N=[...t.requested??[]].sort();if(C.length===N.length&&C.every((t,n)=>t===N[n]))return;t.requested=n,atomicWriteStrict(S,JSON.stringify(t,null,2)+`
|
|
1248
|
+
`)}catch{}}async function workspaceInstall(t,n,S){let C=await acquireInstallLock(t,{signal:S});try{await workspaceInstallLocked(t,n,S)}finally{C.release()}}async function workspaceInstallLocked(t,n,S){let C=discoverWorkspaces(t,{includeRoot:!0});if(C.length===0)throw Error(`gjsify install: ${t} has a "workspaces" field but no workspaces were discovered`);let N=new Map(C.map(t=>[t.name,t])),F=n.focus&&n.focus.length>0?planFocus(C,n.focus,`gjsify install`):void 0,I=F?new Set(F.workspaces):void 0,H=new Set,W=new Map,q=[];for(let t of C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){if(typeof S!=`string`)continue;let C=N.get(n);if(C&&!/^(link|file|portal|git\+|https?):/.test(S)){if(I&&!I.has(t))continue;q.push({fromWorkspaceName:t.name,depName:n,targetLocation:C.location});continue}if(S.startsWith(`workspace:`))throw Error(`gjsify install: ${t.name} declares "${n}: ${S}" but no workspace with that name exists`);if(/^(link|file|portal|git\+|https?):/.test(S))continue;let F=`${n}@${S}`;H.add(F);let Y=W.get(F);Y||(Y=new Set,W.set(F,Y)),Y.add(t.name)}}}ge.log(`gjsify install: ${C.length} workspace(s), ${H.size} external dep spec(s), ${q.length} workspace symlink(s)`);let Y=activateDevLinks(t,!0);writeWorkspaceBinShims(t,F?.workspaces??C);let wireWorkspaceSymlinks=async()=>{if(q.length>0){let t=await Promise.resolve().then(()=>(Vd(),Rd)),n=new Set,S=[];for(let t of q){let C=N.get(t.fromWorkspaceName);if(!C)continue;let F=zn(C.location,`node_modules`,t.depName);n.add(Hn(F));let I=workspaceLinkTarget(F,t.targetLocation);S.push({linkPath:F,relTarget:I})}await Promise.all([...n].map(n=>t.mkdir(n,{recursive:!0})));let C=0,F=[],wireOne=async(n,S)=>{try{await t.rm(n,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}await t.symlink(S,n,XG)};for(let t=0;t<Math.min(32,S.length);t++)F.push((async()=>{for(;;){let t=C++;if(t>=S.length)return;let n=S[t];if(!n)return;await wireOne(n.linkPath,n.relTarget)}})());await Promise.all(F),ge.log(`gjsify install: wired ${q.length} workspace symlink(s)`)}let n=zn(t,`node_modules`),S=0;for(let N of F?.workspaces??C){if(N.location===t||!N.name)continue;let C=zn(n,N.name),F=!1;try{lstatSync(C),F=!0}catch{}F||(mkdirSync(Hn(C),{recursive:!0}),symlinkSync(workspaceLinkTarget(C,N.location),C,XG),S++)}S>0&&ge.log(`gjsify install: hoisted ${S} workspace(s) to root node_modules/`)};await wireWorkspaceSymlinks();let X=C.find(n=>n.location===t)?.manifest,Z=extractOverrides(X),te=Z?.global,ne=new Map,re=new Set;if(Z&&Z.scoped.size>0){for(let t of F?.workspaces??C){let n=t.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C)){let C=scopedOverrideFor(t,n,Z);if(!C)continue;let N=C,F=t.location,I=ne.get(F);I||(I=new Set,ne.set(F,I)),I.add(`${n}@${N}`),re.add(`${n}@${S}`)}}}let t=new Set;for(let n of C)for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n.manifest[S];if(C)for(let[S,N]of Object.entries(C))scopedOverrideFor(n,S,Z)||t.add(`${S}@${N}`)}for(let n of re)t.has(n)||H.delete(n);ne.size>0&&ge.log(`gjsify install: ${ne.size} workspace(s) have scoped overrides — they will install their overridden deps locally after the root install`)}if(H.size>0){let I=makeProgressReporter({enabled:!n.verbose&&!n.quiet&&n.progress!==!1});await installPackages({prefix:t,specs:[...H],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,refreshLockfile:n[`refresh-lockfile`],overrides:te,signal:S,progress:I,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,specOrigins:new Map([...W].map(([t,n])=>[t,[...n]])),optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest)),focusSpecs:F?.specs})}else n.verbose&&ge.log(`gjsify install: no external deps to fetch`);for(let[t,F]of ne){if(F.size===0)continue;let I=C.find(n=>n.location===t)?.name??t;n.verbose&&ge.log(`gjsify install: ${I} — installing ${F.size} scoped-override spec(s) into ${t}/node_modules/`),await installPackages({prefix:t,specs:[...F],verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,signal:S,workspaceNames:new Set(N.keys()),linkedNames:Y?.names,optionalSpecs:optionalDependencyNames(C.map(t=>t.manifest))})}await wireWorkspaceSymlinks(),reportRewiredDevLinks(Y);let ie=writeWorkspaceBinShims(t,F?.workspaces??C);ie>0&&ge.log(`gjsify install: linked ${ie} workspace bin(s) into node_modules/.bin/`)}function writeWorkspaceBinShims(t,n){let S=zn(t,`node_modules`,`.bin`),C=detectNativePackages(t).map(t=>t.prebuildsDir),N=0;for(let F of n){let n=F.manifest,I=n.gjsify?.bin,H=n.bin,W=mergeWorkspaceBins(F.name,I,H);if(W.size!==0){mkdirSync(S,{recursive:!0});for(let[n,{nodeTarget:I,gjsTarget:H}]of W){let W=zn(S,n);for(let t of[W,`${W}.cmd`,`${W}.ps1`])try{rmSync(t,{force:!0,maxRetries:10,retryDelay:100})}catch{}if(writeFileSync(W,buildBinShim(F.location,I,H,C,process.platform,t),{mode:493}),chmodSync(W,493),process.platform===`win32`)for(let[t,n]of Object.entries(buildWorkspaceBinShimsForWindows(F.location,I,H,C)))writeFileSync(`${W}.${t}`,n,{mode:493});N++}}}return N}function extractOverrides(t){if(!t)return;let n={},S=new Map,merge=(t,C)=>{if(t){for(let[N,F]of Object.entries(t))if(!N.startsWith(`_`)){if(typeof F==`string`){let t=N,S=N.startsWith(`@`)?N.indexOf(`@`,1):N.indexOf(`@`);S>0&&(t=N.slice(0,S)),n[t]=F;continue}if(F&&typeof F==`object`&&!Array.isArray(F)){let t={};for(let[n,S]of Object.entries(F)){if(n.startsWith(`_`))continue;if(typeof S!=`string`){ge.warn(`gjsify install: ${C}["${N}"]["${n}"] is not a string — only one level of nesting is supported, skipping`);continue}let F=n,I=n.startsWith(`@`)?n.indexOf(`@`,1):n.indexOf(`@`);I>0&&(F=n.slice(0,I)),t[F]=S}if(Object.keys(t).length>0){let n=S.get(N)??{};S.set(N,{...n,...t})}continue}ge.warn(`gjsify install: ${C}["${N}"] is not a string or object — skipping`)}}};if(merge(t.overrides,`overrides`),merge(t.resolutions,`resolutions`),!(Object.keys(n).length===0&&S.size===0))return{global:n,scoped:S}}function scopedOverrideFor(t,n,S){if(!S||S.scoped.size===0)return;let C=[t.name,t.relativeLocation];for(let t of C){let C=S.scoped.get(t);if(C?.[n])return C[n]}}function buildBinShim(t,n,S,C=[],N=process.platform,F=t){let I=n?zn(t,n):null,H=S?zn(t,S):null,W=buildNativeEnvPreamble(F,C,{platform:N});if(I&&H){let t=N===`darwin`||N===`win32`,n=`if command -v gjs >/dev/null 2>&1 && [ -f "${H}" ]; then\n${W}exec gjs -m "${H}" "$@"\nfi\nexec node "${I}" "$@"\n`,S=`if command -v node >/dev/null 2>&1 && [ -f "${I}" ]; then\nexec node "${I}" "$@"\nfi\n${W}exec gjs -m "${H}" "$@"\n`;return`#!/bin/sh
|
|
1249
1249
|
`+(t?S:n)}if(I)return`#!/bin/sh\nexec node "${I}" "$@"\n`;if(H)return`#!/bin/sh\n${W}exec gjs -m "${H}" "$@"\n`;throw Error(`buildBinShim: either nodeTarget or gjsTarget must be provided`)}function buildWorkspaceBinShimsForWindows(t,n,S,C=[]){let N=n?zn(t,n):null,F=S?zn(t,S):null;if(N)return buildLauncherShims({interpreter:`node`,target:N});if(F){let t=C.join(`;`);return buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:F,prependEnv:C.length===0?{}:{GI_TYPELIB_PATH:t,PATH:t}})}throw Error(`buildWorkspaceBinShimsForWindows: either nodeTarget or gjsTarget must be provided`)}function mergeWorkspaceBins(t,n,S){let C=new Map,N=t.startsWith(`@`)?t.slice(t.indexOf(`/`)+1):t,get=t=>{let n=C.get(t);return n||(n={},C.set(t,n)),n};if(typeof S==`string`)get(N).nodeTarget=S;else if(S&&typeof S==`object`)for(let[t,n]of Object.entries(S))typeof n==`string`&&n.length>0&&(get(t).nodeTarget=n);if(typeof n==`string`)get(N).gjsTarget=n;else if(n&&typeof n==`object`)for(let[t,S]of Object.entries(n))typeof S==`string`&&S.length>0&&(get(t).gjsTarget=S);return C}async function projectInstallViaNpm(t){let n=[`install`];t[`save-dev`]&&n.push(`--save-dev`),t[`save-peer`]&&n.push(`--save-peer`),t[`save-optional`]&&n.push(`--save-optional`),t.verbose&&n.push(`--loglevel`,`verbose`),t.packages&&t.packages.length>0&&n.push(...t.packages),await spawnNpm(n)}async function spawnNpm(t){return spawnToCompletion(`npm`,t,{completion:`return`,notFound:()=>Error(`npm not found on PATH — install Node.js first.`)}).then(({code:t})=>{if(t!==0)throw Error(`npm install exited with code ${t}`)}).catch(t=>{let n=t.code;ge.error(n===void 0?t.message:`npm install failed: ${t.message}`),process.exit(1)})}async function installGlobalAndLink(t,n){let S=defaultGlobalLayout();mkdirSync(S.prefix,{recursive:!0}),ge.log(`gjsify install --global → ${S.prefix}`),ge.log(` bins → ${S.binDir}`);let C=await acquireInstallLock(S.prefix,{});try{let C=await installPackages({prefix:S.prefix,specs:t,verbose:n.verbose}),N=t.map(specToPackageName);if(N.includes(`@gjsify/cli`)){let t=C.installed.find(t=>t.name===`@gjsify/cli`)?.version??`latest`;await installGjsEnginePackages(S.prefix,t,{verbose:n.verbose})}n.prune!==!1&&pruneAfterInstall(S.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`}),reportLinkedBins(linkGlobalBins(N,S),S.binDir)}finally{C.release()}}function pruneProjectPrefix(t){t.prune!==!1&&pruneAfterInstall(process.cwd(),resolveHostPlatform({env:{}}),{immutable:t.immutable===!0,hint:`gjsify prune --dry-run`})}function reportLinkedBins(t,n){if(t.length===0)ge.warn("\nNo bins declared (neither `gjsify.bin` nor `bin` in package.json) — nothing was symlinked.");else{ge.log(`\nLinked ${t.length} bin(s):`);for(let n of t)ge.log(` • ${n.link} → ${n.target}`)}t.length>0&&!binDirOnPath(n)&&ge.warn(`\nNote: ${n} is not on your PATH.\nAdd it to your shell rc file:\n export PATH="${n}:$PATH"`)}async function ensureProjectGjsEngine(t,n,S={}){let C=S.cwd??process.cwd(),N=S.hasEngineFn??hasBundlerEngineInstalled;if(!existsSync(zn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))||!n||N(C))return;if(t.immutable){ge.warn(`\nWarning: \`gjsify build\` will fail under GJS — ${qz} is not installed, and\n --immutable cannot add it (the lockfile does not name it). Declare it so the lockfile carries it:
|
|
1250
1250
|
gjsify install ${qz}\n Under Node the npm \`rolldown\` engine is used instead and this does not apply.`);return}let F=readCliVersionFrom(zn(C,`node_modules`,`@gjsify`,`cli`,`package.json`))??`latest`;ge.log(`\n${qz} is missing and this host can run gjs, so \`gjsify build\` would have no\n bundler engine (there is no npm \`rolldown\` fallback under GJS). Installing the GJS engine set at\n ${F}, in lockstep with the CLI.`),await(S.installFn??installGjsEnginePackages)(C,F,{verbose:t.verbose})}async function runPostInstallChecks(t){ge.log(`
|
|
1251
1251
|
--- gjsify post-install checks ---`);let n=runMinimalChecks(),S=n.filter(t=>!t.found&&t.severity===`required`);if(S.length>0){ge.warn(`Missing required system dependencies:
|
|
@@ -1257,27 +1257,27 @@ jq -n --arg v "$version" --arg d "$date" ${N.join(` `)} \\
|
|
|
1257
1257
|
A bridge lost that way is silently absent from the next build rather than
|
|
1258
1258
|
reported, so the first symptom can be an unrelated-looking bundler error
|
|
1259
1259
|
(\`Could not load <file>\` from rolldown, for the CSS bridge). Nothing to
|
|
1260
|
-
install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=zn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(zn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var YG,XG,ZG,QG,$G=__esmMin(()=>{_e(),af(),Xn(),cr(),cv(),JG(),GI(),dL(),gL(),NR(),Gz(),ZR(),gz(),UR(),hv(),qI(),jV(),Yz(),Az(),Mz(),YR(),Fz(),YG=process.platform===`win32`?`junction`:void 0,XG=18e5,ZG={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:t=>t.positional(`packages`,{description:`Optional package specs. With none, runs a full project install.`,type:`string`,array:!0}).option(`global`,{description:`Install into the user-global XDG location and symlink bins into ~/.local/bin.`,type:`boolean`,alias:`g`,default:!1}).option(`save-dev`,{type:`boolean`,alias:`D`}).option(`save-peer`,{type:`boolean`}).option(`save-optional`,{type:`boolean`,alias:`O`}).option(`immutable`,{description:`CI mode: install strictly from gjsify-lock.json, fail if the lockfile is missing or stale. Equivalent to yarn --immutable / npm ci --frozen-lockfile.`,type:`boolean`,default:!1}).option(`refresh-lockfile`,{description:`Re-resolve every dependency to the newest version satisfying its range and rewrite the lockfile (bumps in-range transitive deps). Without it, a resolve preserves versions already pinned in the lockfile and only resolves new/changed deps — the npm/yarn/pnpm default. Mirrors yarn install --mode=update-lockfile.`,type:`boolean`,default:!1}).option(`focus`,{description:`Install only the named workspaces (package names), the workspaces they depend on, and their external dependencies, as if they were the only members of the monorepo (yarn workspaces focus). Reads gjsify-lock.json and never rewrites it; fails if it is missing or stale. Workspace projects only.`,type:`string`,array:!0}).option(`verbose`,{description:`Verbose install logging.`,type:`boolean`,default:!1}).option(`quiet`,{description:`Silence the progress bar.`,type:`boolean`,default:!1}).option(`progress`,{description:`Show a TTY-aware progress bar for resolve / download / extract phases. Auto-enabled when stderr is a TTY (override with --no-progress). Implicitly off under --verbose (per-package log lines replace the bar) or --quiet.`,type:`boolean`,default:!0}).option(`backend`,{description:"Install backend. `native` (default) routes through `@gjsify/{semver,npm-registry,tar}` — no Node/npm at runtime. `npm` shells out to `npm install` as an escape hatch for cases the native backend does not yet model (Yarn PnP repos, lifecycle scripts). Overrides `GJSIFY_INSTALL_BACKEND` if both are set.",type:`string`,choices:[`native`,`npm`]}).option(`timeout`,{description:`Overall install wall-clock timeout in ms (default 1800000 = 30 min). On timeout, all in-flight registry fetches are aborted and the install exits non-zero with a clear "install timed out — likely a registry slowdown" message. Per-request timeouts in @gjsify/npm-registry (default 30s) still apply within this budget. Set to 0 to disable the overall budget.`,type:`number`,default:XG}).option(`os`,{description:"Resolve/install for this OS instead of the running one (npm config key `os`, e.g. darwin, win32, linux). Affects which packages pass the os/cpu/libc compatibility check; the lockfile stays platform-independent either way.",type:`string`}).option(`cpu`,{description:"Resolve/install for this CPU architecture instead of the running one (npm config key `cpu`, e.g. x64, arm64).",type:`string`}).option(`libc`,{description:"Resolve/install for this libc family instead of probing the host (npm config key `libc`: glibc or musl). Only meaningful with --os=linux. A package declaring a libc is incompatible when the target libc is unknown.",type:`string`}).option(`force`,{description:"Install a REQUIRED dependency even when its os/cpu/libc excludes the target, instead of failing with EBADPLATFORM (npm config key `force`). Incompatible OPTIONAL dependencies stay skipped — npm ignores --force for those too, and a binary that cannot load is not worth downloading.",type:`boolean`,default:!1}).option(`prune`,{description:`After installing, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable. Skipped automatically under --immutable, and whenever --os/--cpu/--libc is given: an install must never delete against a target the user typed.`,type:`boolean`,default:!0}),handler:async t=>{if(applyPlatformConfigFromFlags(t),t.immutable){if(t.packages&&t.packages.length>0)return ge.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(t.global)return ge.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(t[`refresh-lockfile`])return ge.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1);assertNoDevLinkUnderImmutable(process.cwd())}if(t.global){if(!t.packages||t.packages.length===0)return ge.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let n of[`save-dev`,`save-peer`,`save-optional`])t[n]&&ge.warn(`gjsify install --global ignores --${n}: global installs do not modify a project package.json.`);await installGlobalAndLink(t.packages,{verbose:t.verbose,prune:t.prune});return}if(warnOnCliVersionSkew(process.cwd()),(t.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(t),pruneProjectPrefix(t),await runPostInstallChecks(t);return}let n=t.timeout>0?t.timeout:0,S=n>0?new AbortController:null,C=S===null?null:setTimeout(()=>S.abort(Error(`install-overall-timeout`)),n),N=n>0?setTimeout(()=>{let t=Math.round(n/100)/10;ge.error(`gjsify install: the ${t}s budget elapsed and the abort did not unwind within 10s — forcing exit. That means one of two things, and this timer cannot distinguish them: the install was still WORKING (a cold tree here extracts several GB, and extraction blocks the loop in multi-second synchronous stretches), or a step genuinely wedged. Re-running tells you which, and is safe: extraction is idempotent, every package already on disk is skipped, so a second run finishes the remainder in a fraction of the time. A re-run that makes NO further progress is a real wedge — file an issue.`),forceExit(1)},n+1e4):null;N?.unref?.();try{await projectInstallNative(t,S?.signal),pruneProjectPrefix(t),await runPostInstallChecks(t)}catch(t){if(S!==null&&S.signal.aborted&&isAbortedFromOverallTimeout(t)){let t=Math.round(n/100)/10;return ge.error(`gjsify install: timed out after ${t}s — likely a registry slowdown or a wedged extract.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw t}finally{C!==null&&clearTimeout(C),N!==null&&clearTimeout(N)}}},QG=`@gjsify/cli`});function sweepCheckouts(t,n){let S=null;try{S=readDevLinkOverride(t)?.checkout??null}catch{S=null}return S&&S!==n?[S,n]:[n]}var eK,tK,nK=__esmMin(()=>{_e(),af(),Xn(),Fz(),eK={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually uses are linked: declared dependencies plus everything in its lockfile or installed node_modules, transitive and nested copies included.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=In(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n),nested:consumerNestedPlacements(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} uses (declared, locked or installed)${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Bn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H);writeDevLinkOverride(n,{version:1,checkout:C,packages:I});let re=ensureLocallyIgnored(n);ge.log(`\n ${ne.length} link(s) written, ${H.length-ne.length} already current.`),Z.length>0&&ge.log(` ${te.length} of ${Z.length} retired link(s) removed.`),ge.log(` override: ${N}`),re===`added`&&ge.log(` git: ${Nz} added to .git/info/exclude (local, never committed)`),re===`no-git`&&ge.log(` git: ${n} is not a git repository — nothing to ignore`),re===`unreadable-git`&&ge.warn(` ! git: ${n} has a .git POINTER that does not parse, so ${Nz} is NOT ignored. Add it to .gitignore by hand, or the next \`git add -A\` commits your local override.`),ge.log("\nEvery `gjsify install` here now re-applies these links and says so.\n`gjsify install --immutable` refuses while the override exists. Undo: `gjsify unlink`.")}},tK={command:`unlink`,description:"Undo `gjsify link`: remove the development links and the .gjsify-link.json override, then reinstall the registry copies.",builder:t=>t.option(`dry-run`,{description:`Print what would be removed and change nothing.`,type:`boolean`,default:!1}).option(`install`,{description:"Reinstall after unlinking, to put the registry copies back where the links were. On by default; --no-install leaves the holes for a later `gjsify install`.",type:`boolean`,default:!0}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=devLinkPath(n);if(!existsSync(C)){ge.log(`gjsify unlink: no development link in ${n} (no ${Nz}).`);return}let N=[];try{let t=readDevLinkOverride(n)?.checkout;t&&N.push(t)}catch{}let F=[];try{F=prepareDevLinks(n)?.links??[]}catch(t){ge.warn(`gjsify unlink: ${t instanceof Error?t.message:String(t)}\n Removing the override anyway; any dangling links are cleaned by the reinstall.`)}let I=`gjsify unlink${S?` (dry-run)`:``}`;if(ge.log(`${I} in ${n}`),S){let t=new Set(F.map(t=>t.name));for(let S of scanDevLinks(n,N))t.add(S.name);for(let n of[...t].sort())ge.log(` would remove link ${n}`);ge.log(` would remove ${C}`),ge.log(` would remove ${Nz} entry from .git/info/exclude (if this module wrote it)`),ge.log(`\n${I}: nothing changed. Drop --dry-run to apply.`);return}let H=removeDevLinks(F),W=new Set(H.map(t=>t.name));for(let t of retireDevLinks(n,N,new Set))W.has(t.name)||H.push(t);for(let t of H)ge.log(` unlinked ${t.name}`);let q=scanDevLinks(n,N);if(q.length>0)return ge.error(`gjsify unlink: ${q.length} link(s) still point into a checkout and could not be removed:\n`+q.map(t=>` ${t.name} ${t.linkPath} → ${t.target}`).join(`
|
|
1261
|
-
`)+`\n ${C} is kept so this stays undoable. Remove the paths above and re-run.`),process.exit(1);if(removeDevLinkOverride(n),ge.log(` removed ${C}`),removeLocalIgnore(n)===`removed`&&ge.log(` removed ${Nz} entry from .git/info/exclude`),t.install===!1){ge.log(`\n ${H.length} link(s) removed. Run \`gjsify install\` to restore the registry copies.`);return}ge.log(`\n ${H.length} link(s) removed — reinstalling to restore the registry copies.\n`);let{runCli:Y}=await Promise.resolve().then(()=>(
|
|
1262
|
-
`)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(t){return t.length>=2&&(t[0]===`'`||t[0]===`"`)&&t[t.length-1]===t[0]?t.slice(1,-1):t}async function runSequential(t,n,S,C,N,F){for(let I of t)await runOne(I,n,S,!1,C,N,F)}async function runParallel(t,n,S,C,N,F,I){let H=0,W=[];for(let q=0;q<C;q++)W.push((async()=>{for(;H<t.length;)await runOne(t[H++],n,S,!0,N,F,I)})());await Promise.all(W)}async function runTopologicalParallel(t,n,S,C,N,F,I,H){let W=new Map([...buildDependencyGraph(t,{includeDev:F}).edges].map(([t,n])=>[t,new Set(n)])),q=new Map(t.map(t=>[t.name,t])),Y=t.length,X=new Set,Z=0,te=!process.stdout.isTTY||N,ne=new Map,re=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),ie=(Number.isFinite(re)&&re>0?re:20)*6e4;return new Promise((t,F)=>{let re=null,ae=Date.now(),describeInflight=()=>[...ne.entries()].map(([t,n])=>`${t} (${Math.round((Date.now()-n)/1e3)}s)`).join(`, `),failFast=t=>{re||(re=t,killActiveChildren(),setTimeout(()=>settle(),oK).unref?.())},oe=setInterval(()=>{let t=Date.now()-ae;t<3e5||ne.size===0||(ge.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(t/6e4)}min — in-flight: ${describeInflight()}`),t>=ie&&failFast(Error(`gjsify foreach: stalled — no workspace completed for ${Math.round(t/6e4)}min (override via GJSIFY_FOREACH_STALL_MINUTES); killed in-flight: ${describeInflight()}`)))},6e4);oe.unref?.();let settle=()=>{clearInterval(oe),re?F(re):t()},pump=()=>{if(!re){for(;Z<C;){let t=[...W.entries()].filter(([,t])=>[...t].every(t=>X.has(t))).map(([t])=>t);if(t.length===0)break;let C=t.sort()[0];W.delete(C),Z++,ne.set(C,Date.now()),te&&ge.error(`[gjsify foreach] start ${C} (${X.size}/${Y} done, ${Z} in flight)`),runOne(q.get(C),n,S,!0,N,I,H).then(()=>{X.add(C)}).catch(t=>{failFast(t instanceof Error?t:Error(String(t)))}).finally(()=>{Z--,ne.delete(C),ae=Date.now(),re?Z===0&&settle():W.size===0&&Z===0?settle():pump()})}W.size>0&&Z===0&&!re&&(clearInterval(oe),F(Error(`gjsify foreach --topological: stuck — workspaces ${[...W.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne(t,n,S,C,N,F,I){if(F){N&&ge.error(`[${t.name}] $ ${n} ${S.join(` `)}`),await spawnPrefixed(n,S,t.location,C?`[${t.name}] `:null);return}if(I&&I.tryRestore(t))return;let H=I?.snapshotOutputs(t),W=detectPackageManager(),q=W===`gjsify`?[`run`,n,...S]:[`run`,n,...S.length>0?[`--`,...S]:[]];N&&ge.error(`[${t.name}] $ ${W} ${q.join(` `)}`),await spawnPrefixed(W,q,t.location,C?`[${t.name}] `:null),I&&H&&I.storeAfterSuccess(t,H)}async function spawnPrefixed(t,n,S,C){let N=null,F=[];try{let I=await spawnToCompletion(t,n,{completion:`exit`,cwd:S,stdio:C?`pipe`:`inherit`,color:!0,onSpawn:t=>{N=t,iK.add(t);let n=!process.stdout.isTTY;C&&t.stdout&&t.stderr&&(F.push(prefixLines(t.stdout,process.stdout,C,n)),F.push(prefixLines(t.stderr,process.stderr,C,n)))}});for(let t of F)t();if(I.code!==0)throw Error(`${t} ${n.join(` `)} exited with code ${I.code}`)}finally{N&&iK.delete(N)}}var iK,aK,oK,sK,cK=__esmMin(()=>{_e(),hv(),sz(),o_(),GI(),qI(),rK(),cB(),TR(),fB(),hB(),iK=new Set,aK=5e3,oK=15e3,sK={command:`foreach [script] [args..]`,description:"Run a workspace script across all (or filtered) workspaces. Drop-in for `yarn workspaces foreach`: -A/--all, -p/--parallel, -t/--topological, --include, --exclude, --no-private. Pass --exec to run an arbitrary command instead of a script.",builder:t=>t.positional(`script`,{description:"Script name to run in each workspace (`run <name>`-equivalent). With --exec, the command to run instead.",type:`string`}).positional(`args`,{description:`Extra arguments forwarded to each child invocation.`,type:`string`,array:!0}).option(`all`,{description:"Include workspaces declared as `private: true`.",type:`boolean`,alias:`A`,default:!1}).option(`parallel`,{description:`Run workspaces in parallel (capped by --jobs).`,type:`boolean`,alias:`p`,default:!1}).option(`topological`,{description:`Wait for each workspace's deps to finish before starting it (production deps only).`,type:`boolean`,alias:`t`,default:!1}).option(`topological-dev`,{description:`Like --topological but also respects devDependencies (often cyclic — use sparingly).`,type:`boolean`,default:!1}).option(`include`,{description:`Glob pattern to include workspaces by name (repeatable). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=t.exec===!0,N=t.script,F=t.args??[];if(!C){let n=doubleDashArgs(t);n.length>0&&(F=[...F,...n])}if(C){let n=doubleDashArgs(t);if(n.length>0&&(N?F=[...F,...n]:(N=n[0],F=[...F,...n.slice(1)])),!N)return ge.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(S,t.include);let I=filterWorkspaces(S,{include:t.include,exclude:t.exclude,noPrivate:t.private===!1});if(t[`with-dependencies`]===!0){let n=affectedClosure(buildDependencyGraph(S,{includeDev:t[`topological-dev`]===!0}),I.map(t=>t.name));I=filterWorkspaces(S.filter(t=>n.has(t.name)),{exclude:t.exclude,noPrivate:t.private===!1})}if(!C){if(!N)return ge.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let t=N;I=I.filter(n=>typeof(n.manifest.scripts??{})[t]==`string`)}if(typeof t.shard==`string`&&t.shard.length>0){let n=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(t.shard);if(!n)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let S=Number(n[1]),C=Number(n[2]);if(C<1||S<1||S>C)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(C>1){let t=[...I].sort((t,n)=>t.name<n.name?-1:+(t.name>n.name));I=t.filter((t,n)=>n%C===S-1),ge.log(`gjsify foreach: shard ${S}/${C} → ${I.length} of ${t.length} workspace(s)`)}}if(I.length===0){ge.log(`gjsify foreach: no workspaces match (${C?`exec`:`script`}="${N}", include=${JSON.stringify(t.include??[])}, exclude=${JSON.stringify(t.exclude??[])})`);return}(t.topological||t[`topological-dev`])&&(I=topologicalSort(buildDependencyGraph(I,{includeDev:t[`topological-dev`]===!0})));let H=t.verbose===!0,W=N,q=t.cached??buildCacheEnabledByEnv();if(t.cached===!0&&C)return ge.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let Y=q&&!C?new BuildCacheRunner({root:n,workspaces:S,script:W,args:F,targets:I.map(t=>t.name)}):void 0,X=t.parallel===!0?cliRuntimeClosure(S):new Set,Z=X.size>0?I.filter(t=>X.has(t.name)):[],te=Z.length>0?I.filter(t=>!X.has(t.name)):I;try{if(Z.length>0){ge.error(`[gjsify foreach] serial prefix: ${Z.length} package(s) the running CLI imports — ${Z.map(t=>t.name).join(`, `)}`);for(let t of Z)ge.error(`[gjsify foreach] start ${t.name} (serial prefix)`),await runOne(t,W,F,!0,H,C,Y)}if(t.parallel&&!t.topological&&!t[`topological-dev`]){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runParallel(te,W,F,n,H,C,Y)}else if(t.parallel){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runTopologicalParallel(te,W,F,n,H,t[`topological-dev`]===!0,C,Y)}else await runSequential(te,W,F,H,C,Y)}catch(t){return killActiveChildren(),ge.error(t.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(t,n,S,C={}){let N=(n.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${t}/package.json`)}let F=findWorkspaceRoot(t),I=[zn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(zn(F,`node_modules`,`.bin`));let H=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},W={...process.env,...H,PATH:[...I,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:S,npm_package_name:n.name??``,npm_package_version:n.version??``,...C.env};if(C.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let q=await spawnToCompletion(N,[],{completion:`return`,cwd:t,env:W,shell:!0,stdio:C.stdio===`inherit-stderr`?`inherit-stderr`:C.stdio===`pipe`?`pipe`:`inherit`});if(q.code!==0)throw Error(`gjsify lifecycle-script: "${S}" in ${t} exited with ${describeExit(q)}`);return!0}var lK=__esmMin(()=>{Xn(),hv(),qI()});async function packWorkspace(t,n={}){let S=zn(t,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${t}`);let C=readFileSync(S,`utf-8`),N=JSON.parse(C),F=typeof N.name==`string`?N.name:``,I=typeof N.version==`string`?N.version:`0.0.0`;if(!F)throw Error(`gjsify pack: package.json at ${t} has no "name"`);let H=n.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(t,N,S,{optional:!0,stdio:n.lifecycleStdio});let W=readFileSync(S,`utf-8`),q=W===C?N:JSON.parse(W),Y=n.skipWorkspaceRewrite?q:rewriteWorkspaceDeps(q,t),X=JSON.stringify(Y,null,indentOf(W))+`
|
|
1260
|
+
install: no \`-musl\` package is published for any target yet.`)}}maybeInstallGitHooks()}function maybeInstallGitHooks(){let t=process.cwd(),n=zn(t,`scripts`,`install-git-hooks.mjs`);if(existsSync(n)&&existsSync(zn(t,`.git`)))try{let S=spawnSync(nodeBinary(),[n,`--quiet`],{cwd:t,stdio:`inherit`,env:process.env});S.status!==0&&ge.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(t){ge.warn(`[gjsify install] git hook installation skipped: ${t instanceof Error?t.message:String(t)}`)}}var XG,ZG,QG,$G,eK=__esmMin(()=>{_e(),af(),Xn(),cr(),cv(),YG(),GI(),dL(),gL(),NR(),Gz(),ZR(),gz(),UR(),hv(),qI(),jV(),Yz(),Az(),Mz(),YR(),Fz(),XG=process.platform===`win32`?`junction`:void 0,ZG=18e5,QG={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:t=>t.positional(`packages`,{description:`Optional package specs. With none, runs a full project install.`,type:`string`,array:!0}).option(`global`,{description:`Install into the user-global XDG location and symlink bins into ~/.local/bin.`,type:`boolean`,alias:`g`,default:!1}).option(`save-dev`,{type:`boolean`,alias:`D`}).option(`save-peer`,{type:`boolean`}).option(`save-optional`,{type:`boolean`,alias:`O`}).option(`immutable`,{description:`CI mode: install strictly from gjsify-lock.json, fail if the lockfile is missing or stale. Equivalent to yarn --immutable / npm ci --frozen-lockfile.`,type:`boolean`,default:!1}).option(`refresh-lockfile`,{description:`Re-resolve every dependency to the newest version satisfying its range and rewrite the lockfile (bumps in-range transitive deps). Without it, a resolve preserves versions already pinned in the lockfile and only resolves new/changed deps — the npm/yarn/pnpm default. Mirrors yarn install --mode=update-lockfile.`,type:`boolean`,default:!1}).option(`focus`,{description:`Install only the named workspaces (package names), the workspaces they depend on, and their external dependencies, as if they were the only members of the monorepo (yarn workspaces focus). Reads gjsify-lock.json and never rewrites it; fails if it is missing or stale. Workspace projects only.`,type:`string`,array:!0}).option(`verbose`,{description:`Verbose install logging.`,type:`boolean`,default:!1}).option(`quiet`,{description:`Silence the progress bar.`,type:`boolean`,default:!1}).option(`progress`,{description:`Show a TTY-aware progress bar for resolve / download / extract phases. Auto-enabled when stderr is a TTY (override with --no-progress). Implicitly off under --verbose (per-package log lines replace the bar) or --quiet.`,type:`boolean`,default:!0}).option(`backend`,{description:"Install backend. `native` (default) routes through `@gjsify/{semver,npm-registry,tar}` — no Node/npm at runtime. `npm` shells out to `npm install` as an escape hatch for cases the native backend does not yet model (Yarn PnP repos, lifecycle scripts). Overrides `GJSIFY_INSTALL_BACKEND` if both are set.",type:`string`,choices:[`native`,`npm`]}).option(`timeout`,{description:`Overall install wall-clock timeout in ms (default 1800000 = 30 min). On timeout, all in-flight registry fetches are aborted and the install exits non-zero with a clear "install timed out — likely a registry slowdown" message. Per-request timeouts in @gjsify/npm-registry (default 30s) still apply within this budget. Set to 0 to disable the overall budget.`,type:`number`,default:ZG}).option(`os`,{description:"Resolve/install for this OS instead of the running one (npm config key `os`, e.g. darwin, win32, linux). Affects which packages pass the os/cpu/libc compatibility check; the lockfile stays platform-independent either way.",type:`string`}).option(`cpu`,{description:"Resolve/install for this CPU architecture instead of the running one (npm config key `cpu`, e.g. x64, arm64).",type:`string`}).option(`libc`,{description:"Resolve/install for this libc family instead of probing the host (npm config key `libc`: glibc or musl). Only meaningful with --os=linux. A package declaring a libc is incompatible when the target libc is unknown.",type:`string`}).option(`force`,{description:"Install a REQUIRED dependency even when its os/cpu/libc excludes the target, instead of failing with EBADPLATFORM (npm config key `force`). Incompatible OPTIONAL dependencies stay skipped — npm ignores --force for those too, and a binary that cannot load is not worth downloading.",type:`boolean`,default:!1}).option(`prune`,{description:`After installing, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable. Skipped automatically under --immutable, and whenever --os/--cpu/--libc is given: an install must never delete against a target the user typed.`,type:`boolean`,default:!0}),handler:async t=>{if(applyPlatformConfigFromFlags(t),t.immutable){if(t.packages&&t.packages.length>0)return ge.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(t.global)return ge.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(t[`refresh-lockfile`])return ge.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1);assertNoDevLinkUnderImmutable(process.cwd())}if(t.global){if(!t.packages||t.packages.length===0)return ge.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let n of[`save-dev`,`save-peer`,`save-optional`])t[n]&&ge.warn(`gjsify install --global ignores --${n}: global installs do not modify a project package.json.`);await installGlobalAndLink(t.packages,{verbose:t.verbose,prune:t.prune});return}if(warnOnCliVersionSkew(process.cwd()),(t.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(t),pruneProjectPrefix(t),await runPostInstallChecks(t);return}let n=t.timeout>0?t.timeout:0,S=n>0?new AbortController:null,C=S===null?null:setTimeout(()=>S.abort(Error(`install-overall-timeout`)),n),N=n>0?setTimeout(()=>{let t=Math.round(n/100)/10;ge.error(`gjsify install: the ${t}s budget elapsed and the abort did not unwind within 10s — forcing exit. That means one of two things, and this timer cannot distinguish them: the install was still WORKING (a cold tree here extracts several GB, and extraction blocks the loop in multi-second synchronous stretches), or a step genuinely wedged. Re-running tells you which, and is safe: extraction is idempotent, every package already on disk is skipped, so a second run finishes the remainder in a fraction of the time. A re-run that makes NO further progress is a real wedge — file an issue.`),forceExit(1)},n+1e4):null;N?.unref?.();try{await projectInstallNative(t,S?.signal),pruneProjectPrefix(t),await runPostInstallChecks(t)}catch(t){if(S!==null&&S.signal.aborted&&isAbortedFromOverallTimeout(t)){let t=Math.round(n/100)/10;return ge.error(`gjsify install: timed out after ${t}s — likely a registry slowdown or a wedged extract.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw t}finally{C!==null&&clearTimeout(C),N!==null&&clearTimeout(N)}}},$G=`@gjsify/cli`});function sweepCheckouts(t,n){let S=null;try{S=readDevLinkOverride(t)?.checkout??null}catch{S=null}return S&&S!==n?[S,n]:[n]}var tK,nK,rK=__esmMin(()=>{_e(),af(),Xn(),Fz(),tK={command:`link <checkout>`,description:"Link this project against a local gjsify checkout for development: its workspace packages replace the installed registry copies, recorded in a git-ignored .gjsify-link.json that every later `gjsify install` re-applies. Undo with `gjsify unlink`.",builder:t=>t.positional(`checkout`,{description:`Path to the gjsify checkout to link from (a repo whose package.json declares "workspaces").`,type:`string`,demandOption:!0}).option(`packages`,{description:"Name glob selecting which of the checkout's workspace packages take part (repeatable; default: all of them). Matched against the package NAME with the same single-segment dialect as `gjsify foreach --include`, so a whole scope is `@gjsify/*` — a bare `*` matches no scoped name. Only packages this project actually uses are linked: declared dependencies plus everything in its lockfile or installed node_modules, transitive and nested copies included.",type:`string`,array:!0}).option(`dry-run`,{description:`Print the links that would be made and write nothing.`,type:`boolean`,default:!1}),handler:t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=In(n,t.checkout),N=devLinkPath(n),F=resolveCheckoutWorkspaces(C,N),I=t.packages??[],H=planDevLinks({consumerRoot:n,workspaces:F,patterns:I,knownNames:consumerKnownNames(n),nested:consumerNestedPlacements(n)});if(H.length===0)return ge.error(`gjsify link: nothing to link — ${C} has ${F.length} workspace package(s), none of which ${n} uses (declared, locked or installed)${I.length===0?``:` and matches ${I.join(`, `)}`}.\nA link that links nothing is a silent no-op, so this is an error. Check the --packages pattern, or run \`gjsify install\` first so the dependency tree exists.`),process.exit(1);let W=`gjsify link${S?` (dry-run)`:``}`;ge.log(`${W} → ${C}`),ge.log(`${` `.repeat(W.length)} in ${n}`);for(let t of H)ge.log(` ${t.name} → ${Bn(C,t.target)||`.`}`);let q=unbuiltDevLinks(H);if(q.length>0)return ge.error(`\n${formatUnbuiltDevLinks(q)}`),process.exit(1);let Y=sweepCheckouts(n,C),X=new Set(H.map(t=>t.name)),Z=scanDevLinks(n,Y).filter(t=>!X.has(t.name));for(let t of Z)ge.log(` retire ${t.name} (no longer selected)`);if(S){ge.log(`\n${W}: nothing written. Drop --dry-run to apply.`);return}let te=retireDevLinks(n,Y,X),ne=applyDevLinks(H);writeDevLinkOverride(n,{version:1,checkout:C,packages:I});let re=ensureLocallyIgnored(n);ge.log(`\n ${ne.length} link(s) written, ${H.length-ne.length} already current.`),Z.length>0&&ge.log(` ${te.length} of ${Z.length} retired link(s) removed.`),ge.log(` override: ${N}`),re===`added`&&ge.log(` git: ${Nz} added to .git/info/exclude (local, never committed)`),re===`no-git`&&ge.log(` git: ${n} is not a git repository — nothing to ignore`),re===`unreadable-git`&&ge.warn(` ! git: ${n} has a .git POINTER that does not parse, so ${Nz} is NOT ignored. Add it to .gitignore by hand, or the next \`git add -A\` commits your local override.`),ge.log("\nEvery `gjsify install` here now re-applies these links and says so.\n`gjsify install --immutable` refuses while the override exists. Undo: `gjsify unlink`.")}},nK={command:`unlink`,description:"Undo `gjsify link`: remove the development links and the .gjsify-link.json override, then reinstall the registry copies.",builder:t=>t.option(`dry-run`,{description:`Print what would be removed and change nothing.`,type:`boolean`,default:!1}).option(`install`,{description:"Reinstall after unlinking, to put the registry copies back where the links were. On by default; --no-install leaves the holes for a later `gjsify install`.",type:`boolean`,default:!0}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]??!1,C=devLinkPath(n);if(!existsSync(C)){ge.log(`gjsify unlink: no development link in ${n} (no ${Nz}).`);return}let N=[];try{let t=readDevLinkOverride(n)?.checkout;t&&N.push(t)}catch{}let F=[];try{F=prepareDevLinks(n)?.links??[]}catch(t){ge.warn(`gjsify unlink: ${t instanceof Error?t.message:String(t)}\n Removing the override anyway; any dangling links are cleaned by the reinstall.`)}let I=`gjsify unlink${S?` (dry-run)`:``}`;if(ge.log(`${I} in ${n}`),S){let t=new Set(F.map(t=>t.name));for(let S of scanDevLinks(n,N))t.add(S.name);for(let n of[...t].sort())ge.log(` would remove link ${n}`);ge.log(` would remove ${C}`),ge.log(` would remove ${Nz} entry from .git/info/exclude (if this module wrote it)`),ge.log(`\n${I}: nothing changed. Drop --dry-run to apply.`);return}let H=removeDevLinks(F),W=new Set(H.map(t=>t.name));for(let t of retireDevLinks(n,N,new Set))W.has(t.name)||H.push(t);for(let t of H)ge.log(` unlinked ${t.name}`);let q=scanDevLinks(n,N);if(q.length>0)return ge.error(`gjsify unlink: ${q.length} link(s) still point into a checkout and could not be removed:\n`+q.map(t=>` ${t.name} ${t.linkPath} → ${t.target}`).join(`
|
|
1261
|
+
`)+`\n ${C} is kept so this stays undoable. Remove the paths above and re-run.`),process.exit(1);if(removeDevLinkOverride(n),ge.log(` removed ${C}`),removeLocalIgnore(n)===`removed`&&ge.log(` removed ${Nz} entry from .git/info/exclude`),t.install===!1){ge.log(`\n ${H.length} link(s) removed. Run \`gjsify install\` to restore the registry copies.`);return}ge.log(`\n ${H.length} link(s) removed — reinstalling to restore the registry copies.\n`);let{runCli:Y}=await Promise.resolve().then(()=>(HX(),VX));await Y([`install`])}}});function splitWorkspaceSpecifier(t,n){if(t.startsWith(`.`)||t.startsWith(`/`)||t.includes(`:`))return null;let S=t.split(`/`),C=t.startsWith(`@`)?[2]:[1];for(let t of C){let C=S.slice(0,t).join(`/`);if(!n.has(C))continue;let N=S.slice(t).join(`/`);return{name:C,subpath:N?`./${N}`:`.`}}return null}function resolveRelative(t,n){let S=In(Hn(t),n);for(let t of[S,`${S}.js`,`${S}.mjs`,zn(S,`index.js`)])try{if(statSync(t).isFile())return t}catch{}return null}function workspaceEntry(t,n){let S=t.manifest,pick=t=>{if(typeof t==`string`)return t;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;for(let t of[`node`,`import`,`default`,`gjs`])if(t in n){let S=pick(n[t]);if(S)return S}return null},C=null;if(typeof S.exports==`string`?C=n===`.`?S.exports:null:S.exports&&typeof S.exports==`object`&&(C=pick(S.exports[n])),!C&&n===`.`&&(C=typeof S.module==`string`?S.module:null,C??=typeof S.main==`string`?S.main:null),!C)return null;let N=In(t.location,C);return existsSync(N)?N:null}function workspacePeers(t,n){return Object.keys(t.peerDependencies??{}).filter(t=>n.has(t))}function cliRuntimeClosure(t,n={}){let S=new Map(t.map(t=>[t.name,t])),C=new Set,N=n.entry,F=n.cliManifest;if(N===void 0||F===void 0){let t=cliPackageDir(),n=null;if(t)try{n=JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{}if(F??=n,N===void 0){let S=n?.bin,C=typeof S==`string`?S:S?.gjsify??n?.main;N=t&&C?In(t,C):null}}for(let t of workspacePeers(F??{},S))C.add(t);if(!N||!existsSync(N))return C;let I=new Set,H=[N];for(;H.length>0;){let t=H.shift();if(I.has(t))continue;I.add(t);let n;try{n=readFileSync(t,`utf8`)}catch{continue}for(let N of moduleSpecifiers$1(n)){if(N.startsWith(`.`)){let n=resolveRelative(t,N);n&&H.push(n);continue}let n=splitWorkspaceSpecifier(N,S),F=n?S.get(n.name):void 0;if(!n||!F)continue;C.add(n.name);for(let t of workspacePeers(F.manifest,S))C.add(t);let I=workspaceEntry(F,n.subpath);I&&H.push(I)}}return C}var iK=__esmMin(()=>{af(),Xn(),fP(),Ch()});function signalTree(t,n,S){for(let t=n.length-1;t>=0;t--)try{process.kill(n[t],S)}catch{}try{t.kill(S)}catch{}}function killActiveChildren(){let t=new Map;for(let n of aK){let S=n.pid?collectDescendants(n.pid):[];t.set(n,S),signalTree(n,S,`SIGTERM`)}setTimeout(()=>{for(let n of aK){let S=new Set(n.pid?collectDescendants(n.pid):[]);for(let C of t.get(n)??[])S.add(C);signalTree(n,[...S],`SIGKILL`)}},oK).unref?.()}function assertEveryIncludeMatches(t,n){if(!n||n.length===0)return;let S=n.filter(n=>filterWorkspaces(t,{include:[n]}).length===0);if(S.length===0)return;let C=[`gjsify foreach: --include matched no workspace (${S.length} of ${n.length} pattern(s)):`];for(let n of S){C.push(` ${JSON.stringify(n)}`);let S=stripSurroundingQuotes(n);if(S!==n&&filterWorkspaces(t,{include:[S]}).length>0){C.push(` → matches as ${JSON.stringify(S)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let N=t.map(t=>t.name).filter(t=>t.toLowerCase().includes(S.replace(/\*/g,``).toLowerCase())).slice(0,3);N.length>0&&C.push(` → did you mean: ${N.join(`, `)}?`)}throw C.push(` ${t.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ge.error(C.join(`
|
|
1262
|
+
`)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(t){return t.length>=2&&(t[0]===`'`||t[0]===`"`)&&t[t.length-1]===t[0]?t.slice(1,-1):t}async function runSequential(t,n,S,C,N,F){for(let I of t)await runOne(I,n,S,!1,C,N,F)}async function runParallel(t,n,S,C,N,F,I){let H=0,W=[];for(let q=0;q<C;q++)W.push((async()=>{for(;H<t.length;)await runOne(t[H++],n,S,!0,N,F,I)})());await Promise.all(W)}async function runTopologicalParallel(t,n,S,C,N,F,I,H){let W=new Map([...buildDependencyGraph(t,{includeDev:F}).edges].map(([t,n])=>[t,new Set(n)])),q=new Map(t.map(t=>[t.name,t])),Y=t.length,X=new Set,Z=0,te=!process.stdout.isTTY||N,ne=new Map,re=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),ie=(Number.isFinite(re)&&re>0?re:20)*6e4;return new Promise((t,F)=>{let re=null,ae=Date.now(),describeInflight=()=>[...ne.entries()].map(([t,n])=>`${t} (${Math.round((Date.now()-n)/1e3)}s)`).join(`, `),failFast=t=>{re||(re=t,killActiveChildren(),setTimeout(()=>settle(),sK).unref?.())},oe=setInterval(()=>{let t=Date.now()-ae;t<3e5||ne.size===0||(ge.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(t/6e4)}min — in-flight: ${describeInflight()}`),t>=ie&&failFast(Error(`gjsify foreach: stalled — no workspace completed for ${Math.round(t/6e4)}min (override via GJSIFY_FOREACH_STALL_MINUTES); killed in-flight: ${describeInflight()}`)))},6e4);oe.unref?.();let settle=()=>{clearInterval(oe),re?F(re):t()},pump=()=>{if(!re){for(;Z<C;){let t=[...W.entries()].filter(([,t])=>[...t].every(t=>X.has(t))).map(([t])=>t);if(t.length===0)break;let C=t.sort()[0];W.delete(C),Z++,ne.set(C,Date.now()),te&&ge.error(`[gjsify foreach] start ${C} (${X.size}/${Y} done, ${Z} in flight)`),runOne(q.get(C),n,S,!0,N,I,H).then(()=>{X.add(C)}).catch(t=>{failFast(t instanceof Error?t:Error(String(t)))}).finally(()=>{Z--,ne.delete(C),ae=Date.now(),re?Z===0&&settle():W.size===0&&Z===0?settle():pump()})}W.size>0&&Z===0&&!re&&(clearInterval(oe),F(Error(`gjsify foreach --topological: stuck — workspaces ${[...W.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne(t,n,S,C,N,F,I){if(F){N&&ge.error(`[${t.name}] $ ${n} ${S.join(` `)}`),await spawnPrefixed(n,S,t.location,C?`[${t.name}] `:null);return}if(I&&I.tryRestore(t))return;let H=I?.snapshotOutputs(t),W=detectPackageManager(),q=W===`gjsify`?[`run`,n,...S]:[`run`,n,...S.length>0?[`--`,...S]:[]];N&&ge.error(`[${t.name}] $ ${W} ${q.join(` `)}`),await spawnPrefixed(W,q,t.location,C?`[${t.name}] `:null),I&&H&&I.storeAfterSuccess(t,H)}async function spawnPrefixed(t,n,S,C){let N=null,F=[];try{let I=await spawnToCompletion(t,n,{completion:`exit`,cwd:S,stdio:C?`pipe`:`inherit`,color:!0,onSpawn:t=>{N=t,aK.add(t);let n=!process.stdout.isTTY;C&&t.stdout&&t.stderr&&(F.push(prefixLines(t.stdout,process.stdout,C,n)),F.push(prefixLines(t.stderr,process.stderr,C,n)))}});for(let t of F)t();if(I.code!==0)throw Error(`${t} ${n.join(` `)} exited with code ${I.code}`)}finally{N&&aK.delete(N)}}var aK,oK,sK,cK,lK=__esmMin(()=>{_e(),hv(),sz(),o_(),GI(),qI(),iK(),cB(),TR(),fB(),hB(),aK=new Set,oK=5e3,sK=15e3,cK={command:`foreach [script] [args..]`,description:"Run a workspace script across all (or filtered) workspaces. Drop-in for `yarn workspaces foreach`: -A/--all, -p/--parallel, -t/--topological, --include, --exclude, --no-private. Pass --exec to run an arbitrary command instead of a script.",builder:t=>t.positional(`script`,{description:"Script name to run in each workspace (`run <name>`-equivalent). With --exec, the command to run instead.",type:`string`}).positional(`args`,{description:`Extra arguments forwarded to each child invocation.`,type:`string`,array:!0}).option(`all`,{description:"Include workspaces declared as `private: true`.",type:`boolean`,alias:`A`,default:!1}).option(`parallel`,{description:`Run workspaces in parallel (capped by --jobs).`,type:`boolean`,alias:`p`,default:!1}).option(`topological`,{description:`Wait for each workspace's deps to finish before starting it (production deps only).`,type:`boolean`,alias:`t`,default:!1}).option(`topological-dev`,{description:`Like --topological but also respects devDependencies (often cyclic — use sparingly).`,type:`boolean`,default:!1}).option(`include`,{description:`Glob pattern to include workspaces by name (repeatable). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async t=>{let n=findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n),C=t.exec===!0,N=t.script,F=t.args??[];if(!C){let n=doubleDashArgs(t);n.length>0&&(F=[...F,...n])}if(C){let n=doubleDashArgs(t);if(n.length>0&&(N?F=[...F,...n]:(N=n[0],F=[...F,...n.slice(1)])),!N)return ge.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(S,t.include);let I=filterWorkspaces(S,{include:t.include,exclude:t.exclude,noPrivate:t.private===!1});if(t[`with-dependencies`]===!0){let n=affectedClosure(buildDependencyGraph(S,{includeDev:t[`topological-dev`]===!0}),I.map(t=>t.name));I=filterWorkspaces(S.filter(t=>n.has(t.name)),{exclude:t.exclude,noPrivate:t.private===!1})}if(!C){if(!N)return ge.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let t=N;I=I.filter(n=>typeof(n.manifest.scripts??{})[t]==`string`)}if(typeof t.shard==`string`&&t.shard.length>0){let n=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(t.shard);if(!n)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let S=Number(n[1]),C=Number(n[2]);if(C<1||S<1||S>C)return ge.error(`gjsify foreach: invalid --shard "${t.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(C>1){let t=[...I].sort((t,n)=>t.name<n.name?-1:+(t.name>n.name));I=t.filter((t,n)=>n%C===S-1),ge.log(`gjsify foreach: shard ${S}/${C} → ${I.length} of ${t.length} workspace(s)`)}}if(I.length===0){ge.log(`gjsify foreach: no workspaces match (${C?`exec`:`script`}="${N}", include=${JSON.stringify(t.include??[])}, exclude=${JSON.stringify(t.exclude??[])})`);return}(t.topological||t[`topological-dev`])&&(I=topologicalSort(buildDependencyGraph(I,{includeDev:t[`topological-dev`]===!0})));let H=t.verbose===!0,W=N,q=t.cached??buildCacheEnabledByEnv();if(t.cached===!0&&C)return ge.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let Y=q&&!C?new BuildCacheRunner({root:n,workspaces:S,script:W,args:F,targets:I.map(t=>t.name)}):void 0,X=t.parallel===!0?cliRuntimeClosure(S):new Set,Z=X.size>0?I.filter(t=>X.has(t.name)):[],te=Z.length>0?I.filter(t=>!X.has(t.name)):I;try{if(Z.length>0){ge.error(`[gjsify foreach] serial prefix: ${Z.length} package(s) the running CLI imports — ${Z.map(t=>t.name).join(`, `)}`);for(let t of Z)ge.error(`[gjsify foreach] start ${t.name} (serial prefix)`),await runOne(t,W,F,!0,H,C,Y)}if(t.parallel&&!t.topological&&!t[`topological-dev`]){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runParallel(te,W,F,n,H,C,Y)}else if(t.parallel){let n=t.jobs&&t.jobs>0?t.jobs:cpus().length;await runTopologicalParallel(te,W,F,n,H,t[`topological-dev`]===!0,C,Y)}else await runSequential(te,W,F,H,C,Y)}catch(t){return killActiveChildren(),ge.error(t.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(t,n,S,C={}){let N=(n.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${t}/package.json`)}let F=findWorkspaceRoot(t),I=[zn(t,`node_modules`,`.bin`)];F&&F!==t&&I.push(zn(F,`node_modules`,`.bin`));let H=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},W={...process.env,...H,PATH:[...I,process.env.PATH??``].filter(Boolean).join(Jn),npm_lifecycle_event:S,npm_package_name:n.name??``,npm_package_version:n.version??``,...C.env};if(C.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let q=await spawnToCompletion(N,[],{completion:`return`,cwd:t,env:W,shell:!0,stdio:C.stdio===`inherit-stderr`?`inherit-stderr`:C.stdio===`pipe`?`pipe`:`inherit`});if(q.code!==0)throw Error(`gjsify lifecycle-script: "${S}" in ${t} exited with ${describeExit(q)}`);return!0}var uK=__esmMin(()=>{Xn(),hv(),qI()});async function packWorkspace(t,n={}){let S=zn(t,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${t}`);let C=readFileSync(S,`utf-8`),N=JSON.parse(C),F=typeof N.name==`string`?N.name:``,I=typeof N.version==`string`?N.version:`0.0.0`;if(!F)throw Error(`gjsify pack: package.json at ${t} has no "name"`);let H=n.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(t,N,S,{optional:!0,stdio:n.lifecycleStdio});let W=readFileSync(S,`utf-8`),q=W===C?N:JSON.parse(W),Y=n.skipWorkspaceRewrite?q:rewriteWorkspaceDeps(q,t),X=JSON.stringify(Y,null,indentOf(W))+`
|
|
1263
1263
|
`,Z=collectPackedFiles(t,q);assertTypeDeclarationsShipped(t,q,Z);let te=[{name:`package/`,directory:!0,mode:493}],ne=[],re=0;for(let n of Z){let S;S=n===`package.json`?new TextEncoder().encode(X):new Uint8Array(readFileSync(zn(t,n)));let C=statSync(zn(t,n)).mode&511;te.push({name:`package/${n}`,body:S,mode:C,mtime:0}),ne.push({path:n,size:S.byteLength,mode:C}),re+=S.byteLength}let ie=await gzip(createTarball(te)),ae=`${F.startsWith(`@`)?F.slice(1).replace(`/`,`-`):F}-${I}.tgz`,oe=createHash(`sha1`).update(ie).digest(`hex`),Q=`sha512-${createHash(`sha512`).update(ie).digest(`base64`)}`,se=n.destination?In(n.destination):t,ce=zn(se,ae);return n.dryRun||(mkdirSync(se,{recursive:!0}),writeFileSync(ce,ie)),{filename:ae,name:F,version:I,size:ie.byteLength,unpackedSize:re,shasum:oe,integrity:Q,entryCount:ne.length,files:ne,absolutePath:n.dryRun?null:ce}}function collectPackedFiles(t,n){let S=forceIncluded(n),C=Array.isArray(n.files)?n.files.filter(t=>typeof t==`string`):null,N=new Set;if(C)for(let n of expandFilesPatterns(t,C))N.add(n);else{let n=loadIgnore(t);for(let S of walkAll(t))n(S)||N.add(S)}for(let n of S)existsSync(zn(t,n))&&N.add(n);return[...N].sort()}function collectTypeDeclarationRefs(t){let n=new Set,add=t=>{if(typeof t!=`string`)return;let S=t.replace(/^\.\//,``);S.includes(`*`)||n.add(S)};for(let n of[`types`,`typings`])add(t[n]);let walk=t=>{if(!(!t||typeof t!=`object`)){if(Array.isArray(t)){for(let n of t)walk(n);return}for(let[n,S]of Object.entries(t))n===`types`||n===`typings`?add(S):walk(S)}};return walk(t.exports),[...n]}function assertTypeDeclarationsShipped(t,n,S){let C=new Set(S),N=collectTypeDeclarationRefs(n).filter(n=>{let S=zn(t,n);return existsSync(S)&&statSync(S).isFile()&&!C.has(n)});if(N.length===0)return;let F=typeof n.name==`string`?n.name:`(unnamed)`,I=Array.isArray(n.files)?JSON.stringify(n.files):`(none)`;throw Error(`gjsify pack: ${F} references TypeScript declaration file(s) via "exports"/"types" that exist on disk but are excluded from the tarball by the "files" allowlist (${I}):\n`+N.map(t=>` - ${t}`).join(`
|
|
1264
1264
|
`)+`
|
|
1265
|
-
Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(t){let n=new Set;n.add(`package.json`);for(let t of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])n.add(t);let S=typeof t.main==`string`?t.main:null;S&&n.add(S.replace(/^\.\//,``));let C=t.bin;if(typeof C==`string`)n.add(C.replace(/^\.\//,``));else if(C&&typeof C==`object`)for(let t of Object.values(C))typeof t==`string`&&n.add(t.replace(/^\.\//,``));return[...n]}function walkAll(t,n=``){let S=[],C=n?zn(t,n):t,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if(
|
|
1266
|
-
`);for(let n of t){let t=n.trim();!t||t.startsWith(`#`)||t.startsWith(`!`)||C.push(globToRegex(t))}}return t=>{for(let n of C)if(n.test(t))return!0;return!1}}function globToRegex(t){let n=t.replace(/^\//,``);return n=n.replace(/[.+^${}()|[\]\\]/g,`\\$&`),n=n.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),n=n.replace(/\?/g,`[^/]`),RegExp(`^${n}($|/)`)}function collectWorkspaceProtocolDeps(t){let n=[];for(let S of
|
|
1265
|
+
Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(t){let n=new Set;n.add(`package.json`);for(let t of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])n.add(t);let S=typeof t.main==`string`?t.main:null;S&&n.add(S.replace(/^\.\//,``));let C=t.bin;if(typeof C==`string`)n.add(C.replace(/^\.\//,``));else if(C&&typeof C==`object`)for(let t of Object.values(C))typeof t==`string`&&n.add(t.replace(/^\.\//,``));return[...n]}function walkAll(t,n=``){let S=[],C=n?zn(t,n):t,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if(fK.has(C.name)||C.name.startsWith(`.tsbuildinfo`))continue;let N=n?`${n}/${C.name}`:C.name;C.isDirectory()?S.push(...walkAll(t,N)):C.isFile()&&S.push(N)}return S}function expandFilesPatterns(t,n){let S=new Set,C=null;for(let N of n){let n=N.replace(/^\.\//,``).replace(/\/$/,``);if(!n)continue;if(!/[*?[\]]/.test(n)){let C=zn(t,n);if(!existsSync(C))continue;let N=statSync(C);if(N.isDirectory())for(let C of walkAll(t,n))S.add(C);else N.isFile()&&S.add(n);continue}C??=walkAll(t);let F=filesGlobToRegExp(n),I=filesGlobToRegExp(`${n}/**`);for(let t of C)(F.test(t)||I.test(t))&&S.add(t)}return[...S]}function filesGlobToRegExp(t){let n=`^`;for(let S=0;S<t.length;S++){let C=t[S];if(C===`*`)t[S+1]===`*`?(n+=`.*`,S++,t[S+1]===`/`&&S++):n+=`[^/]*`;else if(C===`?`)n+=`[^/]`;else if(C===`[`){let C=S+1,N=`[`;for(t[C]===`!`&&(N+=`^`,C++);C<t.length&&t[C]!==`]`;C++)N+=t[C];C<t.length?(n+=`${N}]`,S=C):n+=`\\[`}else".+^${}()|\\]".includes(C)?n+=`\\${C}`:n+=C}return RegExp(`${n}$`)}function loadIgnore(t){let n=zn(t,`.npmignore`),S=zn(t,`.gitignore`),C=[],N=existsSync(n)?n:existsSync(S)?S:null;if(N){let t=readFileSync(N,`utf-8`).split(`
|
|
1266
|
+
`);for(let n of t){let t=n.trim();!t||t.startsWith(`#`)||t.startsWith(`!`)||C.push(globToRegex(t))}}return t=>{for(let n of C)if(n.test(t))return!0;return!1}}function globToRegex(t){let n=t.replace(/^\//,``);return n=n.replace(/[.+^${}()|[\]\\]/g,`\\$&`),n=n.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),n=n.replace(/\?/g,`[^/]`),RegExp(`^${n}($|/)`)}function collectWorkspaceProtocolDeps(t){let n=[];for(let S of pK){let C=t[S];if(C)for(let[t,N]of Object.entries(C))typeof N==`string`&&N.startsWith(`workspace:`)&&n.push(`${S}.${t}`)}return n}function findPackWorkspaceRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=t;for(let t=0;t<12;t++){let t=zn(S,`package.json`);if(existsSync(t)&&readPackageJson$2(t)?.workspaces!==void 0)return S;let n=In(S,`..`);if(n===S)break;S=n}return null}function rewriteWorkspaceDeps(t,n){let S=findPackWorkspaceRoot(n);if(!S){let S=collectWorkspaceProtocolDeps(t);if(S.length>0)throw Error(`gjsify pack: ${String(t.name)} declares workspace: ranges (${S.join(`, `)}) but ${n} is not inside a monorepo (no ancestor package.json declares "workspaces"). A workspace: range cannot be published — replace it with a real npm range, or pack from within the monorepo.`);return t}let C=new Map;for(let t of discoverWorkspaces(S))t.name&&t.version&&C.set(t.name,t.version);let N=JSON.parse(JSON.stringify(t));for(let t of pK){let n=N[t];if(n)for(let[F,I]of Object.entries(n)){if(typeof I!=`string`||!I.startsWith(`workspace:`))continue;let H=C.get(F);if(!H)throw Error(`gjsify pack: ${N.name} declares ${I} on ${F} (${t}) but no sibling workspace with that name exists in the monorepo at ${S}`);let W=I.slice(10);W===`*`||W===``?n[F]=H:W===`^`||W===`~`?n[F]=`${W}${H}`:n[F]=W}}return N}function indentOf(t){let n=t.match(/\n([ \t]+)"/);return n?n[1]:` `}var dK,fK,pK,mK=__esmMin(()=>{af(),gl(),Xn(),oz(),GI(),qI(),KI(),uK(),dK={command:`pack [path]`,description:`Produce an npm-compatible .tgz tarball for the workspace at <path> (default: cwd). Rewrites workspace:^/~/* deps to resolved versions.`,builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`pack-destination`,{description:`Directory to write the tarball into. Default: workspace cwd.`,type:`string`}).option(`json`,{description:"Emit pack metadata as JSON on stdout (mirrors `npm pack --json`).",type:`boolean`,default:!1}).option(`dry-run`,{description:`Compute everything but do not write the .tgz.`,type:`boolean`,default:!1}).option(`ignore-scripts`,{description:"Skip the `prepack` lifecycle script before packing. Mirrors `npm pack --ignore-scripts`. Use when scripts are already run by the outer workflow.",type:`boolean`,default:!1}),handler:async t=>{let n=await packWorkspace(In(t.path??process.cwd()),{destination:t[`pack-destination`],dryRun:t[`dry-run`]===!0,lifecycleScripts:t[`ignore-scripts`]?[]:[`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`});t.json?process.stdout.write(`${JSON.stringify([n],null,2)}\n`):process.stdout.write(`${n.filename}\n`)}},fK=new Set([`.git`,`.svn`,`.hg`,`.gitignore`,`.gitattributes`,`.npmrc`,`CVS`,`.DS_Store`,`node_modules`,`.npmignore`,`package-lock.json`,`gjsify-lock.json`,`yarn.lock`,`yarn-error.log`,`.yarn`,`.pnp.cjs`,`.pnp.loader.mjs`,`tsconfig.tsbuildinfo`]),pK=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]});function parseRetryAfter(t,n=Date.now()){if(!t)return;let S=t.trim();if(/^\d+(?:\.\d+)?$/.test(S))return Math.round(Number(S)*1e3);let C=Date.parse(S);return Number.isNaN(C)?void 0:Math.max(0,C-n)}function retryDelayMs(t,n,S){let C=parseRetryAfter(S);return Math.min(C??n*2**t,gK)}async function fetchWithTransientRetry(t,n={}){let S=n.retries??5,C=n.baseMs??2e3,N=n.sleep??(t=>new Promise(n=>setTimeout(n,t))),F=n.random??Math.random;for(let I=0;;I++){let H,W;try{H=await t()}catch(t){W=t}if(H&&!isTransientStatus(H.status))return{response:H,retried:I};if(I>=S){if(H)return{response:H,retried:I};throw W}let q=H?.headers.get(`retry-after`),Y=retryDelayMs(I,C,q),X=parseRetryAfter(q)===void 0?Math.round(Y*(.5+.5*F())):Y,Z=H?`${H.status} ${H.statusText}`:`network error: ${W instanceof Error?W.message:String(W)}`;n.log?.(`transient ${Z} (attempt ${I+1}/${S+1}), retrying in ${X}ms`),await N(X)}}var hK,isTransientStatus,gK,_K=__esmMin(()=>{hK=new Set([408,425,429,500,502,503,504]),isTransientStatus=t=>hK.has(t),gK=3e4});function decodeJwtPayload(t){let n=t.split(`.`);if(n.length!==3)return null;try{let t=n[1].replace(/-/g,`+`).replace(/_/g,`/`),S=typeof atob==`function`?atob(t):Buffer.from(t,`base64`).toString(`binary`);return JSON.parse(S)}catch{return null}}function hasGithubOidcEnv(){return!!(process.env.ACTIONS_ID_TOKEN_REQUEST_URL&&process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN)}async function fetchGithubOidcToken(t,n,S={}){let C=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,N=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!C||!N)throw new OidcUnavailableError("GitHub Actions OIDC env vars (ACTIONS_ID_TOKEN_REQUEST_{URL,TOKEN}) not set. The calling workflow needs `permissions: id-token: write`.",`no-env`);let F=`${C}${C.includes(`?`)?`&`:`?`}audience=${encodeURIComponent(t)}`;n?.(`gjsify oidc: GET ${F.replace(N,`<bearer>`)}`);let I;try{({response:I}=await fetchWithTransientRetry(()=>fetch(F,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${N}`}}),{...retryOptions(S),log:n&&(t=>n(`gjsify oidc: id_token ${t}`))}))}catch(t){throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: network error — ${t instanceof Error?t.message:String(t)}`,`fetch-id-token`)}if(!I.ok){let t=await I.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${I.status} ${I.statusText} — ${t.slice(0,200)}`,`fetch-id-token`)}let H=await I.json().catch(()=>({}));if(!H.value)throw new OidcUnavailableError("GitHub OIDC response missing `value` field",`no-id-token`);return H.value}async function exchangeOidcForNpmToken(t){let{packageName:n,registry:S,idToken:C,log:N}=t,F=`${S.endsWith(`/`)?S.slice(0,-1):S}/-/npm/v1/oidc/token/exchange/package/${n.startsWith(`@`)?(()=>{let t=n.indexOf(`/`),S=n.slice(1,t),C=n.slice(t+1);return`@${encodeURIComponent(S)}%2f${encodeURIComponent(C)}`})():encodeURIComponent(n)}`;N?.(`gjsify oidc: POST ${F}`);let I,H;try{({response:I,retried:H}=await fetchWithTransientRetry(()=>fetch(F,{method:`POST`,headers:{Authorization:`Bearer ${C}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`}),{...retryOptions(t),log:N&&(t=>N(`gjsify oidc: ${t} for ${n}`))}))}catch(t){throw new OidcExchangeError(`npm OIDC token exchange network error for ${n}: ${t instanceof Error?t.message:String(t)}`,0,``,n,decodeJwtPayload(C)??void 0)}let W=await I.text().catch(()=>``);if(!I.ok)throw new OidcExchangeError(`npm OIDC token exchange failed for ${n}: ${I.status} ${I.statusText} — ${W.slice(0,300)}${H?` (after ${H} retries)`:``}`,I.status,W,n,decodeJwtPayload(C)??void 0);let q;try{q=JSON.parse(W)}catch{throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${n}: ${W.slice(0,200)}`,I.status,W,n)}if(!q.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${n}`,I.status,W,n,decodeJwtPayload(C)??void 0);return q.token}async function getNpmTrustedToken(t){let n=`npm:${new URL(t.registry).hostname}`,S=await fetchGithubOidcToken(n,t.log,t);return{token:await exchangeOidcForNpmToken({...t,idToken:S}),audience:n}}var retryOptions,OidcUnavailableError,OidcExchangeError,vK,yK=__esmMin(()=>{_K(),retryOptions=t=>({retries:t.maxRetries??5,baseMs:t.retryBaseMs??2e3,sleep:t.sleep,random:t.random}),OidcUnavailableError=class extends Error{reason;constructor(t,n){super(t),this.reason=n,this.name=`OidcUnavailableError`}},OidcExchangeError=class extends Error{status;body;packageName;claims;constructor(t,n,S,C,N){super(t),this.status=n,this.body=S,this.packageName=C,this.claims=N,this.name=`OidcExchangeError`}},vK="Trust entries are stored but the OIDC exchange is only verifiable in CI: run `gh workflow run release.yml --ref main -f verify_only=true -f skip_publish=true` and check for ✗ lines."});async function diagnose404(t){let{packageName:n,version:S,registry:C,npmrc:N}=t,F={};try{F=await whoami(C,N)}catch{return{reason:`unknown`,message:formatUnknown(n,S)}}return F.username&&F.username.length>0?{reason:`live-token-404`,username:F.username,message:formatLiveToken404(n,S,F.username)}:{reason:`dead-token`,message:formatDeadToken(n,S)}}function formatDeadToken(t,n){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`The npm token in ~/.npmrc appears to be revoked or expired (the /-/whoami probe`,`returned {} instead of {"username": "..."}). The 404 is npm's response to a PUT`,`authenticated with an invalid bearer token.`,``,`To refresh:`,` npm login`,` # or, future: gjsify login (tracked as project_gjsify_login_goal)`,``,`Then verify before publishing:`,` curl -s -H "Authorization: Bearer $(grep registry.npmjs.org ~/.npmrc | sed 's|.*=||')" \\`,` https://registry.npmjs.org/-/whoami`,` # Healthy: {"username":"<you>"}`,` # Dead: {}`].join(`
|
|
1267
1267
|
`)}function formatLiveToken404(t,n,S){return[`gjsify publish: ${t}@${n} — 404 Not Found`,``,`Authenticated as: ${S}`,``,`Your token authenticates, so this is NOT a dead-token problem. The package`,`${t} is not (yet) on npmjs.com. Two cases:`,``,` 1. First publish of a brand-new scoped package — do the one-time bootstrap`,` (see AGENTS.md > "New @gjsify/* package: first-publish + Trusted`,` Publisher bootstrap"). The npm registry can also 404 *transiently*`,` while provisioning a brand-new package: simply re-run, or do the very`," first publish with `npm publish` (then configure the Trusted Publisher)."," 2. You lack publish access to the scope — verify with `npm access ls-packages`."].join(`
|
|
1268
|
-
`)}function formatUnknown(t,n){return`gjsify publish: ${t}@${n} — 404 Not Found`}function is404DiagnosticCandidate(t){let n=t.trim();return!!(n.length===0||/^not found$/i.test(n)||/"error"\s*:\s*"Not Found"/i.test(n))}var
|
|
1269
|
-
`)}async function probePackageName(t){let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=await sendPackumentRequest({url:`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/${escapePackageName(t.name)}`,doFetch:n,probeTimeoutMs:t.probeTimeoutMs??3e4,authorization:t.authorization,nonce:`name-${Date.now()}-${++
|
|
1270
|
-
`))if(S.trim())try{let t=JSON.parse(S);(t.ev===`unserved`||t.ev===`held`||t.ev===`served`)&&n.push(t)}catch{}return n}function pinVersion(t){return/^[\^~]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(t.trim())?.[1]}async function findUnavailablePins(t){let n=[],S=new Map;for(let C of t.pins){let N=pinVersion(C.spec);if(!N){t.log?.(`gjsify publish: ${C.name}@${C.spec} names no single version — not checked for hold`);continue}let F=`${C.name}@${N}`,I=C.block===`dependencies`?F:`${F}#nowait`;if(!S.has(I)){let n=C.block===`dependencies`?t:{...t,waitBudgetMs:0};S.set(I,await judgePin(n,C.name,N))}let H=S.get(I);H&&n.push({...H,block:C.block})}return n}async function judgePin(t,n,S){let C={name:n,version:S,block:`dependencies`},N=[...t.ledger].reverse().find(t=>t.name===n&&t.version===S);if(N?.ev===`served`)return null;if(N?.ev===`unserved`&&isTerminalClass(N.cls))return{...C,cls:N.cls,detail:N.detail};if(N?.ev===`held`)return{...C,cls:`held`,detail:`was itself held — ${summariseReasons(N.reasons)}`};let F={registry:t.registry,name:n,version:S,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log},I=await verifyPublishedVersion({...F,budgetMs:
|
|
1271
|
-
`)}var
|
|
1268
|
+
`)}function formatUnknown(t,n){return`gjsify publish: ${t}@${n} — 404 Not Found`}function is404DiagnosticCandidate(t){let n=t.trim();return!!(n.length===0||/^not found$/i.test(n)||/"error"\s*:\s*"Not Found"/i.test(n))}var bK=__esmMin(()=>{xh()});function backoffFor(t){return xK[Math.min(Math.max(t,0),xK.length-1)]??3e4}function probeTimeoutFor(t,n){return Math.min(t,Math.max(n,SK))}function budgetForPayload(t,n){if(t<6e5||n<=wK)return t;let S=(n-wK)/(1024*1024);return t+Math.ceil(S)*TK}function cacheBustedUrl(t,n){return`${t}${t.includes(`?`)?`&`:`?`}__gjsify_readback=${encodeURIComponent(n)}`}async function verifyPublishedVersion(t){let{registry:n,name:S,version:C,budgetMs:N}=t,F=t.fetchImpl??((...t)=>globalThis.fetch(...t)),I=t.sleep??(t=>new Promise(n=>setTimeout(n,t))),H=t.now??(()=>Date.now()),W=t.probeTimeoutMs??3e4,q=`${n.endsWith(`/`)?n.slice(0,-1):n}/${escapePackageName(S)}`,Y=H(),X=0,Z={state:`error`,detail:`no probe was sent`};for(let n=0;X++,Z=await probeOnce({url:q,version:C,doFetch:F,probeTimeoutMs:probeTimeoutFor(W,N-(H()-Y)),authorization:t.authorization,nonce:`${Y}-${X}`}),t.log?.(`gjsify publish: read-back probe ${X} of ${S}@${C} → ${Z.state}`+(Z.state===`present`?``:` (${Z.detail})`)),Z.state!==`present`;n++){let t=N-(H()-Y);if(t<=0)break;await I(Math.min(backoffFor(n),t))}let te={attempts:X,elapsedMs:H()-Y,url:q,last:Z};if(Z.state===`present`)return{...te,confirmed:!0,verdict:`confirmed`,verdictDetail:`${q} serves ${C} with a tarball`};if(Z.state===`error`)return{...te,confirmed:!1,verdict:`unknown`,verdictDetail:`the read-back could not reach a verdict — ${Z.detail}`};let ne=await probeRegistryRecord({url:q,version:C,doFetch:F,probeTimeoutMs:W,authorization:t.authorization,nonce:`${Y}-record`});return t.log?.(`gjsify publish: read-back record probe of ${S}@${C} → ${ne.state} (${ne.detail})`),ne.state===`recorded`?{...te,confirmed:!1,verdict:`recorded-not-served`,verdictDetail:ne.detail,recordedAt:ne.recordedAt}:ne.state===`no-record`?{...te,confirmed:!1,verdict:`not-published`,verdictDetail:ne.detail}:{...te,confirmed:!1,verdict:`unknown`,verdictDetail:ne.detail}}async function probeRegistryRecord(t){let{url:n,version:S,doFetch:C,probeTimeoutMs:N}=t,F=new AbortController,I=setTimeout(()=>F.abort(),N),H;try{H=await C(cacheBustedUrl(n,t.nonce),{headers:{"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},signal:F.signal})}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record was unreadable (${t instanceof Error?t.message:String(t)})`}}finally{clearTimeout(I)}if(H.status===404)return{state:`no-record`,detail:`the registry has no packument for this name at all (404)`};if(!H.ok)return{state:`unknown`,detail:`the registry serves no ${S} and its own record answered ${H.status} ${H.statusText}`};let W;try{W=await H.json()}catch(t){return{state:`unknown`,detail:`the registry serves no ${S} and its own record is not JSON (${t instanceof Error?t.message:String(t)})`}}let q=W?.time,Y=q&&typeof q==`object`?q[S]:void 0;return typeof Y==`string`&&Y.length>0?{state:`recorded`,recordedAt:Y,detail:`the registry RECORDS ${S} at ${Y} and its install document does not serve it`}:{state:`no-record`,detail:`the registry has no record of ${S} — neither in its install document nor in its own \`time\` map`}}async function sendPackumentRequest(t){let{url:n,doFetch:S,probeTimeoutMs:C}=t,N={accept:`application/vnd.npm.install-v1+json`,"cache-control":`no-cache`,...t.authorization?{authorization:t.authorization}:{}},send=async t=>{let n=new AbortController,F=setTimeout(()=>n.abort(),C);try{return await S(t,{headers:N,signal:n.signal})}finally{clearTimeout(F)}},F;try{F=await send(cacheBustedUrl(n,t.nonce)),!F.ok&&F.status!==404&&F.status>=400&&F.status<500&&(F=await send(n))}catch(t){return{error:`request failed (${t instanceof Error?t.message:String(t)})`}}return F}async function probeOnce(t){let{version:n}=t,S=await sendPackumentRequest(t);if(`error`in S)return{state:`error`,detail:S.error};let C=S;if(C.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!C.ok)return{state:`error`,status:C.status,detail:`${C.status} ${C.statusText}`};let N;try{N=await C.json()}catch(t){let n=t instanceof Error?t.message:String(t);return{state:`error`,status:C.status,detail:`packument is not JSON (${n})`}}let F=N?.versions,I=F&&typeof F==`object`?Object.keys(F):[],H=F&&typeof F==`object`&&Object.hasOwn(F,n)?F[n]:void 0;if(!H){let t=I.length>0?I[I.length-1]:`(none)`;return{state:`absent`,status:C.status,detail:`packument carries ${I.length} version(s), newest ${t} — ${n} is not among them`}}let W=H.dist?.tarball;return typeof W!=`string`||W.length===0?{state:`absent`,status:C.status,detail:`packument has ${n} but its \`dist.tarball\` is missing`}:{state:`present`,status:C.status,tarball:W}}function formatUnconfirmedPublish(t){let{name:n,version:S,putUrl:C,putStatus:N,putStatusText:F,payloadBytes:I,readback:H}=t,W=t.claim??`accepted`,q=(H.elapsedMs/1e3).toFixed(1),Y=H.last.state===`present`?`served`:H.last.detail,X=W===`already-published`?`npm says ${S} is ALREADY PUBLISHED`:`npm ACCEPTED the upload`,Z=H.verdict===`unknown`?H.last.state===`absent`?`${X}; its install document does not serve ${S} and the registry's own record could NOT be read.`:`${X} and the read-back could NOT establish whether the registry serves it.`:H.verdict===`recorded-not-served`?`${X}; the registry RECORDS ${S} and its install document does not serve it.`:`${X} and the registry has no record of ${S}.`,te=H.verdict===`unknown`?[` This is NOT a report that the publish failed, and it is not one that it worked. The read-back`,` reached no answer it could act on, so the version may or may not be installable — confirm it`," before releasing anything that depends on it (`npm view <name>@<version> dist.tarball`)."]:H.verdict===`recorded-not-served`?[` Do NOT re-publish: the registry holds the write, so a re-run is answered 409 and changes`,` nothing. The document npm installs from is behind the registry's own record — measured on`,` the ts-for-gir v5.1.0 release, @ts-for-gir/reporter was recorded at 21:43:00.983Z and a`,` cache-busted read of its install document still did not carry 5.1.0 ~40 min later. Wait and`,` re-read; if it persists, check https://status.npmjs.org/.`]:W===`already-published`?[` A 409 is npm refusing to overwrite a version it holds, which is not the same as serving it:`,` in the v0.46.0 recovery @gjsify/node-runtime-darwin-arm64 was answered 409 at 09:48:49 and`,` the registry recorded 0.46.0 at 09:49:07, 18s later. Re-running answers the same 409, so it`," cannot fix this — wait and re-read (`npm view <name>@<version>`), or check",` https://status.npmjs.org/.`]:[` A 2xx from npm is an ACCEPTED write, not a durable one. In the v0.46.0 release 19 of 199`,` packages were recorded by the registry 56-252s after their 2xx, and ONE was never recorded`,` at all while its job stayed green — that is the failure this check exists to name.`," Re-run this publish (`--tolerate-republish` no-ops if it landed meanwhile). If it keeps",` failing, the write was rejected downstream of the 2xx: check https://status.npmjs.org/.`];return[`gjsify publish: ${n}@${S} — ${Z}`,` PUT ${C} (${I} bytes) → ${N} ${F}`,` read-back GET ${H.url} (accept: application/vnd.npm.install-v1+json, per-probe cache buster)`,` answered ${H.last.state}: ${Y}`,` after ${H.attempts} probe(s) over ${q}s`,` verdict ${H.verdict} — ${H.verdictDetail}`,...te].join(`
|
|
1269
|
+
`)}async function probePackageName(t){let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=await sendPackumentRequest({url:`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/${escapePackageName(t.name)}`,doFetch:n,probeTimeoutMs:t.probeTimeoutMs??3e4,authorization:t.authorization,nonce:`name-${Date.now()}-${++EK}`});if(`error`in S)return{state:`unknown`,detail:S.error};if(S.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!S.ok)return{state:`unknown`,status:S.status,detail:`${S.status} ${S.statusText}`};let C;try{C=await S.json()}catch(t){let n=t instanceof Error?t.message:String(t);return{state:`unknown`,status:S.status,detail:`packument is not JSON (${n})`}}let N=C?.versions,F=N&&typeof N==`object`?Object.keys(N).length:0;return F===0?{state:`unknown`,status:S.status,detail:`a 200 carrying no versions establishes nothing`}:{state:`present`,status:S.status,versions:F}}var xK,SK,CK,wK,TK,EK,DK=__esmMin(()=>{Ch(),xK=[2e3,4e3,8e3,15e3,3e4],SK=2e3,CK=6e5,wK=32*1024*1024,TK=1e4,EK=0});function collectWorkspacePins(t,n){let S=[];for(let C of OK){let N=depsOf(t,C),F=depsOf(n,C);for(let[t,n]of Object.entries(N))typeof n!=`string`||!n.startsWith(`workspace:`)||S.push({name:t,spec:F[t]??n,block:C})}return S}var OK,kK,depsOf,AK=__esmMin(()=>{OK=[`dependencies`,`optionalDependencies`,`peerDependencies`],kK=`dependencies`,depsOf=(t,n)=>{let S=t[n];return S&&typeof S==`object`?S:{}}});function statusTokenFromEnv(t){for(let n of[t.NPM_STATUS_TOKEN,t.NODE_AUTH_TOKEN]){let t=n?.trim();if(t&&!/^X+(-X+)+$/.test(t))return t}}async function fetchVersionStatus(t){if(!t.token)return{state:`unavailable`,reason:`no-credential`,detail:`the status endpoint needs an npm access token (set NPM_STATUS_TOKEN); OIDC publish tokens are not accepted`};let n=t.fetchImpl??((...t)=>globalThis.fetch(...t)),S=`${t.registry.endsWith(`/`)?t.registry.slice(0,-1):t.registry}/-/package/${escapePackageName(t.name)}/version/${encodeURIComponent(t.version)}/status`,C;try{C=await n(S,{headers:{accept:`application/json`,authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(t.probeTimeoutMs??3e4)})}catch(t){return{state:`unavailable`,reason:`error`,detail:t instanceof Error?t.message:String(t)}}if(C.status===401)return{state:`unavailable`,reason:`rejected`,detail:`401 — the token is missing, invalid or expired`};if(C.status===403)return{state:`unavailable`,reason:`not-enabled`,detail:`403 — package version status is not enabled for this package`};if(C.status===404)return{state:`unavailable`,reason:`not-found`,detail:`404 — no such version, or the token cannot see this package`};if(!C.ok)return{state:`unavailable`,reason:`error`,detail:`${C.status} ${C.statusText}`};let N;try{N=await C.json()}catch(t){return{state:`unavailable`,reason:`error`,detail:`status body is not JSON (${t instanceof Error?t.message:String(t)})`}}let F=N?.status;return typeof F!=`string`||!jK.includes(F)?{state:`unavailable`,reason:`error`,detail:`unrecognised status ${JSON.stringify(F)}`}:{state:`known`,status:F}}function isTerminalClass(t){return t!==`validating`&&t!==`published-lagging`&&t!==`unchecked`}function whyUnchecked(t){return t.reason===`no-credential`?`status endpoint not asked: no NPM_STATUS_TOKEN`:t.detail}function classifyUnserved(t,n){if(n.state===`known`)switch(n.status){case`validating`:return{cls:`validating`,detail:`npm accepted the upload and its automated review has not finished`,terminal:!1};case`staged`:return{cls:`staged`,detail:`awaiting maintainer approval on npm`,terminal:!0};case`blocked`:return{cls:`blocked`,detail:`failed npm automated validation`,terminal:!0};case`deleted`:return{cls:`deleted`,detail:`deleted on npm`,terminal:!0};case`published`:return{cls:`published-lagging`,detail:`npm reports it published; the install document does not serve it yet`,terminal:!1}}return n.reason===`not-found`?{cls:`missing`,detail:`the registry has no such version (${n.detail}); the PUT did not land`,terminal:!0}:{cls:`unchecked`,detail:`not served (read-back: ${t}); ${whyUnchecked(n)}`,terminal:!1}}function describeClass(t){switch(t){case`validating`:return`validating (npm automated review pending)`;case`staged`:return`staged (needs maintainer approval)`;case`blocked`:return`blocked (failed automated validation)`;case`deleted`:return`deleted`;case`published-lagging`:return`published, not yet served`;case`missing`:return`missing (never recorded)`;case`unchecked`:return`not served (status not checked)`}}var jK,MK=__esmMin(()=>{Ch(),jK=[`published`,`validating`,`staged`,`blocked`,`deleted`]});function appendLedger(t,n){t&&appendFileSync(t,`${JSON.stringify(n)}\n`)}function readLedger(t){if(!t||!existsSync(t))return[];let n=[];for(let S of readFileSync(t,`utf-8`).split(`
|
|
1270
|
+
`))if(S.trim())try{let t=JSON.parse(S);(t.ev===`unserved`||t.ev===`held`||t.ev===`served`)&&n.push(t)}catch{}return n}function pinVersion(t){return/^[\^~]?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(t.trim())?.[1]}async function findUnavailablePins(t){let n=[],S=new Map;for(let C of t.pins){let N=pinVersion(C.spec);if(!N){t.log?.(`gjsify publish: ${C.name}@${C.spec} names no single version — not checked for hold`);continue}let F=`${C.name}@${N}`,I=C.block===`dependencies`?F:`${F}#nowait`;if(!S.has(I)){let n=C.block===`dependencies`?t:{...t,waitBudgetMs:0};S.set(I,await judgePin(n,C.name,N))}let H=S.get(I);H&&n.push({...H,block:C.block})}return n}async function judgePin(t,n,S){let C={name:n,version:S,block:`dependencies`},N=[...t.ledger].reverse().find(t=>t.name===n&&t.version===S);if(N?.ev===`served`)return null;if(N?.ev===`unserved`&&isTerminalClass(N.cls))return{...C,cls:N.cls,detail:N.detail};if(N?.ev===`held`)return{...C,cls:`held`,detail:`was itself held — ${summariseReasons(N.reasons)}`};let F={registry:t.registry,name:n,version:S,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log},I=await verifyPublishedVersion({...F,budgetMs:PK});if(I.confirmed)return confirmedServed(t,N,n,S);let ask=()=>fetchVersionStatus({registry:t.registry,name:n,version:S,token:t.statusToken,fetchImpl:t.fetchImpl}),H=classifyUnserved(I.verdict,await ask());if(!H.terminal&&t.waitBudgetMs>0){if(I=await verifyPublishedVersion({...F,budgetMs:t.waitBudgetMs}),I.confirmed)return confirmedServed(t,N,n,S);H=classifyUnserved(I.verdict,await ask())}return{...C,cls:H.cls,detail:H.detail}}function confirmedServed(t,n,S,C){return n?.ev===`unserved`&&appendLedger(t.ledgerPath,{ev:`served`,name:S,version:C}),null}function summariseReasons(t){return t.map(t=>`${t.name}@${t.version} is ${t.cls===`held`?`held`:describeClass(t.cls)}`).join(`; `)}async function recordUnserved(t){let n=await fetchVersionStatus({registry:t.registry,name:t.name,version:t.version,token:t.statusToken,fetchImpl:t.fetchImpl}),S=classifyUnserved(t.verdict,n);return appendLedger(t.ledgerPath,{ev:`unserved`,name:t.name,version:t.version,cls:S.cls,detail:S.detail}),S}function pendingEntries(t){let n=new Map;for(let S of t)n.set(`${S.name}@${S.version}`,S);let S=[...n.values()];return{unserved:S.filter(t=>t.ev===`unserved`),held:S.filter(t=>t.ev===`held`)}}function markHeldPublished(t,n,S){[...readLedger(t)].reverse().find(t=>t.name===n&&t.version===S)?.ev===`held`&&appendLedger(t,{ev:`served`,name:n,version:S})}async function settleUnserved(t){let n=pendingEntries(t.entries).unserved.filter(t=>!isTerminalClass(t.cls));return(await Promise.all(n.map(async n=>{if((await verifyPublishedVersion({registry:t.registryFor(n.name),name:n.name,version:n.version,budgetMs:t.budgetMs,authorization:t.authorization,fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:t.log})).confirmed)return appendLedger(t.ledgerPath,{ev:`served`,name:n.name,version:n.version}),`${n.name}@${n.version}`}))).filter(t=>t!==void 0)}function renderLedgerSummary(t,n){let{unserved:S,held:C}=pendingEntries(t);if(S.length===0&&C.length===0)return;let N=[`### npm versions that were accepted but are not installable`,``];if(S.length>0){N.push(`| Package | Version | State | Detail |`,`| --- | --- | --- | --- |`);for(let t of S)N.push(`| \`${t.name}\` | ${t.version} | ${describeClass(t.cls)} | ${t.detail} |`);N.push(``)}if(C.length>0){N.push(`### Held — NOT published in this run`,``,`Each package below depends on a version npm does not serve, so publishing it would have shipped a package that cannot be installed.`,``,`| Package | Version | Because |`,`| --- | --- | --- |`);for(let t of C)N.push(`| \`${t.name}\` | ${t.version} | ${summariseReasons(t.reasons)} |`);N.push(``,"Once the dependencies above are served by npm (a `validating` version appears on its own, or is approved/released by a maintainer), publish the held set with:",``,"```sh",`gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${[...new Set(C.map(t=>t.name))].join(` `)}'`,"```"),S.some(t=>t.cls===`blocked`||t.cls===`deleted`)&&N.push(``,"A `blocked` or `deleted` version is a spent number: re-running the release cannot serve it, the package needs a version bump.")}return N.join(`
|
|
1271
|
+
`)}var NK,PK,holdsPublish,FK=__esmMin(()=>{af(),AK(),DK(),MK(),NK=3e5,PK=1,holdsPublish=t=>t.block===kK});function beginPrompt(){IK++}function endPrompt(t=defaultWrite){if(IK=Math.max(0,IK-1),IK>0||LK.length===0)return;let n=LK.splice(0,LK.length);for(let S of n)t(S)}function writeAroundPrompt(t,n=defaultWrite){if(IK>0){LK.push(t);return}n(t)}function defaultWrite(t){process.stdout.write(t)}var IK,LK,RK=__esmMin(()=>{IK=0,LK=[]});function isTtyStdin(){let t=process.stdin;return!!t.isTTY&&typeof t.setRawMode==`function`}function applyKey(t,n,S){return n===`\r`||n===`
|
|
1272
1272
|
`?{buf:t,echo:`
|
|
1273
|
-
`,done:!0,interrupt:!1}:n===
|
|
1274
|
-
`,done:!1,interrupt:!0}:n===
|
|
1275
|
-
Enter OTP: `,
|
|
1276
|
-
Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(t,n=promptLine,S={}){this.promptFn=n,this.registry=S.registry;let C=t&&t.length>0?t:void 0;C?(this.cached=C,this.registry&&writeCachedOtp(this.registry,C)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(t,n){if(n!==void 0&&this.generation>n&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(t??(this.generation>0?KK
|
|
1277
|
-
`)}return}return process.exit(1)}case`republish-tolerated`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,action:`republish-tolerated`,name:t.name,version:t.version,status:t.status,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${t.name}@${t.version} (already published, tolerated) ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`skipped-untrusted-new`:n?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:t.name,version:t.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`blocked-missing-dependency`:{let S=t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `);return n?process.stdout.write(`${JSON.stringify({ok:t.ok,action:`blocked-missing-dependency`,name:t.name,version:t.version,registry:t.registry,tolerated:t.tolerated,missing:t.missing},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (NOT published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${S})\n`),ge.error(`gjsify publish: every consumer install of ${t.name} would fail with \`npm error 404\`, on every package manager — a required edge is not skippable. Bootstrap the target first (docs/publishing.md § New \`@gjsify/*\` package), then re-run. See #1713.`),t.tolerated?void 0:process.exit(1)}case`otp-required`:return ge.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(t.error,t.name,n),process.exit(1);case`oidc-no-token`:{let S=t.error instanceof Error?t.error.message:String(t.error);return ge.error(`gjsify publish: OIDC token exchange failed for ${t.name} (${S}) and no fallback npm token is configured — refusing to publish without credentials.`),n&&process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return n?process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,status:404,diagnostic:t.diag.reason,username:t.diag.username},null,2)}\n`):process.stderr.write(`${t.diag.message}\n`),process.exit(1);case`error`:return ge.error(`gjsify publish: ${t.name}@${t.version} — ${t.status} ${t.statusText}`),ge.error(t.text),process.exit(1)}}async function packWorkspaceToBytes(t){let n=zn(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),S=await packWorkspace(t,{destination:n,dryRun:!1,lifecycleScripts:[]});if(!S.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let C=new Uint8Array(readFileSync(S.absolutePath));try{(await Promise.resolve().then(()=>(af(),nf))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(af(),nf))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=zn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(af(),nf));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(oz(),az)),H=new Uint8Array(readFileSync(C.absolutePath));N(S,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let W=await F(H);for(let t of I(W))if(t.name===`package/package.json`&&t.body)return JSON.parse(new TextDecoder().decode(t.body));return n}function buildPublishPayload(t){let{pkg:n,tag:S,access:C,tarballBytes:N,tarballUrl:F,packed:I,provenance:H}=t,W={...n,_id:`${I.name}@${I.version}`,dist:{integrity:I.integrity,shasum:I.shasum,tarball:F}};H&&(W._hasShrinkwrap=!1);let q={_id:I.name,name:I.name,description:typeof n.description==`string`?n.description:``,"dist-tags":{[S]:I.version},versions:{[I.version]:W},readme:``,_attachments:{[I.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(N),length:N.byteLength}}};return C&&(q.access=C),q}function handleOidcFailure(t,n,S){if(t instanceof OidcUnavailableError){let C=`gjsify publish: OIDC not available — ${t.message}`;S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-unavailable`,reason:t.reason,message:t.message})}\n`):process.stderr.write(`${C}\n`);return}if(t instanceof OidcExchangeError){let C=t.status===401||t.status===403?`npm rejected the OIDC exchange (${t.status}) — check that ${n} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(n)}/access pointing at this workflow.`:t.message;if(S)process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-exchange`,status:t.status,body:t.body,claims:t.claims,message:t.message})}\n`);else if(process.stderr.write(`✗ ${n}: ${C}\n`),t.body&&process.stderr.write(` ↳ npm said: ${t.body.slice(0,300)}\n`),t.claims){let n=t.claims,S=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(t=>n[t]!==void 0).map(t=>`${t}=${JSON.stringify(n[t])}`).join(`, `);S&&process.stderr.write(` ↳ JWT claims npm received: ${S}\n`)}return}let C=t instanceof Error?t.message:String(t);S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`unknown`,message:C})}\n`):process.stderr.write(`✗ ${n}: ${C}\n`)}var JK,YK=__esmMin(()=>{_e(),af(),o_(),Xn(),xW(),xh(),Ch(),pK(),vK(),yK(),EK(),kK(),PK(),jK(),DB(),qK(),VK(),gK(),JK={command:`publish [path]`,description:"Pack + upload the workspace at <path> (default: cwd) to its npm registry. Drop-in for `npm publish` with workspace:^ rewrite handled automatically.",builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`tag`,{description:`Dist-tag to publish under. Default: latest.`,type:`string`,default:`latest`}).option(`access`,{description:"Package access — `public` or `restricted` (required for first publish of scoped packages on the public registry).",type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as the `npm-otp` header. Required for manual publishes from a 2FA-enabled account.",type:`string`}).option(`tolerate-republish`,{description:'Treat "version already published" as success — covers both classic 409 Conflict and the npm OIDC-path 403 Forbidden + `"previously published"` body shape. Matches yarn `--tolerate-republish`.',type:`boolean`,default:!1}).option(`tolerate-untrusted-new`,{description:'Skip (exit 0) when OIDC token exchange returns `package not found` AND no fallback token is configured — i.e. a never-before-published `@scope/<name>` whose Trusted Publisher entry hasn\'t been set up on npmjs.com yet. Without this flag, one un-bootstrapped new package breaks the entire serialized `gjsify foreach publish` loop. Pair with `--tolerate-republish` in CI release workflows so a fresh-merged package gracefully skips its first CI publish, leaving the manual-bootstrap step to a maintainer (see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap").',type:`boolean`,default:!1}).option(`verify-timeout`,{description:"Seconds to keep asking the registry for the just-published version before giving up. npm answers 2xx to a write it has only ACCEPTED: in the v0.46.0 release 19 of 199 packages were recorded 56-252s after their 2xx and one was never recorded at all, so a shorter window turns normal queueing into a false red. `0` disables the read-back — for a registry with no packument read path; the success line then reads `UNVERIFIED` and says so, because a publish nothing checked must never look like one that was checked.",type:`number`,default:SK/1e3}).option(`verify-defer`,{description:"Report an unconfirmed read-back and exit 0 instead of 1. ONLY for a caller that re-checks the same set afterwards — `gjsify run npm:publish` passes it because `scripts/verify-published-closure.mjs` sweeps the whole roster at the end of release.yml. Everywhere else an unconfirmed publish must fail the job that made it.",type:`boolean`,default:!1}).option(`hold-timeout`,{description:'Seconds to wait for an intra-repo dependency pin whose exact version the registry does not serve (yet) before HOLDING this package instead of publishing it. A version npm accepted but never serves (status "validating") would make every dependent uninstallable; the write lag measured on v0.46.0 reaches 252s, hence the default. `0` probes once and holds without waiting. A hold exits 1, or 0 under `--verify-defer`.',type:`number`,default:MK/1e3}).option(`report-ledger`,{description:"Print the job-summary markdown for the publish ledger named by $GJSIFY_PUBLISH_LEDGER (versions npm accepted but does not serve, packages held because of them, the recovery command) and exit. Pair with `--ref <tag>`.",type:`boolean`,default:!1}).option(`fail-on-unsettled`,{description:`With --report-ledger: exit 1 when any package is still HELD or any accepted version is still unserved, naming them and the recovery command. The end-of-sweep gate: a sweep that left something behind must be red, not a warning.`,type:`boolean`,default:!1}).option(`held-names`,{description:`Print, one per line, the packages the ledger shows HELD and not yet published, and exit. Feeds the held-package second pass (.github/scripts/retry-held-publish.sh).`,type:`boolean`,default:!1}).option(`settle-ledger`,{description:`Wait up to --settle-timeout for every version the ledger records as accepted-but-unserved to be served (the longer read-back the sweep defers), record each as served, and exit.`,type:`boolean`,default:!1}).option(`settle-timeout`,{description:`With --settle-ledger: seconds to wait. Versions poll concurrently, so this is the longest lag tolerated, not a sum. Default 600 (the fatal read-back default; measured lags reach 368 s).`,type:`number`,default:SK/1e3}).option(`ref`,{description:`With --report-ledger: the git ref to put in the printed recovery command.`,type:`string`}).option(`provenance`,{description:`Pass-through flag — recorded in the payload but no signing happens (gjsify doesn't ship a sigstore signer yet).`,type:`boolean`,default:!1}).option(`dry-run`,{description:`Pack only, do not PUT.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit publish metadata as JSON on stdout.`,type:`boolean`,default:!1}).option(`trusted`,{description:"Authenticate via npm Trusted Publishing (OIDC): exchange the GitHub Actions id-token for a short-lived npm token. Pass `--trusted` to force this mode (errors if env vars missing). Omit to auto-detect: OIDC is used iff `ACTIONS_ID_TOKEN_REQUEST_URL`+`_TOKEN` are set AND no `_authToken` is present in the resolved npmrc; otherwise the long-lived token path is used. Requires the calling workflow to declare `permissions: id-token: write` AND the target package to have a Trusted Publisher configured on npmjs.com.",type:`boolean`,default:void 0}).option(`check-trusted`,{description:"Diagnostic mode: perform the OIDC id-token request + npm token exchange, report success/failure, then exit WITHOUT publishing. Useful as a bulk-verifier (e.g. via `gjsify foreach publish --check-trusted`) to confirm Trusted Publisher config across many packages.",type:`boolean`,default:!1}),handler:async t=>{let n=In(t.path??process.cwd()),S=t.tag??`latest`,C=t.access,N=t.otp,F=t[`tolerate-republish`]===!0,I=t[`tolerate-untrusted-new`]===!0,H=t[`verify-timeout`]??6e5/1e3;if(!Number.isFinite(H)||H<0)return ge.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`verify-timeout`])}`),process.exit(2);let W=Math.round(H*1e3),q=t[`verify-defer`]===!0,Y=t.provenance===!0,X=t[`dry-run`]===!0,Z=t[`check-trusted`]===!0,te=t.trusted,ne=!!process.env.GJSIFY_PUBLISH_DEBUG,re=process.env.GJSIFY_PUBLISH_LEDGER;if(t[`held-names`]===!0){for(let t of pendingEntries(readLedger(re)).held)process.stdout.write(`${t.name}\n`);return}if(t[`settle-ledger`]===!0){let n=t[`settle-timeout`]??6e5/1e3;if(!Number.isFinite(n)||n<0)return ge.error(`gjsify publish: --settle-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`settle-timeout`])}`),process.exit(2);let S=await loadNpmrc(process.cwd()),C=await settleUnserved({entries:readLedger(re),ledgerPath:re,registryFor:t=>(process.env.npm_config_registry??registryFor(t,S)??ph).replace(/\/$/,``),budgetMs:Math.max(1,Math.round(n*1e3)),log:ne?t=>ge.error(t):void 0});for(let t of C)process.stdout.write(`served after settling: ${t}\n`);return}if(t[`report-ledger`]===!0){let n=readLedger(re),S=renderLedgerSummary(n,t.ref??`<tag>`);if(S&&process.stdout.write(`${S}\n`),t[`fail-on-unsettled`]===!0){let{unserved:S,held:C}=pendingEntries(n),N=[...new Set([...C,...S].map(t=>t.name))];if(N.length>0){let n=t.ref??`<tag>`;return ge.error(`gjsify publish: ${C.length} package(s) still HELD and ${S.length} version(s) still unserved after the second pass: ${N.join(` `)}\n recover: re-run THIS run (\`gh run rerun <run-id>\` — keeps the version; never a new dispatch on the next channel, which mints a new one), or for a release: gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${N.join(` `)}'`),process.exit(1)}}return}let ie=t[`hold-timeout`]??3e5/1e3;if(!Number.isFinite(ie)||ie<0)return ge.error(`gjsify publish: --hold-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`hold-timeout`])}`),process.exit(2);if(Y&&ge.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Z){let S=zn(n,`package.json`),C=JSON.parse(readFileSync(S,`utf-8`));if(typeof C.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${S} has no \`name\` field\n`),process.exit(2);if(C.private===!0){let n={ok:!0,action:`check-trusted`,name:C.name,skipped:`private`};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`- ${C.name}: skipped (private package)\n`);return}let N=await loadNpmrc(n),F=process.env.npm_config_registry??registryFor(C.name,N)??ph;try{await getNpmTrustedToken({packageName:C.name,registry:F,log:ne?t=>ge.error(t):void 0});let n={ok:!0,action:`check-trusted`,name:C.name,registry:F};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`✓ ${C.name}: trusted publisher OK\n`);return}catch(n){handleOidcFailure(n,C.name,t.json===!0);return}}if(X){let S=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`}),C={ok:!0,action:`dry-run`,name:S.name,version:S.version,filename:S.filename,size:S.size,shasum:S.shasum,integrity:S.integrity};t.json?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${S.name}@${S.version} (dry-run, ${S.size} bytes, ${S.entryCount} files)\n`);return}let ae=!!(process.stdin.isTTY&&process.stdout.isTTY),oe=await loadNpmrc(n),Q;try{Q=JSON.parse(readFileSync(zn(n,`package.json`),`utf-8`)).name}catch{}let se=process.env.npm_config_registry??(Q?registryFor(Q,oe):void 0)??oe.registry??ph,ce=new OtpProvider(N,ae?promptLine:async()=>``,{registry:se});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:ce,seedOtpFirst:N!==void 0,verifyBudgetMs:W,holdWaitMs:Math.min(Math.round(ie*1e3),remainingHoldDeadlineMs())}),t.json===!0,q)}}});function buildTree(t){let n={name:`#root`,attrs:{},nodes:[]},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)t.nodes.push(n.text);else if(n.kind===`open`){let C={name:normName(n.name),attrs:n.attributes,nodes:[]};t.nodes.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function inlineMarkdown(t){let n=``;for(let S of t.nodes){if(typeof S==`string`){n+=S;continue}if(isTranslation(S))continue;let t=inlineMarkdown(S),C=XK[S.name];C===void 0?S.name===`a`&&S.attrs.href?n+=`[${t}](${S.attrs.href})`:n+=t:n+=t.trim()===``?t:`${C}${t.trim()}${C}`}return n}function parseBlocks(t){let n=[];for(let S of elements(t))if(!isTranslation(S)){if(S.name===`p`){let t=clean(inlineMarkdown(S));t&&n.push({p:t})}else if(S.name===`ul`||S.name===`ol`){let t=elements(S,`li`).filter(t=>!isTranslation(t)).map(t=>clean(inlineMarkdown(t))).filter(Boolean);t.length&&n.push({ul:t})}}return n}function parseMetainfoReleases(t){let n=elements(buildTree(t),`component`)[0];if(!n)throw Error(`metainfo root must be <component>`);let S=elements(n,`releases`)[0];return S?elements(S,`release`).map(t=>{let n=t.attrs.timestamp,S=t.attrs.date??(n?new Date(Number(n)*1e3).toISOString().slice(0,10):``),C=elements(t,`description`).find(t=>!isTranslation(t)),N=C?parseBlocks(C):[];return{version:t.attrs.version??``,date:S,...N.length?{description:N}:{}}}):[]}var normName,elements,isTranslation,XK,clean,ZK=__esmMin(()=>{Ye(),normName=t=>t.startsWith(`_`)?t.slice(1):t,elements=(t,n)=>t.nodes.filter(t=>typeof t!=`string`&&(n===void 0||t.name===n)),isTranslation=t=>t.attrs[`xml:lang`]!==void 0,XK={em:`*`,i:`*`,strong:`**`,b:`**`,code:"`",tt:"`"},clean=t=>t.replace(/\s+/g,` `).trim()});function descriptionToMarkdown(t){let n=typeof t==`string`?stringToBlocks(t):t,S=[];for(let t of n)if(`p`in t){let n=t.p.trim().replace(/\s+/g,` `);n&&S.push(n)}else{let n=t.ul.map(t=>(typeof t==`string`?t:t.item).trim()).filter(Boolean);n.length&&S.push(n.map(t=>`- ${t}`).join(`
|
|
1273
|
+
`,done:!0,interrupt:!1}:n===zK?{buf:t,echo:`
|
|
1274
|
+
`,done:!1,interrupt:!0}:n===BK||n===VK?t.length>0?{buf:t.slice(0,-1),echo:`\b \b`,done:!1,interrupt:!1}:{buf:t,echo:``,done:!1,interrupt:!1}:n>=` `?{buf:t+n,echo:S?`*`:n,done:!1,interrupt:!1}:{buf:t,echo:``,done:!1,interrupt:!1}}async function runRawSession(t){let n=process.stdin,S=process.stdout,C=null,cleanup=()=>{n.removeListener(`data`,onData);try{n.setRawMode(!1)}catch{}typeof n.pause==`function`&&n.pause()},onData=t=>{let n=typeof t==`string`?t:t.toString(`utf-8`);for(let t of n){if(!C)continue;let n=applyKey(C.buf,t,C.mask);if(C.buf=n.buf,n.echo&&S.write(n.echo),n.interrupt)return cleanup(),process.exit(130);if(n.done){let{resolve:t}=C;C=null,t(n.buf)}}};n.setRawMode(!0),typeof n.resume==`function`&&n.resume(),n.setEncoding(`utf-8`),n.on(`data`,onData);let read=(t,n)=>new Promise(N=>{beginPrompt(),S.write(t),C={mask:n,buf:``,resolve:t=>{endPrompt(),N(t)}}});try{return await t(read)}finally{cleanup()}}function readLine(){return new Promise(t=>{let n=``,onData=S=>{n+=typeof S==`string`?S:S.toString(`utf-8`);let C=n.search(/[\r\n]/);C>=0&&(cleanup(),t(n.slice(0,C)))},onEnd=()=>{cleanup(),t(n.replace(/\r$/,``).trim())},cleanup=()=>{process.stdin.removeListener(`data`,onData),process.stdin.removeListener(`end`,onEnd)};process.stdin.setEncoding(`utf-8`),typeof process.stdin.isPaused==`function`&&process.stdin.isPaused()&&process.stdin.resume(),process.stdin.on(`data`,onData),process.stdin.once(`end`,onEnd)})}async function promptLine(t){if(!isTtyStdin()){beginPrompt(),process.stdout.write(t);try{return await readLine()}finally{endPrompt()}}return runRawSession(n=>n(t,!1))}async function promptCredentials(t){if(!isTtyStdin()){let n=t;n||=(process.stdout.write(`Username: `),await readLine()),process.stdout.write(`Password: `);let S=await readLine();return{username:n,password:S}}return runRawSession(async n=>({username:t??await n(`Username: `,!1),password:await n(`Password: `,!0)}))}var zK,BK,VK,HK=__esmMin(()=>{RK(),zK=``,BK=``,VK=`\b`});function isOtpCacheEnabled(){let t=process.env[UK];return!(t===`1`||t===`true`||t===`yes`)}function normalizeRegistry(t){return t.endsWith(`/`)?t.slice(0,-1):t}function cacheBaseDir(t){if(t?.dir)return t.dir;let n=process.env.XDG_RUNTIME_DIR;return zn(n&&n.length>0?n:tmpdir(),WK)}function cacheFileFor(t,n){let S=normalizeRegistry(t).replace(/[^a-zA-Z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120);return zn(cacheBaseDir(n),`otp-${S||`default`}.json`)}function readCachedOtp(t,n){if(!isOtpCacheEnabled())return;let S=n?.now??Date.now(),C=cacheFileFor(t,n);try{if(!existsSync(C))return;let n=JSON.parse(readFileSync(C,`utf8`));if(!n||typeof n.otp!=`string`||typeof n.expiresAt!=`number`){deleteCacheFile(C);return}if(n.registry!==normalizeRegistry(t))return;if(S>=n.expiresAt){deleteCacheFile(C);return}return n.otp.length>0?n.otp:void 0}catch{deleteCacheFile(C);return}}function writeCachedOtp(t,n,S){if(!isOtpCacheEnabled()||!n||n.length===0)return;let C=S?.now??Date.now(),N=S?.ttlMs??3e4;try{mkdirSync(cacheBaseDir(S),{recursive:!0,mode:448});let F=cacheFileFor(t,S),I={otp:n,expiresAt:C+N,registry:normalizeRegistry(t)};writeFileSync(F,JSON.stringify(I),{mode:384}),chmodSync(F,384)}catch{}}function clearCachedOtp(t,n){deleteCacheFile(cacheFileFor(t,n))}function deleteCacheFile(t){try{existsSync(t)&&rmSync(t,{force:!0})}catch{}}var UK,WK,GK=__esmMin(()=>{af(),o_(),Xn(),UK=`GJSIFY_NO_OTP_CACHE`,WK=`gjsify-otp`});async function isOtpChallenge(t){if(t.status!==401)return!1;if((t.headers.get(`www-authenticate`)??``).toLowerCase().includes(`otp`))return!0;let n=await t.clone().text().catch(()=>``);return/one-time pass/i.test(n)||/\bEOTP\b/.test(n)}async function withOtpRetry(t,n,S={}){let C=S.maxPrompts??2,N=S.question,F=n.current(),I=S.seedFirstAttempt===!0&&F!==void 0,H=n.epoch(),W=await t(I?F:void 0);if(!await isOtpChallenge(W))return W;if(I&&n.invalidate(H),!I&&n.current()!==void 0){if(H=n.epoch(),W=await t(n.current()),!await isOtpChallenge(W))return W;n.invalidate(H)}for(let S=0;S<C;S++){let S=await n.refresh(N,H);if(!S||(H=n.epoch(),W=await t(S),!await isOtpChallenge(W)))return W;n.invalidate(H)}return W}var KK,qK,OtpProvider,JK=__esmMin(()=>{HK(),GK(),KK=`This operation requires a one-time password.
|
|
1275
|
+
Enter OTP: `,qK=`The previous one-time password is no longer valid (npm codes last about 30 seconds).
|
|
1276
|
+
Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(t,n=promptLine,S={}){this.promptFn=n,this.registry=S.registry;let C=t&&t.length>0?t:void 0;C?(this.cached=C,this.registry&&writeCachedOtp(this.registry,C)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(t,n){if(n!==void 0&&this.generation>n&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(t??(this.generation>0?qK:KK));try{return await this.pending}finally{this.pending=void 0}}async promptOnce(t){let n=(await this.promptFn(t)).trim();return n&&(this.cached=n,this.generation++,this.registry&&writeCachedOtp(this.registry,n)),n}invalidate(t){t!==void 0&&this.generation!==t||(this.cached=void 0,this.registry&&clearCachedOtp(this.registry))}}});function remainingHoldDeadlineMs(){let t=Number(process.env.GJSIFY_HOLD_DEADLINE);return Number.isFinite(t)&&t>0?Math.max(0,t-Date.now()):1/0}function acceptsRepublish(t,n,S,C){return(t===409||t===403&&/previously published/i.test(n))&&(S||C)}async function publishWorkspace(t){let{wsDir:n,tag:S,access:C,provenance:N,tolerate:F,tolerateUntrustedNew:I,trustedFlag:H,verbose:W,json:q,otpProvider:Y}=t,X=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:q?`inherit-stderr`:`inherit`}),Z=await packWorkspaceToBytes(n),te=readFileSync(zn(n,`package.json`),`utf-8`),ne=JSON.parse(te),re=await loadRewrittenManifest(n,ne),ie=await loadNpmrc(n),ae=t.registry??process.env.npm_config_registry??registryFor(X.name,ie)??ph,oe=ae.endsWith(`/`)?ae.slice(0,-1):ae,Q=`${oe}/${escapePackageName(X.name)}`,se=`${X.name.includes(`/`)?X.name.slice(X.name.indexOf(`/`)+1):X.name}-${X.version}.tgz`,ce=buildPublishPayload({pkg:re,tag:S,access:C,tarballBytes:Z,tarballUrl:`${oe}/${X.name}/-/${se}`,packed:{...X,wireFilename:se},provenance:N}),le=buildPublishHeaders(Q,{npmrc:ie}),ue=new Set(t.assumePresent??[]),de=collectWorkspacePins(ne,re).filter(t=>!ue.has(t.name));if(de.length>0){let t=await Promise.all(de.map(async t=>({pin:t,presence:await probePackageName({registry:ae,name:t.name,authorization:le.authorization})}))),n=[];for(let{pin:S,presence:C}of t){if(C.state===`present`)continue;let t=`${S.block}.${S.name}@${S.spec}`;if(C.state===`unknown`){ge.error(`gjsify publish: could not establish whether ${S.name} exists (${C.detail}) — not blocking on ${t}`);continue}if(S.block!==`dependencies`){ge.error(`gjsify publish: ${t} names a package ${ae} does not have — npm installs around it, Yarn (\`YN0035\`) does not`);continue}n.push(S)}if(n.length>0)return{ok:I,action:`blocked-missing-dependency`,name:X.name,version:X.version,registry:ae,tolerated:I,missing:n}}let fe=process.env.GJSIFY_PUBLISH_LEDGER;if(de.length>0){let n=await findUnavailablePins({registry:oe,pins:de,ledger:readLedger(fe),ledgerPath:fe,authorization:le.authorization,statusToken:statusTokenFromEnv(process.env),waitBudgetMs:t.holdWaitMs??3e5,log:W?t=>ge.error(t):void 0});for(let t of n.filter(t=>!holdsPublish(t)))ge.error(`gjsify publish: ${t.block}.${t.name}@${t.version} is not served (${t.detail}) — optional edge, publishing anyway`);let S=n.filter(holdsPublish);if(S.length>0)return appendLedger(fe,{ev:`held`,name:X.name,version:X.version,reasons:S}),{ok:!1,action:`held-unpublished-dependency`,name:X.name,version:X.version,registry:oe,reasons:S}}let pe=H===!0||H===void 0&&hasGithubOidcEnv()&&!process.env.NODE_AUTH_TOKEN,me=`token`;if(pe)try{let{token:t,audience:n}=await getNpmTrustedToken({packageName:X.name,registry:ae,log:W?t=>ge.error(t):void 0});le.authorization=`Bearer ${t}`,me=`oidc`,W&&ge.error(`gjsify publish: OIDC token obtained (audience=${n})`)}catch(t){if(t instanceof OidcExchangeError&&t.status===404&&/package not found/i.test(t.body)&&I)return{ok:!0,action:`skipped-untrusted-new`,name:X.name,version:X.version};if(H===!0)return{ok:!1,action:`oidc-failed`,name:X.name,version:X.version,error:t};if(!le.authorization)return{ok:!1,action:`oidc-no-token`,name:X.name,version:X.version,error:t};if(W){let n=t instanceof Error?t.message:String(t);ge.error(`gjsify publish: OIDC auto-detect failed (${n}) — falling back to token auth`)}}W&&(ge.error(`gjsify publish: PUT ${Q} (${X.name}@${X.version})`),ge.error(` auth-mode: ${me}`),ge.error(` authorization: ${le.authorization?`(set)`:`(none)`}`),ge.error(` payload size: ${JSON.stringify(ce).length} bytes`));let he=JSON.stringify(ce),_e=!1,doPut=async n=>{let S={...le};n&&(S[`npm-otp`]=n,S[`npm-auth-type`]=`legacy`);let{response:C,retried:N}=await fetchWithTransientRetry(()=>fetch(Q,{method:`PUT`,headers:S,body:he}),{log:t=>ge.error(`gjsify publish: PUT ${X.name}@${X.version}: ${t}`),...t.putRetry});return N>0&&(_e=!0),C},ve=await withOtpRetry(doPut,Y,{seedFirstAttempt:t.seedOtpFirst});if(W){ge.error(` response: ${ve.status} ${ve.statusText}`);let t=await ve.clone().text().catch(()=>``);t&&ge.error(` body: ${t.slice(0,300)}`)}let readBack=async()=>{let n=t.verifyBudgetMs??6e5;if(n<=0)return;let S=budgetForPayload(n,he.length);return verifyPublishedVersion({registry:oe,name:X.name,version:X.version,budgetMs:S,authorization:le.authorization,log:W?t=>ge.error(t):void 0})};if(await isOtpChallenge(ve))return{ok:!1,action:`otp-required`,name:X.name,version:X.version,status:ve.status};if(ve.ok){let t=await readBack();return t?.confirmed&&W&&ge.error(` read-back: confirmed after ${t.attempts} probe(s) in ${t.elapsedMs} ms`),t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`accepted`,name:X.name,version:X.version,registry:oe,putStatus:ve.status,putStatusText:ve.statusText,putUrl:Q,payloadBytes:he.length,readback:t,classification:await recordUnserved({ledgerPath:fe,registry:oe,name:X.name,version:X.version,verdict:t.verdict,statusToken:statusTokenFromEnv(process.env)})}:(markHeldPublished(fe,X.name,X.version),{ok:!0,action:`published`,name:X.name,version:X.version,filename:X.filename,size:X.size,integrity:X.integrity,tag:S,registry:oe,readback:t})}let ye=await ve.text().catch(()=>`<no body>`);if(acceptsRepublish(ve.status,ye,F,_e)){let t=await readBack();return t&&!t.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`already-published`,name:X.name,version:X.version,registry:oe,putStatus:ve.status,putStatusText:ve.statusText,putUrl:Q,payloadBytes:he.length,readback:t,classification:await recordUnserved({ledgerPath:fe,registry:oe,name:X.name,version:X.version,verdict:t.verdict,statusToken:statusTokenFromEnv(process.env)})}:(markHeldPublished(fe,X.name,X.version),{ok:!0,action:`republish-tolerated`,name:X.name,version:X.version,status:ve.status,registry:oe,readback:t})}if(ve.status===404&&me===`token`&&is404DiagnosticCandidate(ye)){let t=await diagnose404({packageName:X.name,version:X.version,registry:oe,npmrc:ie});if(t.reason!==`unknown`)return{ok:!1,action:`diagnostic`,name:X.name,version:X.version,status:404,diag:t}}return{ok:!1,action:`error`,name:X.name,version:X.version,status:ve.status,statusText:ve.statusText,text:ye}}function describeVerification(t,n){if(!t?.confirmed)return{verified:!1,clause:`(UNVERIFIED — read-back disabled by --verify-timeout 0)`,json:null};let S=(t.elapsedMs/1e3).toFixed(1);return{verified:!0,clause:`(verified on ${n} — ${t.attempts} probe(s), ${S}s)`,json:{registry:n,verdict:t.verdict,probes:t.attempts,elapsedMs:t.elapsedMs,tarball:t.last.state===`present`?t.last.tarball:null}}}function warnUnverified(t,n,S){process.env.GITHUB_ACTIONS&&process.stderr.write(`::warning title=Publish unverified::${t}@${n} was published with the read-back disabled (--verify-timeout 0) — nothing confirmed that ${S} serves it\n`)}function reportPublishOutcome(t,n,S=!1){switch(t.action){case`published`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,name:t.name,version:t.version,filename:t.filename,size:t.size,integrity:t.integrity,tag:t.tag,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${t.name}@${t.version} ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`held-unpublished-dependency`:{let C=summariseReasons(t.reasons);return n?process.stdout.write(`${JSON.stringify({ok:!1,action:`held-unpublished-dependency`,name:t.name,version:t.version,registry:t.registry,reasons:t.reasons,deferred:S},null,2)}\n`):process.stderr.write(`~ ${t.name}@${t.version} (HELD — not published: ${C})\n`),process.env.GITHUB_ACTIONS&&process.stderr.write(`::warning title=Package held::${t.name}@${t.version} was NOT published: ${C}\n`),S?void 0:process.exit(1)}case`publish-unconfirmed`:{let C=`${formatUnconfirmedPublish(t)}\n state: ${describeClass(t.classification.cls)} — ${t.classification.detail}`;if(n?process.stdout.write(`${JSON.stringify({ok:!1,action:`publish-unconfirmed`,name:t.name,version:t.version,registry:t.registry,claim:t.claim,putStatus:t.putStatus,probes:t.readback.attempts,elapsedMs:t.readback.elapsedMs,readbackUrl:t.readback.url,readbackState:t.readback.last.state,verdict:t.readback.verdict,verdictDetail:t.readback.verdictDetail,recordedAt:t.readback.recordedAt??null,deferred:S,class:t.classification.cls,classDetail:t.classification.detail},null,2)}\n`):process.stderr.write(`${C}\n`),S){if(process.env.GITHUB_ACTIONS){let n=t.claim===`already-published`?`was reported already published`:`was accepted`;process.stderr.write(`::warning title=Publish unconfirmed::${t.name}@${t.version} ${n} (HTTP ${t.putStatus}) but did not resolve on ${t.registry} within ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}; ${describeClass(t.classification.cls)}] — the release-closure job must confirm it
|
|
1277
|
+
`)}return}return process.exit(1)}case`republish-tolerated`:{let S=describeVerification(t.readback,t.registry),C={ok:!0,action:`republish-tolerated`,name:t.name,version:t.version,status:t.status,registry:t.registry,verified:S.verified,verification:S.json};n?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${t.name}@${t.version} (already published, tolerated) ${S.clause}\n`),S.verified||warnUnverified(t.name,t.version,t.registry);return}case`skipped-untrusted-new`:n?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:t.name,version:t.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`blocked-missing-dependency`:{let S=t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `);return n?process.stdout.write(`${JSON.stringify({ok:t.ok,action:`blocked-missing-dependency`,name:t.name,version:t.version,registry:t.registry,tolerated:t.tolerated,missing:t.missing},null,2)}\n`):process.stdout.write(`~ ${t.name}@${t.version} (NOT published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${S})\n`),ge.error(`gjsify publish: every consumer install of ${t.name} would fail with \`npm error 404\`, on every package manager — a required edge is not skippable. Bootstrap the target first (docs/publishing.md § New \`@gjsify/*\` package), then re-run. See #1713.`),t.tolerated?void 0:process.exit(1)}case`otp-required`:return ge.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(t.error,t.name,n),process.exit(1);case`oidc-no-token`:{let S=t.error instanceof Error?t.error.message:String(t.error);return ge.error(`gjsify publish: OIDC token exchange failed for ${t.name} (${S}) and no fallback npm token is configured — refusing to publish without credentials.`),n&&process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return n?process.stdout.write(`${JSON.stringify({ok:!1,name:t.name,version:t.version,status:404,diagnostic:t.diag.reason,username:t.diag.username},null,2)}\n`):process.stderr.write(`${t.diag.message}\n`),process.exit(1);case`error`:return ge.error(`gjsify publish: ${t.name}@${t.version} — ${t.status} ${t.statusText}`),ge.error(t.text),process.exit(1)}}async function packWorkspaceToBytes(t){let n=zn(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),S=await packWorkspace(t,{destination:n,dryRun:!1,lifecycleScripts:[]});if(!S.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let C=new Uint8Array(readFileSync(S.absolutePath));try{(await Promise.resolve().then(()=>(af(),nf))).rmSync(S.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(af(),nf))).rmdirSync(n)}catch{}return C}async function loadRewrittenManifest(t,n){let S=zn(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),C=await packWorkspace(t,{destination:S,dryRun:!1}),{rmSync:N}=await Promise.resolve().then(()=>(af(),nf));if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:F,parseTar:I}=await Promise.resolve().then(()=>(oz(),az)),H=new Uint8Array(readFileSync(C.absolutePath));N(S,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let W=await F(H);for(let t of I(W))if(t.name===`package/package.json`&&t.body)return JSON.parse(new TextDecoder().decode(t.body));return n}function buildPublishPayload(t){let{pkg:n,tag:S,access:C,tarballBytes:N,tarballUrl:F,packed:I,provenance:H}=t,W={...n,_id:`${I.name}@${I.version}`,dist:{integrity:I.integrity,shasum:I.shasum,tarball:F}};H&&(W._hasShrinkwrap=!1);let q={_id:I.name,name:I.name,description:typeof n.description==`string`?n.description:``,"dist-tags":{[S]:I.version},versions:{[I.version]:W},readme:``,_attachments:{[I.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(N),length:N.byteLength}}};return C&&(q.access=C),q}function handleOidcFailure(t,n,S){if(t instanceof OidcUnavailableError){let C=`gjsify publish: OIDC not available — ${t.message}`;S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-unavailable`,reason:t.reason,message:t.message})}\n`):process.stderr.write(`${C}\n`);return}if(t instanceof OidcExchangeError){let C=t.status===401||t.status===403?`npm rejected the OIDC exchange (${t.status}) — check that ${n} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(n)}/access pointing at this workflow.`:t.message;if(S)process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`oidc-exchange`,status:t.status,body:t.body,claims:t.claims,message:t.message})}\n`);else if(process.stderr.write(`✗ ${n}: ${C}\n`),t.body&&process.stderr.write(` ↳ npm said: ${t.body.slice(0,300)}\n`),t.claims){let n=t.claims,S=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(t=>n[t]!==void 0).map(t=>`${t}=${JSON.stringify(n[t])}`).join(`, `);S&&process.stderr.write(` ↳ JWT claims npm received: ${S}\n`)}return}let C=t instanceof Error?t.message:String(t);S?process.stdout.write(`${JSON.stringify({ok:!1,name:n,error:`unknown`,message:C})}\n`):process.stderr.write(`✗ ${n}: ${C}\n`)}var YK,XK=__esmMin(()=>{_e(),af(),o_(),Xn(),xW(),xh(),Ch(),mK(),yK(),bK(),DK(),AK(),FK(),MK(),DB(),JK(),HK(),_K(),YK={command:`publish [path]`,description:"Pack + upload the workspace at <path> (default: cwd) to its npm registry. Drop-in for `npm publish` with workspace:^ rewrite handled automatically.",builder:t=>t.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`tag`,{description:`Dist-tag to publish under. Default: latest.`,type:`string`,default:`latest`}).option(`access`,{description:"Package access — `public` or `restricted` (required for first publish of scoped packages on the public registry).",type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as the `npm-otp` header. Required for manual publishes from a 2FA-enabled account.",type:`string`}).option(`tolerate-republish`,{description:'Treat "version already published" as success — covers both classic 409 Conflict and the npm OIDC-path 403 Forbidden + `"previously published"` body shape. Matches yarn `--tolerate-republish`.',type:`boolean`,default:!1}).option(`tolerate-untrusted-new`,{description:'Skip (exit 0) when OIDC token exchange returns `package not found` AND no fallback token is configured — i.e. a never-before-published `@scope/<name>` whose Trusted Publisher entry hasn\'t been set up on npmjs.com yet. Without this flag, one un-bootstrapped new package breaks the entire serialized `gjsify foreach publish` loop. Pair with `--tolerate-republish` in CI release workflows so a fresh-merged package gracefully skips its first CI publish, leaving the manual-bootstrap step to a maintainer (see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap").',type:`boolean`,default:!1}).option(`verify-timeout`,{description:"Seconds to keep asking the registry for the just-published version before giving up. npm answers 2xx to a write it has only ACCEPTED: in the v0.46.0 release 19 of 199 packages were recorded 56-252s after their 2xx and one was never recorded at all, so a shorter window turns normal queueing into a false red. `0` disables the read-back — for a registry with no packument read path; the success line then reads `UNVERIFIED` and says so, because a publish nothing checked must never look like one that was checked.",type:`number`,default:CK/1e3}).option(`verify-defer`,{description:"Report an unconfirmed read-back and exit 0 instead of 1. ONLY for a caller that re-checks the same set afterwards — `gjsify run npm:publish` passes it because `scripts/verify-published-closure.mjs` sweeps the whole roster at the end of release.yml. Everywhere else an unconfirmed publish must fail the job that made it.",type:`boolean`,default:!1}).option(`hold-timeout`,{description:'Seconds to wait for an intra-repo dependency pin whose exact version the registry does not serve (yet) before HOLDING this package instead of publishing it. A version npm accepted but never serves (status "validating") would make every dependent uninstallable; the write lag measured on v0.46.0 reaches 252s, hence the default. `0` probes once and holds without waiting. A hold exits 1, or 0 under `--verify-defer`.',type:`number`,default:NK/1e3}).option(`report-ledger`,{description:"Print the job-summary markdown for the publish ledger named by $GJSIFY_PUBLISH_LEDGER (versions npm accepted but does not serve, packages held because of them, the recovery command) and exit. Pair with `--ref <tag>`.",type:`boolean`,default:!1}).option(`fail-on-unsettled`,{description:`With --report-ledger: exit 1 when any package is still HELD or any accepted version is still unserved, naming them and the recovery command. The end-of-sweep gate: a sweep that left something behind must be red, not a warning.`,type:`boolean`,default:!1}).option(`held-names`,{description:`Print, one per line, the packages the ledger shows HELD and not yet published, and exit. Feeds the held-package second pass (.github/scripts/retry-held-publish.sh).`,type:`boolean`,default:!1}).option(`settle-ledger`,{description:`Wait up to --settle-timeout for every version the ledger records as accepted-but-unserved to be served (the longer read-back the sweep defers), record each as served, and exit.`,type:`boolean`,default:!1}).option(`settle-timeout`,{description:`With --settle-ledger: seconds to wait. Versions poll concurrently, so this is the longest lag tolerated, not a sum. Default 600 (the fatal read-back default; measured lags reach 368 s).`,type:`number`,default:CK/1e3}).option(`ref`,{description:`With --report-ledger: the git ref to put in the printed recovery command.`,type:`string`}).option(`provenance`,{description:`Pass-through flag — recorded in the payload but no signing happens (gjsify doesn't ship a sigstore signer yet).`,type:`boolean`,default:!1}).option(`dry-run`,{description:`Pack only, do not PUT.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit publish metadata as JSON on stdout.`,type:`boolean`,default:!1}).option(`trusted`,{description:"Authenticate via npm Trusted Publishing (OIDC): exchange the GitHub Actions id-token for a short-lived npm token. Pass `--trusted` to force this mode (errors if env vars missing). Omit to auto-detect: OIDC is used iff `ACTIONS_ID_TOKEN_REQUEST_URL`+`_TOKEN` are set AND no `_authToken` is present in the resolved npmrc; otherwise the long-lived token path is used. Requires the calling workflow to declare `permissions: id-token: write` AND the target package to have a Trusted Publisher configured on npmjs.com.",type:`boolean`,default:void 0}).option(`check-trusted`,{description:"Diagnostic mode: perform the OIDC id-token request + npm token exchange, report success/failure, then exit WITHOUT publishing. Useful as a bulk-verifier (e.g. via `gjsify foreach publish --check-trusted`) to confirm Trusted Publisher config across many packages.",type:`boolean`,default:!1}),handler:async t=>{let n=In(t.path??process.cwd()),S=t.tag??`latest`,C=t.access,N=t.otp,F=t[`tolerate-republish`]===!0,I=t[`tolerate-untrusted-new`]===!0,H=t[`verify-timeout`]??6e5/1e3;if(!Number.isFinite(H)||H<0)return ge.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`verify-timeout`])}`),process.exit(2);let W=Math.round(H*1e3),q=t[`verify-defer`]===!0,Y=t.provenance===!0,X=t[`dry-run`]===!0,Z=t[`check-trusted`]===!0,te=t.trusted,ne=!!process.env.GJSIFY_PUBLISH_DEBUG,re=process.env.GJSIFY_PUBLISH_LEDGER;if(t[`held-names`]===!0){for(let t of pendingEntries(readLedger(re)).held)process.stdout.write(`${t.name}\n`);return}if(t[`settle-ledger`]===!0){let n=t[`settle-timeout`]??6e5/1e3;if(!Number.isFinite(n)||n<0)return ge.error(`gjsify publish: --settle-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`settle-timeout`])}`),process.exit(2);let S=await loadNpmrc(process.cwd()),C=await settleUnserved({entries:readLedger(re),ledgerPath:re,registryFor:t=>(process.env.npm_config_registry??registryFor(t,S)??ph).replace(/\/$/,``),budgetMs:Math.max(1,Math.round(n*1e3)),log:ne?t=>ge.error(t):void 0});for(let t of C)process.stdout.write(`served after settling: ${t}\n`);return}if(t[`report-ledger`]===!0){let n=readLedger(re),S=renderLedgerSummary(n,t.ref??`<tag>`);if(S&&process.stdout.write(`${S}\n`),t[`fail-on-unsettled`]===!0){let{unserved:S,held:C}=pendingEntries(n),N=[...new Set([...C,...S].map(t=>t.name))];if(N.length>0){let n=t.ref??`<tag>`;return ge.error(`gjsify publish: ${C.length} package(s) still HELD and ${S.length} version(s) still unserved after the second pass: ${N.join(` `)}\n recover: re-run THIS run (\`gh run rerun <run-id>\` — keeps the version; never a new dispatch on the next channel, which mints a new one), or for a release: gh workflow run release.yml --ref ${n} -f skip_publish=false -f only='${N.join(` `)}'`),process.exit(1)}}return}let ie=t[`hold-timeout`]??3e5/1e3;if(!Number.isFinite(ie)||ie<0)return ge.error(`gjsify publish: --hold-timeout must be a non-negative number of seconds, got ${JSON.stringify(t[`hold-timeout`])}`),process.exit(2);if(Y&&ge.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Z){let S=zn(n,`package.json`),C=JSON.parse(readFileSync(S,`utf-8`));if(typeof C.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${S} has no \`name\` field\n`),process.exit(2);if(C.private===!0){let n={ok:!0,action:`check-trusted`,name:C.name,skipped:`private`};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`- ${C.name}: skipped (private package)\n`);return}let N=await loadNpmrc(n),F=process.env.npm_config_registry??registryFor(C.name,N)??ph;try{await getNpmTrustedToken({packageName:C.name,registry:F,log:ne?t=>ge.error(t):void 0});let n={ok:!0,action:`check-trusted`,name:C.name,registry:F};t.json?process.stdout.write(`${JSON.stringify(n)}\n`):process.stdout.write(`✓ ${C.name}: trusted publisher OK\n`);return}catch(n){handleOidcFailure(n,C.name,t.json===!0);return}}if(X){let S=await packWorkspace(n,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:t.json?`inherit-stderr`:`inherit`}),C={ok:!0,action:`dry-run`,name:S.name,version:S.version,filename:S.filename,size:S.size,shasum:S.shasum,integrity:S.integrity};t.json?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${S.name}@${S.version} (dry-run, ${S.size} bytes, ${S.entryCount} files)\n`);return}let ae=!!(process.stdin.isTTY&&process.stdout.isTTY),oe=await loadNpmrc(n),Q;try{Q=JSON.parse(readFileSync(zn(n,`package.json`),`utf-8`)).name}catch{}let se=process.env.npm_config_registry??(Q?registryFor(Q,oe):void 0)??oe.registry??ph,ce=new OtpProvider(N,ae?promptLine:async()=>``,{registry:se});reportPublishOutcome(await publishWorkspace({wsDir:n,tag:S,access:C,provenance:Y,tolerate:F,tolerateUntrustedNew:I,trustedFlag:te,verbose:ne,json:t.json===!0,otpProvider:ce,seedOtpFirst:N!==void 0,verifyBudgetMs:W,holdWaitMs:Math.min(Math.round(ie*1e3),remainingHoldDeadlineMs())}),t.json===!0,q)}}});function buildTree(t){let n={name:`#root`,attrs:{},nodes:[]},S=[n];for(let n of scanXml(t)){let t=S[S.length-1];if(n.kind===`text`)t.nodes.push(n.text);else if(n.kind===`open`){let C={name:normName(n.name),attrs:n.attributes,nodes:[]};t.nodes.push(C),n.selfClosing||S.push(C)}else S.length>1&&S.pop()}return n}function inlineMarkdown(t){let n=``;for(let S of t.nodes){if(typeof S==`string`){n+=S;continue}if(isTranslation(S))continue;let t=inlineMarkdown(S),C=ZK[S.name];C===void 0?S.name===`a`&&S.attrs.href?n+=`[${t}](${S.attrs.href})`:n+=t:n+=t.trim()===``?t:`${C}${t.trim()}${C}`}return n}function parseBlocks(t){let n=[];for(let S of elements(t))if(!isTranslation(S)){if(S.name===`p`){let t=clean(inlineMarkdown(S));t&&n.push({p:t})}else if(S.name===`ul`||S.name===`ol`){let t=elements(S,`li`).filter(t=>!isTranslation(t)).map(t=>clean(inlineMarkdown(t))).filter(Boolean);t.length&&n.push({ul:t})}}return n}function parseMetainfoReleases(t){let n=elements(buildTree(t),`component`)[0];if(!n)throw Error(`metainfo root must be <component>`);let S=elements(n,`releases`)[0];return S?elements(S,`release`).map(t=>{let n=t.attrs.timestamp,S=t.attrs.date??(n?new Date(Number(n)*1e3).toISOString().slice(0,10):``),C=elements(t,`description`).find(t=>!isTranslation(t)),N=C?parseBlocks(C):[];return{version:t.attrs.version??``,date:S,...N.length?{description:N}:{}}}):[]}var normName,elements,isTranslation,ZK,clean,QK=__esmMin(()=>{Ye(),normName=t=>t.startsWith(`_`)?t.slice(1):t,elements=(t,n)=>t.nodes.filter(t=>typeof t!=`string`&&(n===void 0||t.name===n)),isTranslation=t=>t.attrs[`xml:lang`]!==void 0,ZK={em:`*`,i:`*`,strong:`**`,b:`**`,code:"`",tt:"`"},clean=t=>t.replace(/\s+/g,` `).trim()});function descriptionToMarkdown(t){let n=typeof t==`string`?stringToBlocks(t):t,S=[];for(let t of n)if(`p`in t){let n=t.p.trim().replace(/\s+/g,` `);n&&S.push(n)}else{let n=t.ul.map(t=>(typeof t==`string`?t:t.item).trim()).filter(Boolean);n.length&&S.push(n.map(t=>`- ${t}`).join(`
|
|
1278
1278
|
`))}return S.join(`
|
|
1279
1279
|
|
|
1280
|
-
`)}function stripVersionPrefix(t){return t.trim().replace(/^v/i,``)}function resolveReleases(t){let n=t.metainfo??(t.configReleases?void 0:t.siteMetainfo);return n===void 0?{releases:t.configReleases}:{releases:parseMetainfoReleases(t.readMetainfo(n)),source:n}}function renderReleaseNotes({releases:t,source:n,version:S,repoUrl:C}){let N=stripVersionPrefix(S),F=t??[],I=F.findIndex(t=>stripVersionPrefix(t.version)===N);if(I<0){let t=n===void 0?"no `releases` configured":"no `<release>` entries";throw Error(`no \`releases\` entry for version ${N} in ${n??`the gjsify config`}`+(F.length?` (found: ${F.map(t=>t.version).join(`, `)})`:` (${t})`))}let H=F[I],W=H.description===void 0?``:descriptionToMarkdown(H.description);if(!W)throw Error(`the \`releases\` entry for version ${N} has no description`);let q=F[I+1];return!C||!q?`${W}\n`:`${W}\n\n**Full changelog:** ${`${C.replace(/\/+$/,``)}/compare/v${stripVersionPrefix(q.version)}...v${N}`}\n`}var
|
|
1280
|
+
`)}function stripVersionPrefix(t){return t.trim().replace(/^v/i,``)}function resolveReleases(t){let n=t.metainfo??(t.configReleases?void 0:t.siteMetainfo);return n===void 0?{releases:t.configReleases}:{releases:parseMetainfoReleases(t.readMetainfo(n)),source:n}}function renderReleaseNotes({releases:t,source:n,version:S,repoUrl:C}){let N=stripVersionPrefix(S),F=t??[],I=F.findIndex(t=>stripVersionPrefix(t.version)===N);if(I<0){let t=n===void 0?"no `releases` configured":"no `<release>` entries";throw Error(`no \`releases\` entry for version ${N} in ${n??`the gjsify config`}`+(F.length?` (found: ${F.map(t=>t.version).join(`, `)})`:` (${t})`))}let H=F[I],W=H.description===void 0?``:descriptionToMarkdown(H.description);if(!W)throw Error(`the \`releases\` entry for version ${N} has no description`);let q=F[I+1];return!C||!q?`${W}\n`:`${W}\n\n**Full changelog:** ${`${C.replace(/\/+$/,``)}/compare/v${stripVersionPrefix(q.version)}...v${N}`}\n`}var $K=__esmMin(()=>{gV(),QK()}),eq,tq=__esmMin(()=>{_R(),KI(),$K(),af(),Xn(),eq={command:`release-notes [release]`,description:"Print the `releases` entry for a version as GitHub Markdown (from the config or a metainfo file). Fails when there is no entry or no description.",builder:t=>t.positional(`release`,{description:"Version or tag (a leading `v` is accepted). Default: the version in package.json.",type:`string`}).option(`compare`,{description:"Append a `**Full changelog:**` compare link to the previous entry (needs `vcsBrowserUrl`).",type:`boolean`,default:!1}).option(`metainfo`,{description:"Read the `<release>` entries from this AppStream metainfo file instead of the config. Default without `releases` in the config: the file named by `gjsify.site.metainfo`.",type:`string`}),handler:async t=>{let n=process.cwd();try{let S=await new Config().forCommand(n),C=S.ship??{},N=S.flatpak??{},F=t.release??readPackageJson$2(zn(n,`package.json`))?.version;if(!F)throw Error(`no version given and package.json has none`);let{releases:I,source:H}=resolveReleases({metainfo:t.metainfo,configReleases:C.releases??N.releases,siteMetainfo:S.site?.metainfo,readMetainfo:t=>{try{return readFileSync(In(n,t),`utf8`)}catch{throw Error(`cannot read the metainfo file ${t}`)}}}),W=t.compare===!0?C.vcsBrowserUrl??N.vcsBrowserUrl:void 0;process.stdout.write(renderReleaseNotes({releases:I,source:H,version:stripVersionPrefix(F),repoUrl:W}))}catch(t){return process.stderr.write(`gjsify release-notes: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}});function px(t,n){return Math.round(t*n)}function planAndroidIcons(t){let n=[];for(let{name:S,scale:C}of rq){let N=`mipmap-${S}`;n.push({path:`${N}/ic_launcher.png`,kind:`legacy`,size:px(48,C)}),n.push({path:`${N}/ic_launcher_round.png`,kind:`round`,size:px(48,C)}),n.push({path:`${N}/ic_launcher_foreground.png`,kind:`foreground`,size:px(108,C)}),t.monochrome&&n.push({path:`${N}/ic_launcher_monochrome.png`,kind:`monochrome`,size:px(108,C)})}for(let{name:t,scale:S}of iq)n.push({path:`drawable-${t}/logo.png`,kind:`splash`,size:px(96,S)});let S=adaptiveIconXml(t.monochrome);return{png:n,text:[{path:`values/ic_launcher_background.xml`,content:backgroundXml(t.background)},{path:`mipmap-anydpi-v26/ic_launcher.xml`,content:S},{path:`mipmap-anydpi-v26/ic_launcher_round.xml`,content:S}]}}function backgroundXml(t){return`<?xml version="1.0" encoding="utf-8"?>
|
|
1281
1281
|
<resources>
|
|
1282
1282
|
<color name="ic_launcher_background">${t}</color>
|
|
1283
1283
|
</resources>
|
|
@@ -1287,12 +1287,12 @@ Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pendi
|
|
|
1287
1287
|
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
|
1288
1288
|
${t?` <monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
|
|
1289
1289
|
`:``}</adaptive-icon>
|
|
1290
|
-
`}function normalizeColor(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];return`#${(S.length===3?[...S].map(t=>t+t).join(``):S).toUpperCase()}`}function parseMetainfoBranding(t){let n=null;for(let S of t.matchAll(/<color\b([^>]*)>\s*([^<\s]+)\s*<\/color>/g)){let t=S[1]??``;if(!/type\s*=\s*["']primary["']/.test(t))continue;let C=normalizeColor(S[2]??``);if(C===null)continue;let N=/scheme_preference\s*=\s*["']([^"']+)["']/.exec(t)?.[1];if(N===`light`)return C;N===void 0&&n===null&&(n=C)}return n}function parseAppResourcesPath(t){return/\bappResourcesPath\s*:\s*["'`]([^"'`]+)["'`]/.exec(t)?.[1]??null}function resolveResourcesName(t){return t.flag??t.configured??(t.nativescriptConfig===null?null:parseAppResourcesPath(t.nativescriptConfig))??`App_Resources`}function resolveBackground(t){let n=t.flag??t.configured;if(n!==void 0){let t=normalizeColor(n);if(t===null)throw Error(`gjsify android-icons: \`${n}\` is not a colour — write it as #rrggbb.`);return t}return t.fromMetainfo??`#FFFFFF`}function pickIconSources(t){let n=t.filter(t=>Wn(t).toLowerCase()===`.svg`),S=n.filter(t=>!isSymbolicIcon(t)),C=S.find(t=>/(?:^|[\\/])scalable[\\/]/.test(t))??S[0]??null,N=n.filter(isSymbolicIcon),F=C===null?null:`${Un(C,`.svg`)}-symbolic`;return{icon:C,symbolic:N.find(t=>Un(t,`.svg`)===F)??N[0]??null}}function symbolicSibling(t){return zn(Hn(Hn(Hn(t))),`symbolic`,`apps`,`${Un(t,`.svg`)}-symbolic.svg`)}function dataUri(t){return`data:image/svg+xml;base64,${Buffer.from(t).toString(`base64`)}`}function wrapperSvg(t,n,S){let C=`xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"`;if(t===`round`){let t=100*
|
|
1290
|
+
`}function normalizeColor(t){let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(n===null)return null;let S=n[1];return`#${(S.length===3?[...S].map(t=>t+t).join(``):S).toUpperCase()}`}function parseMetainfoBranding(t){let n=null;for(let S of t.matchAll(/<color\b([^>]*)>\s*([^<\s]+)\s*<\/color>/g)){let t=S[1]??``;if(!/type\s*=\s*["']primary["']/.test(t))continue;let C=normalizeColor(S[2]??``);if(C===null)continue;let N=/scheme_preference\s*=\s*["']([^"']+)["']/.exec(t)?.[1];if(N===`light`)return C;N===void 0&&n===null&&(n=C)}return n}function parseAppResourcesPath(t){return/\bappResourcesPath\s*:\s*["'`]([^"'`]+)["'`]/.exec(t)?.[1]??null}function resolveResourcesName(t){return t.flag??t.configured??(t.nativescriptConfig===null?null:parseAppResourcesPath(t.nativescriptConfig))??`App_Resources`}function resolveBackground(t){let n=t.flag??t.configured;if(n!==void 0){let t=normalizeColor(n);if(t===null)throw Error(`gjsify android-icons: \`${n}\` is not a colour — write it as #rrggbb.`);return t}return t.fromMetainfo??`#FFFFFF`}function pickIconSources(t){let n=t.filter(t=>Wn(t).toLowerCase()===`.svg`),S=n.filter(t=>!isSymbolicIcon(t)),C=S.find(t=>/(?:^|[\\/])scalable[\\/]/.test(t))??S[0]??null,N=n.filter(isSymbolicIcon),F=C===null?null:`${Un(C,`.svg`)}-symbolic`;return{icon:C,symbolic:N.find(t=>Un(t,`.svg`)===F)??N[0]??null}}function symbolicSibling(t){return zn(Hn(Hn(Hn(t))),`symbolic`,`apps`,`${Un(t,`.svg`)}-symbolic.svg`)}function dataUri(t){return`data:image/svg+xml;base64,${Buffer.from(t).toString(`base64`)}`}function wrapperSvg(t,n,S){let C=`xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"`;if(t===`round`){let t=100*aq,N=(100-t)/2;return`<svg ${C} width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="50" fill="${S}"/><image x="${N}" y="${N}" width="${t}" height="${t}" xlink:href="${dataUri(n)}"/></svg>`}return`<svg ${C} width="108" height="108" viewBox="0 0 108 108"><image x="21" y="21" width="66" height="66" xlink:href="${dataUri(n)}"/></svg>`}function sha256(t){return createHash(`sha256`).update(t).digest(`hex`)}function hashInputs(t){return sha256(JSON.stringify({generator:1,icon:sha256(t.icon),symbolic:t.symbolic===null?null:sha256(t.symbolic),background:t.background}))}function buildStamp(t,n,S){return{generator:1,inputs:t,files:[...n.png.map(t=>t.path),...n.text.map(t=>t.path)].map(t=>On.join(S,t)).sort()}}function checkStamp(t,n,S){if(t===null)return{current:!1,reason:`was never generated`};let C;try{C=JSON.parse(t)}catch{return{current:!1,reason:`has an unreadable stamp`}}if(C.generator!==1||C.inputs!==n)return{current:!1,reason:`is out of date with the icon, colour or generator`};let N=(C.files??[]).find(t=>!S(t));return N===void 0?{current:!0}:{current:!1,reason:`lacks ${N}`}}var nq,rq,iq,aq,oq=__esmMin(()=>{gl(),Xn(),wH(),nq=`.gjsify-android-icons.json`,rq=[{name:`mdpi`,scale:1},{name:`hdpi`,scale:1.5},{name:`xhdpi`,scale:2},{name:`xxhdpi`,scale:3},{name:`xxxhdpi`,scale:4}],iq=[{name:`ldpi`,scale:.75},...rq],aq=.72});function walk(t,n=[]){if(!existsSync(t))return n;for(let S of readdirSync(t,{withFileTypes:!0})){let C=zn(t,S.name);S.isDirectory()?walk(C,n):n.push(C)}return n}function discoverIcon(t,n){if(n!==void 0){let S=In(t,n);if(!existsSync(S))throw Error(`the icon ${n} does not exist`);let C=symbolicSibling(S);return{icon:S,symbolic:existsSync(C)?C:null}}let S=[zn(t,`data`,`icons`),...siblingIconRoots(t)];for(let t of S){let n=pickIconSources(walk(t).filter(t=>t.toLowerCase().endsWith(`.svg`)).sort());if(n.icon!==null)return{icon:n.icon,symbolic:n.symbolic}}throw Error("no app icon found; pass --icon <svg> or set `gjsify.androidIcons.icon`")}function siblingIconRoots(t){let n=Hn(t);return existsSync(n)?readdirSync(n).sort().map(t=>zn(n,t,`data`,`icons`)).filter(n=>n!==zn(t,`data`,`icons`)&&existsSync(n)&&statSync(n).isDirectory()):[]}function findMetainfoColor(t,n){let S=new Set([zn(n,`data`)]);S.add(In(Hn(t),`..`,`..`,`..`,`..`));for(let t of S){let n=walk(zn(t,`metainfo`)).filter(t=>/\.metainfo\.xml(\.in)?$/.test(t)).sort();for(let t of n){let n=parseMetainfoBranding(readFileSync(t,`utf8`));if(n!==null)return n}}return null}var sq,cq,lq=__esmMin(()=>{af(),o_(),Xn(),_R(),oq(),wH(),sq=`Android/src/main/res`,cq={command:`android-icons`,description:`Generate the Android launcher icon and splash logo of a NativeScript app from its one app icon.`,builder:t=>t.option(`resources`,{description:"The App_Resources directory. Default: `gjsify.androidIcons.resources`, else `appResourcesPath` of nativescript.config.ts, else App_Resources.",type:`string`}).option(`icon`,{description:"The scalable app icon SVG. Default: `gjsify.androidIcons.icon`, else the hicolor icon under data/icons (here or in a sibling package).",type:`string`}).option(`background`,{description:"Adaptive-icon background colour. Default: `gjsify.androidIcons.background`, else the metainfo light `<branding>` colour, else white.",type:`string`}).option(`check`,{description:`Write nothing; exit 1 when the generated files are missing or the inputs changed.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd();try{let S=(await new Config().forCommand(n)).androidIcons??{},C=[`nativescript.config.ts`,`nativescript.config.js`].map(t=>zn(n,t)).find(t=>existsSync(t)),N=resolveResourcesName({flag:t.resources,configured:S.resources,nativescriptConfig:C===void 0?null:readFileSync(C,`utf8`)}),F=In(n,N),{icon:I,symbolic:H}=discoverIcon(n,t.icon??S.icon),W=resolveBackground({flag:t.background,configured:S.background,fromMetainfo:findMetainfoColor(I,n)}),q=new Uint8Array(readFileSync(I)),Y=H===null?null:new Uint8Array(readFileSync(H)),X=hashInputs({icon:q,symbolic:Y,background:W}),Z=planAndroidIcons({background:W,monochrome:Y!==null}),te=zn(F,nq);if(t.check===!0){let t=checkStamp(existsSync(te)?readFileSync(te,`utf8`):null,X,t=>existsSync(zn(F,...t.split(`/`))));return t.current?void 0:(process.stderr.write(`gjsify android-icons: ${N} ${t.reason}; run \`gjsify android-icons\` and commit it\n`),process.exit(1))}let ne=zn(F,...sq.split(`/`)),re=mkdtempSync(zn(tmpdir(),`gjsify-android-icons-`));try{let t=new Map([[`plain`,I]]);for(let n of[`round`,`foreground`]){let S=zn(re,`${n}.svg`);writeFileSync(S,wrapperSvg(n,q,W)),t.set(n,S)}if(Y!==null){let n=zn(re,`monochrome.svg`);writeFileSync(n,wrapperSvg(`monochrome`,Y,W)),t.set(`monochrome`,n)}for(let[n,S]of t){let t=Z.png.filter(t=>n===`plain`?t.kind===`legacy`||t.kind===`splash`:t.kind===n),C=await rasterizeSvg({svg:S,sizes:[...new Set(t.map(t=>t.size))],command:`gjsify android-icons`});for(let n of t){let t=zn(ne,n.path);mkdirSync(Hn(t),{recursive:!0}),writeFileSync(t,C.get(n.size))}}}finally{rmSync(re,{recursive:!0,force:!0})}for(let t of Z.text){let n=zn(ne,t.path);mkdirSync(Hn(n),{recursive:!0}),writeFileSync(n,t.content)}rmSync(zn(ne,`drawable`,`ic_launcher_foreground.xml`),{force:!0}),writeFileSync(te,`${JSON.stringify(buildStamp(X,Z,sq),null,2)}\n`),process.stdout.write(`gjsify android-icons: wrote ${Z.png.length+Z.text.length} files under ${Bn(n,ne).split(qn).join(`/`)} from ${Bn(n,I)}\n`)}catch(t){return process.stderr.write(`gjsify android-icons: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}});function globToRegExp(t){let n=t.split(`*`).map(t=>t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`)).join(`.*`);return RegExp(`^${n}$`,`i`)}function isIgnored(t,n){return n.some(n=>{let S=globToRegExp(n);return S.test(t.name)||t.email!==``&&S.test(t.email)})}function parsePerson(t){let n=/^(.*?)\s*<([^>]*)>\s*$/.exec(t.trim());return n?{name:n[1].trim(),email:n[2].trim()}:{name:t.trim(),email:``}}function poLanguage(t){let n=On.basename(t);return/\.po$/i.test(n)?n.slice(0,-3):void 0}function bump(t,n){t.set(n,(t.get(n)??0)+1)}function rank(t){return[...t.entries()].sort(([t,n],[S,C])=>C-n||(t<S?-1:+(t>S))).map(([t])=>t)}function appendUnseen(t,n,S){let C=new Set(t);for(let N of n??[]){let n=N.trim();n&&!C.has(n)&&!S(n)&&(C.add(n),t.push(n))}}function buildCredits(t,n={}){let S=n.ignore??uq,C=n.overrides??{},N=C.exclude??[],excluded=t=>isIgnored({name:t,email:``},N),F=new Map,I=new Map,H=t.map(t=>{let n=new Set;for(let C of[t.author,...t.coAuthors])C.name&&!isIgnored(C,S)&&!excluded(C.name)&&n.add(C.name);let C=new Set,N=!1;for(let n of t.files){isTranslationFile(n)||(N=!0);let t=poLanguage(n);t&&C.add(t)}return{names:n,languages:C,touchesCode:N}}),W=new Map;for(let{names:t,languages:n}of H){if(t.size!==1||n.size!==1)continue;let[S]=t,[C]=n,N=W.get(S);N||W.set(S,N=new Set),N.add(C)}for(let{names:t,languages:n,touchesCode:S}of H){let C=t.size>1||n.size>1;for(let N of t){S&&bump(F,N);let t=W.get(N);for(let S of n){if(C&&t&&!t.has(S))continue;let n=I.get(S);n||I.set(S,n=new Map),bump(n,N)}}}let q={developers:rank(F),translators:{},supporters:[]},Y=C.excludeTranslators??{};for(let t of[...I.keys()].sort()){let n=[...Y[`*`]??[],...Y[t]??[]],S=rank(I.get(t)).filter(t=>!isIgnored({name:t,email:``},n));S.length&&(q.translators[t]=S)}appendUnseen(q.developers,C.developers,excluded);for(let t of Object.keys(C.translators??{}).sort()){let n=q.translators[t]??[];appendUnseen(n,C.translators[t],excluded),n.length&&(q.translators[t]=n)}return q.translators=Object.fromEntries(Object.entries(q.translators).sort(([t],[n])=>t<n?-1:1)),appendUnseen(q.supporters,C.supporters,excluded),q}function parseGitLog(t){let n=[];for(let S of t.split(fq)){if(!S.trim())continue;let[t=``,C=``,N=``,F=``]=S.split(dq);n.push({author:{name:t.trim(),email:C.trim()},coAuthors:N.split(pq).map(t=>t.trim()).filter(Boolean).map(parsePerson),files:F.split(`
|
|
1291
1291
|
`).map(t=>t.trim()).filter(Boolean)})}return n}function git(t,n,S){let C=spawnSync(`git`,[...n],{cwd:t,encoding:`utf8`,input:S,maxBuffer:1<<30});if(C.error)throw Error(`cannot run git: ${C.error.message}`);if(C.status!==0)throw Error(`git ${n.join(` `)} failed: ${String(C.stderr).trim()}`);return String(C.stdout)}function mapTrailers(t,n){let S=new Set;for(let t of n)for(let n of t.coAuthors)n.email&&S.add(`${n.name} <${n.email}>`);if(S.size===0)return;let C=[...S],N=git(t,[`check-mailmap`,`--stdin`],C.join(`
|
|
1292
1292
|
`)+`
|
|
1293
1293
|
`).split(`
|
|
1294
|
-
`).filter(Boolean);if(N.length!==C.length)throw Error(`git check-mailmap answered a different number of lines`);let F=new Map(C.map((t,n)=>[t,parsePerson(N[n])]));for(let t of n)t.coAuthors=t.coAuthors.map(t=>t.email?F.get(`${t.name} <${t.email}>`):t)}function readCommits(t){if(git(t,[`rev-parse`,`--is-shallow-repository`]).trim()===`true`)throw Error(`the repository is a shallow clone; fetch the full history first (git fetch --unshallow)`);let n=parseGitLog(git(t,
|
|
1295
|
-
`}function isStale(t,n){if(t===null)return!0;try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(n)}catch{return!0}}var
|
|
1294
|
+
`).filter(Boolean);if(N.length!==C.length)throw Error(`git check-mailmap answered a different number of lines`);let F=new Map(C.map((t,n)=>[t,parsePerson(N[n])]));for(let t of n)t.coAuthors=t.coAuthors.map(t=>t.email?F.get(`${t.name} <${t.email}>`):t)}function readCommits(t){if(git(t,[`rev-parse`,`--is-shallow-repository`]).trim()===`true`)throw Error(`the repository is a shallow clone; fetch the full history first (git fetch --unshallow)`);let n=parseGitLog(git(t,mq));return mapTrailers(t,n),n}function asStringList(t,n){if(!Array.isArray(t)||t.some(t=>typeof t!=`string`))throw Error(`${n} must be an array of strings`);return t}function parseOverrides(t,n=`overrides`){let S;try{S=JSON.parse(t)}catch(t){throw Error(`${n} is not valid JSON: ${t instanceof Error?t.message:String(t)}`)}if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`${n} must be a JSON object`);let C=S,N=new Set([...hq,...gq]);for(let t of Object.keys(C))if(!N.has(t))throw Error(`${n} has an unknown key "${t}" (known: ${[...N].join(`, `)})`);let F={};for(let t of hq)C[t]!==void 0&&(F[t]=asStringList(C[t],`${n}.${t}`));for(let t of gq){let S=C[t];if(S===void 0)continue;if(typeof S!=`object`||!S||Array.isArray(S))throw Error(`${n}.${t} must map a language to an array of names`);let N={};for(let[C,F]of Object.entries(S))N[C]=asStringList(F,`${n}.${t}.${C}`);F[t]=N}return F}function serializeCredits(t){return JSON.stringify(t,null,2)+`
|
|
1295
|
+
`}function isStale(t,n){if(t===null)return!0;try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(n)}catch{return!0}}var uq,dq,fq,pq,isTranslationFile,mq,hq,gq,_q=__esmMin(()=>{cv(),Xn(),uq=[`*[bot]`,`github-actions`,`Weblate`,`Weblate (bot)`,`Hosted Weblate`,`Weblate Translation Memory`,`LibreTranslate`,`Claude`,`*@anthropic.com`,`noreply-mt-*@weblate.org`,`hosted@weblate.org`,`*[bot]@users.noreply.github.com`],dq=``,fq=``,pq=``,isTranslationFile=t=>/\.pot?$/i.test(t),mq=[`-c`,`core.quotepath=off`,`log`,`--no-merges`,`--use-mailmap`,`--name-only`,`--format=${fq}%aN${dq}%aE${dq}%(trailers:key=Co-authored-by,valueonly,unfold,separator=%x1d)${dq}`],hq=[`developers`,`supporters`,`exclude`],gq=[`translators`,`excludeTranslators`]}),vq,yq,bq,xq=__esmMin(()=>{_R(),_q(),af(),Xn(),vq=`credits.json`,yq=`credits.overrides.json`,bq={command:`credits`,description:`Write the project’s contributors (developers, translators per language) from the git history as JSON, names only.`,builder:t=>t.option(`output`,{alias:`o`,description:`File to write. Default: \`gjsify.credits.output\`, else ${vq}.`,type:`string`}).option(`overrides`,{description:`Hand-kept additions and exclusions. Default: \`gjsify.credits.overrides\`, else ${yq} when it exists.`,type:`string`}).option(`check`,{description:`Write nothing; exit 1 when the file on disk differs from what the history gives.`,type:`boolean`,default:!1}).option(`stdout`,{description:`Print the JSON instead of writing it.`,type:`boolean`,default:!1}).conflicts(`check`,`stdout`),handler:async t=>{let n=process.cwd();try{let S=(await new Config().forCommand(n)).credits??{},C=In(n,t.output??S.output??vq),N=t.overrides??S.overrides,F=In(n,N??yq),I;if(existsSync(F))I=parseOverrides(readFileSync(F,`utf8`),N??yq);else if(N!==void 0)throw Error(`cannot read the overrides file ${N}`);let H=buildCredits(readCommits(n),{ignore:S.ignore??uq,overrides:I}),W=serializeCredits(H);if(t.stdout===!0)process.stdout.write(W);else if(t.check===!0){let n=existsSync(C)?readFileSync(C,`utf8`):null;if(isStale(n,H))return process.stderr.write(`gjsify credits: ${t.output??S.output??vq} is ${n===null?`missing`:`stale`}; run \`gjsify credits\` and commit it\n`),process.exit(1)}else writeFileSync(C,W)}catch(t){return process.stderr.write(`gjsify credits: ${t instanceof Error?t.message:String(t)}\n`),process.exit(1)}}}}),Sq,Cq=__esmMin(()=>{xh(),DB(),Sq={command:`whoami`,description:`Print the npm-registry username for the current ~/.npmrc token. Clear failure message when the token is dead, missing, or the registry is unreachable.`,builder:t=>t.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??n.registry??ph,C=S.endsWith(`/`)?S.slice(0,-1):S,N=t.json===!0;if(!hasAnyCredential(n))return N?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:C})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${C}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
|
|
1296
1296
|
`)+`
|
|
1297
1297
|
`),process.exit(1);let F;try{F=await whoami(S,n)}catch(t){let n=t instanceof Error?t.message:String(t);return N?process.stdout.write(`${JSON.stringify({error:n,registry:C})}\n`):(process.stderr.write(`gjsify whoami: ${n}\n`),process.stderr.write(`Registry: ${C}\n`)),process.exit(1)}if(F.username&&F.username.length>0){N?process.stdout.write(`${JSON.stringify({username:F.username,registry:C})}\n`):(process.stdout.write(`Logged in as: ${F.username}\n`),process.stdout.write(`Registry: ${C}\n`));return}N?process.stdout.write(`${JSON.stringify({error:`dead-token`,registry:C})}\n`):process.stderr.write([`gjsify whoami: token appears dead or revoked (registry returned an empty whoami response).`,``,`Refresh via: npm login`,`Then verify: gjsify whoami`,``,`For the @gjsify scope, see AGENTS.md > "New @gjsify/* package: first-publish + Trusted Publisher bootstrap".`].join(`
|
|
1298
1298
|
`)+`
|
|
@@ -1301,12 +1301,12 @@ ${t?` <monochrome android:drawable="@mipmap/ic_launcher_monochrome"/>
|
|
|
1301
1301
|
`)+`
|
|
1302
1302
|
`),S}function removeAuthToken(t){let n=userconfigNpmrcPath(),S=authTokenKey(t),C=readUserconfig(n);if(!C)return{path:n,removed:!1};let N=C.split(`
|
|
1303
1303
|
`),F=N.filter(t=>!t.replace(/\s+/g,``).startsWith(`${S}=`)),I=F.length!==N.length;return I&&writeUserconfig(n,F.join(`
|
|
1304
|
-
`)),{path:n,removed:I}}var
|
|
1305
|
-
Enter OTP: `),!Y)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(C,Y),X=await putUser(``,Y)}}if(X.status===409){let t=await fetch(`${H}?write=true`,{headers:authHeaders(Y)});if(t.ok){let n=await t.json().catch(()=>({}));for(let t of Object.keys(n))(!W[t]||t===`roles`)&&(W[t]=n[t]);W._rev&&(X=await putUser(`/-rev/${W._rev}`,Y))}}if(X.status===400)throw new LoginError(`gjsify login: there is no user with the username "${N}" on ${C}.`);if(!X.ok){let t=await X.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${X.status} ${X.statusText} from ${C}\n${t.slice(0,400)}`)}let Z=await X.json().catch(()=>({}));if(!Z.token)throw new LoginError("gjsify login: the registry accepted the login but returned no token (unexpected response shape). Your registry may require the web-OAuth flow — use `npm login`.");let te=writeAuthToken(C,Z.token);return Y&&writeCachedOtp(C,Y),{username:(await whoami(C,await loadNpmrc(t.cwd??process.cwd()))).username??N,registry:C,npmrcPath:te}}var LoginError,
|
|
1306
|
-
`)[0].slice(0,200)}var
|
|
1307
|
-
(\`gjsify trust\` uses the ~/.npmrc bearer token directly — unlike \`npm trust\`, which logs in via the browser.)`),process.exit(1)}if(!t.username)return ge.error("gjsify trust: your npm token appears dead or revoked (registry returned an empty whoami).\nRefresh it with `npm login`, then re-run."),process.exit(1);ge.log(`gjsify trust: authenticated as ${t.username}`)}let N=t.repository;if(!N){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(N=parseRepoFromGitRemote(t.stdout)??void 0)}if(!N)return ge.error("gjsify trust: could not determine the GitHub repository.\nPass --repository owner/repo (no `origin` remote to infer from)."),process.exit(1);if(!validateRepository(N))return ge.error(`gjsify trust: --repository must be "owner/repo", got "${N}".`),process.exit(1);let F=normalizeWorkflowFile(t.workflow),I=t.environment,H=t.list===!0,W=t[`dry-run`]===!0,q=t.force===!0,Y=zn(n,`.github`,`workflows`,F);existsSync(Y)||ge.warn(`gjsify trust: note — ${Y} not found; configuring trust for "${F}" anyway.`);let X=filterWorkspaces(mergePublishables(discoverWorkspaces(n,{includeRoot:!0}),n),{noPrivate:t.private!==!0,include:t.packages&&t.packages.length>0?t.packages:void 0}).filter(t=>t.name);if(X.length===0)return ge.error(`gjsify trust: no publishable packages matched.`),process.exit(1);ge.log(`gjsify trust: ${X.length} package(s) | repo=${N} workflow=${F}`),W&&ge.log(`(dry-run — nothing will be written)`),ge.log();let Z=createTrustRequester({npmrc:S,otpProvider:new OtpProvider(t.otp)}),te=0,ne=0,re=0,ie=0,ae=[],oe=[];for(let n of X){let C=n.name,Y=trustUrl(t.registry??registryFor(C,S)??ph,C);process.stdout.write(`→ ${C.padEnd(42)} `);let X=await Z(`GET`,Y),Q=classifyTrustList(X.status,X.json,{repository:N,workflow:F});if(H){Q===`trusted`?ge.log(`trusted`):Q===`unpublished`?ge.log(`unpublished`):Q===`auth-required`?ge.log(`auth-required (could not read)`):Q===`untrusted`?ge.log(`not trusted`):ge.log(`error (HTTP ${X.status})`);continue}if(Q===`trusted`&&!q){ge.log(`already configured — skip`),ne++;continue}if(Q===`unpublished`){ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C);continue}if(W){ge.log(`would configure`),te++;continue}let se=await Z(`POST`,Y,githubTrustBody({repository:N,workflow:F,environment:I}));se.status>=200&&se.status<300?(ge.log(`configured`),te++):se.status===409?(ge.log(`already configured (409) — done`),ne++):se.status===404?(ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C)):(ge.log(`FAILED (HTTP ${se.status})`),ie++,oe.push(`${C} — HTTP ${se.status}${se.text?`: ${firstLine(se.text)}`:``}`))}if(!H){if(ge.log(),ge.log(`Done: ${te} ${W?`would-configure`:`configured`}, ${ne} already-configured, ${re} unpublished, ${ie} failed.`),ae.length>0){ge.log("Need a first publish before they can be trust-configured (then re-run `gjsify trust`):");for(let t of ae)ge.log(` ${t}`)}if(oe.length>0){ge.log("Failed (re-run `gjsify trust` — it is incremental; usually a lapsed 2FA window or rate-limit):");for(let t of oe)ge.log(` ${t}`);return W||(ge.log(),ge.log(
|
|
1304
|
+
`)),{path:n,removed:I}}var wq=__esmMin(()=>{af(),o_(),Xn()});async function runLogin(t){let n=await loadNpmrc(t.cwd??process.cwd()),S=t.registry??process.env.npm_config_registry??(t.scope?registryFor(t.scope.startsWith(`@`)?`${t.scope}/_`:`@${t.scope}/_`,n):void 0)??ph,C=S.endsWith(`/`)?S:`${S}/`,{username:N,password:F}=await promptCredentials(t.username);if(!N)throw new LoginError(`gjsify login: a username is required.`);if(!F)throw new LoginError(`gjsify login: a password is required.`);let I=`Basic ${btoa(`${N}:${F}`)}`,H=`${C}-/user/org.couchdb.user:${encodeURIComponent(N)}`,W={_id:`org.couchdb.user:${N}`,name:N,password:F,type:`user`,roles:[],date:void 0};function authHeaders(t){let n={authorization:I,"content-type":`application/json`,accept:`*/*`};return t&&(n[`npm-otp`]=t),n}async function putUser(t,n){return fetch(`${H}${t}`,{method:`PUT`,headers:authHeaders(n),body:JSON.stringify(W)})}let q=typeof t.otp==`string`&&t.otp.length>0,Y=t.otp??readCachedOtp(C),X=await putUser(``,Y);if(X.status===401&&!q){let t=(X.headers.get(`www-authenticate`)??``).toLowerCase(),n=await X.clone().text().catch(()=>``);if(t.includes(`otp`)||/one-time pass/i.test(n)){if(clearCachedOtp(C),Y=await promptLine(`This operation requires a one-time password.
|
|
1305
|
+
Enter OTP: `),!Y)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(C,Y),X=await putUser(``,Y)}}if(X.status===409){let t=await fetch(`${H}?write=true`,{headers:authHeaders(Y)});if(t.ok){let n=await t.json().catch(()=>({}));for(let t of Object.keys(n))(!W[t]||t===`roles`)&&(W[t]=n[t]);W._rev&&(X=await putUser(`/-rev/${W._rev}`,Y))}}if(X.status===400)throw new LoginError(`gjsify login: there is no user with the username "${N}" on ${C}.`);if(!X.ok){let t=await X.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${X.status} ${X.statusText} from ${C}\n${t.slice(0,400)}`)}let Z=await X.json().catch(()=>({}));if(!Z.token)throw new LoginError("gjsify login: the registry accepted the login but returned no token (unexpected response shape). Your registry may require the web-OAuth flow — use `npm login`.");let te=writeAuthToken(C,Z.token);return Y&&writeCachedOtp(C,Y),{username:(await whoami(C,await loadNpmrc(t.cwd??process.cwd()))).username??N,registry:C,npmrcPath:te}}var LoginError,Tq,Eq=__esmMin(()=>{_e(),xh(),DB(),wq(),HK(),GK(),LoginError=class extends Error{constructor(t){super(t),this.name=`LoginError`}},Tq={command:`login`,description:"Log in to an npm registry (Node-free `npm login`). Prompts for username + password (hidden) and writes the token to ~/.npmrc. Use --otp for 2FA. Web-OAuth flow is not supported — this is npm's legacy credentials flow.",builder:t=>t.option(`registry`,{description:`Registry URL to log in to. Default: ${ph} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Associate the login with a scope (e.g. @gjsify) — resolves that scope's registry from .npmrc.`,type:`string`}).option(`username`,{description:`Username (prompted if omitted).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code (prompted on demand if omitted).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` JSON on success.",type:`boolean`}),handler:async t=>{try{let{username:n,registry:S,npmrcPath:C}=await runLogin({registry:t.registry,scope:t.scope,username:t.username,otp:t.otp});t.json?process.stdout.write(`${JSON.stringify({username:n,registry:S})}\n`):process.stdout.write(`Logged in as ${n} on ${S}\n(token written to ${C})\n`)}catch(t){if(t instanceof LoginError)return ge.error(t.message),process.exit(1);throw t}}}}),Dq,Oq=__esmMin(()=>{xh(),DB(),wq(),GK(),Dq={command:`logout`,description:"Log out of an npm registry (Node-free `npm logout`). Revokes the token on the registry (best-effort) and removes it from ~/.npmrc.",builder:t=>t.option(`registry`,{description:`Registry URL to log out of. Default: ${ph} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Log out of a scope's registry (e.g. @gjsify) — resolved from .npmrc.`,type:`string`}).option(`json`,{description:"Emit `{registry, revoked, removed}` JSON.",type:`boolean`}),handler:async t=>{let n=await loadNpmrc(process.cwd()),S=t.registry??process.env.npm_config_registry??(t.scope?registryFor(t.scope.startsWith(`@`)?`${t.scope}/_`:`@${t.scope}/_`,n):void 0)??ph,C=S.endsWith(`/`)?S:`${S}/`,N=resolveAuthForUrl(`${C}-/whoami`,n),F=!1;if(N?.startsWith(`Bearer `)){let t=N.slice(7);try{F=(await fetch(`${C}-/user/token/${encodeURIComponent(t)}`,{method:`DELETE`,headers:{authorization:N,accept:`*/*`}})).ok}catch{}}clearCachedOtp(C);let{path:I,removed:H}=removeAuthToken(C);t.json?process.stdout.write(`${JSON.stringify({registry:C,revoked:F,removed:H})}\n`):H?process.stdout.write(`Logged out of ${C}${F?` (token revoked)`:``}\n(removed from ${I})\n`):process.stdout.write(`No token for ${C} found in ${I} — nothing to remove.\n`)}}});function discoverNonWorkspacePublishables(t){let n=t,S=kq[0];for(let t=0;t<8&&!existsSync(zn(n,...S));t++){let t=Hn(n);if(t===n)return[];n=t}let C=[];for(let t of kq){let S=zn(n,...t);if(!existsSync(S))continue;let N;try{N=readdirSync(S,{withFileTypes:!0})}catch{continue}for(let n of N){if(!n.isDirectory())continue;let N=zn(S,n.name),F=zn(N,`package.json`);if(existsSync(F))try{let S=JSON.parse(readFileSync(F,`utf8`));if(!S||typeof S.name!=`string`||S.name.length===0)continue;C.push({location:N,relativeLocation:zn(...t,n.name),name:S.name,version:typeof S.version==`string`?S.version:`0.0.0`,manifest:S,private:S.private===!0})}catch{}}}return C}function mergePublishables(t,n){let S=new Set(t.map(t=>t.name));return[...t,...discoverNonWorkspacePublishables(n).filter(t=>!S.has(t.name))]}var kq,Aq=__esmMin(()=>{af(),Xn(),kq=[[`packages`,`node-gi`],[`packages`,`napi`],[`packages`,`node-runtime`]]});function trustUrl(t,n){return`${t.endsWith(`/`)?t.slice(0,-1):t}/-/package/${escapePackageName(n)}/trust`}function githubTrustBody(t){let n={repository:t.repository,workflow_ref:{file:normalizeWorkflowFile(t.workflow)}};return t.environment&&(n.environment=t.environment),[{type:`github`,claims:n,permissions:t.permissions&&t.permissions.length>0?t.permissions:[jq]}]}function normalizeWorkflowFile(t){return t.split(`/`).pop()??t}function validateRepository(t){let n=t.split(`/`);return n.length===2&&n[0].length>0&&n[1].length>0}function matchesGithubTrust(t,n){if(t.type!==`github`)return!1;let S=t.claims?.repository,C=t.claims?.workflow_ref?.file;return S===n.repository&&C===normalizeWorkflowFile(n.workflow)}function classifyTrustList(t,n,S){return t===404?`unpublished`:t===401?`auth-required`:t>=200&&t<300?(Array.isArray(n)?n:[]).some(t=>matchesGithubTrust(t,S))?`trusted`:`untrusted`:`error`}function parseRepoFromGitRemote(t){let n=t.trim();if(!n)return null;n=n.replace(/^git\+/,``),n=n.replace(/\.git$/,``);let S=n.match(/^[^/@]+@[^:]+:(.+)$/);if(S)return twoSegments(S[1]);let C=n.match(/^[a-z]+:\/\/[^/]+\/(.+)$/i);return C?twoSegments(C[1]):null}function twoSegments(t){let n=t.split(`/`).filter(t=>t.length>0);return n.length<2?null:`${n[n.length-2]}/${n[n.length-1]}`}var jq,Mq=__esmMin(()=>{Ch(),jq=`createPackage`});function createTrustRequester(t){return async(n,S,C)=>{let doFetch=N=>{let F=buildHeaders(S,{npmrc:t.npmrc});F.accept=`application/json`,C!==void 0&&(F[`content-type`]=`application/json`),N&&(F[`npm-otp`]=N);let I={method:n,headers:F};return C!==void 0&&(I.body=JSON.stringify(C)),fetch(S,I)},N=await withOtpRetry(doFetch,t.otpProvider),F=await N.text().catch(()=>``),I;try{I=F?JSON.parse(F):void 0}catch{}return{status:N.status,json:I,text:F,headers:N.headers}}}function firstLine(t){return t.split(`
|
|
1306
|
+
`)[0].slice(0,200)}var Nq,Pq=__esmMin(()=>{_e(),cv(),af(),Xn(),xh(),GI(),Aq(),DB(),yK(),JK(),Mq(),Nq={command:`trust [packages..]`,description:"Configure npm Trusted Publishers (OIDC/GitHub Actions) for publishable workspace packages so release.yml can publish without a token. Native — no `npm` needed. Incremental: skips already-configured packages.",builder:t=>t.positional(`packages`,{description:`Optional package-name globs to limit the sweep (default: all publishable workspaces).`,type:`string`,array:!0}).option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as `npm-otp`. Prompted on demand if omitted.",type:`string`}).option(`dry-run`,{description:`List what would be configured without writing anything.`,type:`boolean`,default:!1}).option(`force`,{description:`Re-POST the config even for packages already trusted for this repo+workflow.`,type:`boolean`,default:!1}).option(`list`,{description:`Only report each package’s current trust state; configure nothing.`,type:`boolean`,default:!1}).option(`private`,{description:`Include private workspaces (default false — private packages are not publishable).`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=await loadNpmrc(n);if(!hasAnyCredential(S))return ge.error("gjsify trust: no npm token configured. Run `gjsify login` first."),process.exit(1);let C=t.registry??process.env.npm_config_registry??S.registry??ph;if(t[`dry-run`]!==!0){let t;try{t=await whoami(C,S)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`gjsify trust: npm auth check failed (${n}).\nYour ~/.npmrc token is dead or revoked — refresh it with \`npm login\`, then re-run.
|
|
1307
|
+
(\`gjsify trust\` uses the ~/.npmrc bearer token directly — unlike \`npm trust\`, which logs in via the browser.)`),process.exit(1)}if(!t.username)return ge.error("gjsify trust: your npm token appears dead or revoked (registry returned an empty whoami).\nRefresh it with `npm login`, then re-run."),process.exit(1);ge.log(`gjsify trust: authenticated as ${t.username}`)}let N=t.repository;if(!N){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(N=parseRepoFromGitRemote(t.stdout)??void 0)}if(!N)return ge.error("gjsify trust: could not determine the GitHub repository.\nPass --repository owner/repo (no `origin` remote to infer from)."),process.exit(1);if(!validateRepository(N))return ge.error(`gjsify trust: --repository must be "owner/repo", got "${N}".`),process.exit(1);let F=normalizeWorkflowFile(t.workflow),I=t.environment,H=t.list===!0,W=t[`dry-run`]===!0,q=t.force===!0,Y=zn(n,`.github`,`workflows`,F);existsSync(Y)||ge.warn(`gjsify trust: note — ${Y} not found; configuring trust for "${F}" anyway.`);let X=filterWorkspaces(mergePublishables(discoverWorkspaces(n,{includeRoot:!0}),n),{noPrivate:t.private!==!0,include:t.packages&&t.packages.length>0?t.packages:void 0}).filter(t=>t.name);if(X.length===0)return ge.error(`gjsify trust: no publishable packages matched.`),process.exit(1);ge.log(`gjsify trust: ${X.length} package(s) | repo=${N} workflow=${F}`),W&&ge.log(`(dry-run — nothing will be written)`),ge.log();let Z=createTrustRequester({npmrc:S,otpProvider:new OtpProvider(t.otp)}),te=0,ne=0,re=0,ie=0,ae=[],oe=[];for(let n of X){let C=n.name,Y=trustUrl(t.registry??registryFor(C,S)??ph,C);process.stdout.write(`→ ${C.padEnd(42)} `);let X=await Z(`GET`,Y),Q=classifyTrustList(X.status,X.json,{repository:N,workflow:F});if(H){Q===`trusted`?ge.log(`trusted`):Q===`unpublished`?ge.log(`unpublished`):Q===`auth-required`?ge.log(`auth-required (could not read)`):Q===`untrusted`?ge.log(`not trusted`):ge.log(`error (HTTP ${X.status})`);continue}if(Q===`trusted`&&!q){ge.log(`already configured — skip`),ne++;continue}if(Q===`unpublished`){ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C);continue}if(W){ge.log(`would configure`),te++;continue}let se=await Z(`POST`,Y,githubTrustBody({repository:N,workflow:F,environment:I}));se.status>=200&&se.status<300?(ge.log(`configured`),te++):se.status===409?(ge.log(`already configured (409) — done`),ne++):se.status===404?(ge.log(`not on npm yet — needs first-publish, skip`),re++,ae.push(C)):(ge.log(`FAILED (HTTP ${se.status})`),ie++,oe.push(`${C} — HTTP ${se.status}${se.text?`: ${firstLine(se.text)}`:``}`))}if(!H){if(ge.log(),ge.log(`Done: ${te} ${W?`would-configure`:`configured`}, ${ne} already-configured, ${re} unpublished, ${ie} failed.`),ae.length>0){ge.log("Need a first publish before they can be trust-configured (then re-run `gjsify trust`):");for(let t of ae)ge.log(` ${t}`)}if(oe.length>0){ge.log("Failed (re-run `gjsify trust` — it is incremental; usually a lapsed 2FA window or rate-limit):");for(let t of oe)ge.log(` ${t}`);return W||(ge.log(),ge.log(vK)),process.exit(1)}W||(ge.log(),ge.log(vK))}}}});function resolveRepoRoot(t){let n=findWorkspaceRoot(t);if(n)return n;let S=spawnSync(`git`,[`rev-parse`,`--show-toplevel`],{cwd:t,encoding:`utf8`});if(S.status===0){let t=S.stdout.trim();if(t&&existsSync(t))return t}return t}function assertEveryPatternMatches(t,n){let S=n.filter(n=>{try{return discoverWorkspaces(t,{patterns:[n]}).length===0}catch{return!0}});if(S.length===0)return;let C=[`gjsify onboard: --packages matched no package directory (${S.length} of ${n.length} pattern(s)) under ${t}:`];for(let t of S)C.push(` ${JSON.stringify(t)}`);throw C.push(" Patterns are DIRECTORY globs resolved against the repo root, and only `*` is supported",` (one path segment). A matched directory needs a package.json with a "name".`),Error(C.join(`
|
|
1308
1308
|
`))}function collectOnboardPackages(t,n,S={}){let C=[],N=[],F=new Set,take=(t,n,S)=>{let I=0;for(let t of n)!t.name||F.has(t.name)||(F.add(t.name),N.push(t),I++);C.push({kind:t,patterns:S,count:I})};if(existsSync(zn(t,`package.json`)))try{take(`workspaces`,discoverWorkspaces(t,{includeRoot:!0}))}catch{}return S.patterns&&S.patterns.length>0&&take(`packages`,discoverWorkspaces(t,{patterns:[...S.patterns]}),S.patterns),take(`scanned-dirs`,mergePublishables([],n)),{packages:N,sources:C}}function describeSources(t){return t.filter(t=>t.count>0).map(t=>t.patterns?`${t.kind}(${t.patterns.join(`,`)})=${t.count}`:`${t.kind}=${t.count}`).join(` + `)}function declaredRepository(t){let n=t.manifest.repository,S=typeof n==`string`?n:n?.url;return typeof S!=`string`||S.length===0?null:parseRepoFromGitRemote(S)}function assertRepositoryAgreement(t,n){let S=n.toLowerCase(),C=t.map(t=>({ws:t,declared:declaredRepository(t)})).filter(t=>t.declared!==null&&t.declared.toLowerCase()!==S);if(C.length===0)return;let N=new Map;for(let{ws:t,declared:n}of C){let S=N.get(n)??[];S.push(t.name),N.set(n,S)}let F=[`gjsify onboard: ${C.length} selected package(s) declare a DIFFERENT repository than ${n}:`];for(let[t,n]of N){let S=n.slice(0,5).join(`, `),C=n.length>5?`, … (+${n.length-5} more)`:``;F.push(` ${t}: ${n.length} package(s) — ${S}${C}`)}throw F.push(` A Trusted Publisher scoped to the wrong repository points that package's OIDC exchange`,` at a workflow that does not publish it, which breaks the release this sweep protects.`,` Either exclude them (--exclude), select only what belongs here (--include), or point`,` --repository at the repo that actually publishes them.`),Error(F.join(`
|
|
1309
|
-
`))}var Pq=__esmMin(()=>{af(),cv(),GI(),Xn(),kq(),jq(),qI()});function describeRateLimitHeaders(t){if(!t)return`no headers captured`;let n=[];return t.forEach((t,S)=>{(/^retry-after$/i.test(S)||/ratelimit/i.test(S))&&n.push(`${S}: ${t}`)}),n.length>0?n.join(`, `):`npm sent no Retry-After and no rate-limit headers`}function retryAfterMs(t){let n=t?.get(`retry-after`);if(!n)return null;let S=Number.parseInt(n.trim(),10);return!Number.isFinite(S)||S<0?null:S*1e3}async function packumentExists(t,n){let S=t.endsWith(`/`)?t.slice(0,-1):t;try{let t=await fetch(`${S}/${n.replace(`/`,`%2f`)}`,{method:`GET`,headers:{accept:`application/vnd.npm.install-v1+json`}});return t.status===404?!1:t.ok?!0:null}catch{return null}}function actionForState(t){switch(t){case`trusted`:return`skip`;case`untrusted`:return`trust`;case`unpublished`:return`publish-and-trust`;default:return`blocked`}}function defaultSleep(t){return new Promise(n=>setTimeout(n,t))}async function requestWaitingOutRateLimit(t,n,S,C,N={}){let F=N.sleep??defaultSleep,I=N.maxRateLimitWaitMs??3e5,H=N.rateLimitBaseDelayMs??2e3,W=N.gate;W&&await W.wait();let q=await t(n,S,C),Y=0;for(let X=0;q.status===429&&Y<I;X++){let Z=retryAfterMs(q.headers),te=Math.min(Z??H*2**X,Fq),ne=Math.min(te,I-Y);N.onRateLimit?.({url:S,headers:describeRateLimitHeaders(q.headers),waitMs:ne,fromRetryAfter:Z!==null}),W?.penalize(ne),await(W?W.wait():F(ne)),Y+=ne,q=await t(n,S,C)}return q}async function probeTrustState(t,n,S,C={}){let N=S.registryOverride??registryFor(n.name,S.npmrc)??ph,F=trustUrl(N,n.name),I={repository:S.repository,workflow:S.workflow},H=C.sleep??defaultSleep,W=await requestWaitingOutRateLimit(t,`GET`,F,void 0,C),q=classifyTrustList(W.status,W.json,I);return q===`auth-required`&&C.retryOn401!==!1&&(await H(C.retryDelayMs??400),W=await t(`GET`,F),q=classifyTrustList(W.status,W.json,I)),(q===`untrusted`||q===`auth-required`)&&await(C.exists??packumentExists)(N,n.name)===!1&&(q=`unpublished`),{ws:n,registry:N,url:F,state:q,httpStatus:W.status,action:actionForState(q)}}async function probeAllTrustStates(t,n,S,C,N={}){if(n.length===0)return[];let F=n.length,I=0,report=t=>(I++,N.onProgress?.(I,F,t),t);return[report(await probeTrustState(t,n[0],C,N)),...await mapWithConcurrency(n.slice(1),Math.max(1,S),async n=>report(await probeTrustState(t,n,C,N)))]}async function mapWithConcurrency(t,n,S){let C=Array.from({length:t.length}),N=0,F=Array.from({length:Math.min(Math.max(1,n),t.length)},async()=>{for(;;){let n=N++;if(n>=t.length)return;C[n]=await S(t[n])}});return await Promise.all(F),C}var Fq,RateLimitGate,Iq=__esmMin(()=>{xh(),jq(),Fq=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(t={}){this.now=t.now??(()=>Date.now()),this.sleeper=t.sleep??defaultSleep}async wait(){let t=this.until-this.now();t>0&&await this.sleeper(t)}penalize(t){this.until=Math.max(this.until,this.now()+t)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(t,n,S){let C=S.failed??0;if(S.asJson)process.stdout.write(`${JSON.stringify({ok:C===0,dryRun:S.dryRun,root:S.root,sources:S.sources,discovered:S.discovered,total:n.length,published:t.filter(t=>t.result===`published`||t.result===`published+trusted`).length,trusted:t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length,alreadyDone:t.filter(t=>t.result===`already-done`).length,failed:C,results:t},null,2)}\n`);else{let n=S.dryRun?C>0?`Dry-run INCOMPLETE — nothing changed, but ${C} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${t.filter(t=>t.result.includes(`published`)).length} published, ${t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length} trusted, ${t.filter(t=>t.result===`already-done`).length} already done, ${C} failed.`;process.stdout.write(`\n${n}\n`)}process.exit(+(C>0))}function statusCell(t){switch(t.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${t.httpStatus})`}}async function ensureAuthenticated(t){let{npmrc:n,registry:S,cwd:C,nonInteractive:N,dryRun:F,otp:I,log:H}=t;if(hasAnyCredential(n))try{let t=await whoami(S,n);if(t.username)return t.username}catch{}if(F){H(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(N)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");H(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:S,otp:I,cwd:C})).username}catch(t){throw t instanceof LoginError?Error(t.message):t}}async function buildIfPresent(t,n){if(typeof(t.manifest.scripts??{}).build!=`string`)return;let S=detectPackageManager(),C=[`run`,`build`];n(` $ ${S} ${C.join(` `)}`);let{code:N}=await spawnToCompletion(S,C,{completion:`return`,cwd:t.location,env:{...process.env}});if(N!==0)throw Error(`build exited with code ${N}`)}function describePublishFailure(t){if(t.ok)return`unexpected successful publish outcome: ${t.action}`;switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:return`OIDC token exchange failed: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`oidc-no-token`:return`OIDC token exchange unavailable and no fallback token: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`diagnostic`:return`HTTP 404 (${t.diag.reason})`;case`publish-unconfirmed`:return`npm ${t.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${t.putStatus}) but ${t.name}@${t.version} did not resolve on ${t.registry} after ${t.readback.attempts} probe(s) over ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}: ${t.readback.verdictDetail}]`;case`blocked-missing-dependency`:return`not published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `)}. Bootstrap the target BEFORE its dependent; that order is a correctness property`;case`held-unpublished-dependency`:{let n=t.reasons.map(t=>`${t.block}.${t.name}@${t.version} (${t.detail})`).join(`, `);return`not published — ${t.reasons.length} intra-repo pin(s) name a version ${t.registry} does not serve yet: ${n}. The package is held until the dependency is available.`}case`error`:return`HTTP ${t.status} ${t.statusText}: ${t.text}`;default:return assertNeverDescribeFailure(t)}}function assertNeverDescribeFailure(t){let n=t,S=typeof n.action==`string`?n.action:`unknown`,C=n.error,N=C instanceof Error?C.message:C?String(C):``;return`publish failed: ${S}${N?` — ${N}`:``}`}var Lq,Rq,zq=__esmMin(()=>{_e(),cv(),xh(),GI(),DB(),qK(),vK(),LK(),YK(),Nq(),Tq(),hB(),hv(),Pq(),jq(),Iq(),Lq=4,Rq={command:`onboard`,description:`Ensure every publishable package in a monorepo is both published on npm and has a Trusted Publisher configured for its release workflow — publishing/trusting only what is missing, one shared OTP across the whole sweep. Works on npm/yarn workspaces and, via --packages, on a monorepo with no workspace manifest at all. Idempotent.`,builder:t=>t.option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish via OIDC (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code, used as the initial shared code. Prompted on demand (once) if omitted and a challenge occurs.`,type:`string`}).option(`packages`,{description:'Directory glob naming package folders, resolved against the repo root (repeatable). For a monorepo that is not an npm/yarn workspace — `--packages "*"` in a repo whose 703 package directories sit at the top level. Merged with the root manifest\'s own `workspaces` globs when it has any. A pattern matching NO directory is a hard error.',type:`string`,array:!0}).option(`include`,{description:`Glob pattern to include packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`access`,{description:"npm access for a FIRST publish — `public` or `restricted`. Only ever applied to a package this sweep publishes; an already-published package keeps whatever access it has.",type:`string`,choices:[`public`,`restricted`],default:`public`}).option(`build`,{description:"Run each to-be-published package's `build` script first. `--no-build` skips it, for a repo whose packages are generated artifacts with nothing to build.",type:`boolean`,default:!0}).option(`verbose`,{description:`List every package in the plan table, including the ones already published + trusted (by default only the rows needing work are listed; the counts always cover all of them).`,type:`boolean`,alias:`v`,default:!1}).option(`concurrency`,{description:`How many packages to probe (read state) in parallel (kept small so a single token does not burst npm; the first read is always serial to prompt for the shared OTP once).`,type:`number`,default:4}).option(`write-concurrency`,{description:`How many Trusted-Publisher writes to issue in parallel. It buys FEWER 2FA PROMPTS more than it buys speed: an npm code lives about 30 seconds, so a serial sweep crosses a code boundary every ~38 packages. Raising it does not beat npm's rate limit — a 429 anywhere now pauses the whole sweep, so it self-paces down to whatever the registry will serve. Publishes are unaffected: they stay serial, because publish ORDER is a correctness property.`,type:`number`,default:Lq}).option(`dry-run`,{description:`Report the plan (what would be published / trusted) without changing anything.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit a machine-readable summary object as the final line of stdout.`,type:`boolean`,default:!1}).option(`yes`,{description:`Non-interactive: never prompt. Fail clearly if a login or an OTP is required and not supplied via flags.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]===!0,C=t.json===!0,N=t.yes===!0,log=(t=``)=>{C?process.stderr.write(`${t}\n`):writeAroundPrompt(`${t}\n`)},F=await loadNpmrc(n),I=t.registry??process.env.npm_config_registry??F.registry??ph,H;try{H=await ensureAuthenticated({npmrc:F,registry:I,cwd:n,nonInteractive:N,dryRun:S,otp:t.otp,log})}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:n})}\n`):ge.error(n),process.exit(1)}F=await loadNpmrc(n),H&&log(`gjsify onboard: authenticated as ${H}`);let W=t.repository;if(!W){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(W=parseRepoFromGitRemote(t.stdout)??void 0)}if(!W||!validateRepository(W)){let t=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:t})}\n`):ge.error(t),process.exit(1)}let q=normalizeWorkflowFile(t.workflow),Y=t.environment,X=resolveRepoRoot(n),Z,te;try{t.packages&&t.packages.length>0&&assertEveryPatternMatches(X,t.packages);let S=collectOnboardPackages(X,n,{patterns:t.packages});Z=S.packages,te=describeSources(S.sources)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:n})}\n`):ge.error(n),process.exit(1)}let ne=filterWorkspaces(Z,{noPrivate:!0,include:t.include,exclude:t.exclude}).filter(t=>t.name);if(ne.length===0){let t=`gjsify onboard: no publishable packages found under ${X} (discovered ${Z.length}${te?` — ${te}`:``}). `+(Z.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:t})}\n`):ge.error(t),process.exit(1)}try{assertRepositoryAgreement(ne,W)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:n})}\n`):ge.error(n),process.exit(1)}log(`gjsify onboard: root=${X} | ${te}`),log(`gjsify onboard: ${ne.length} of ${Z.length} package(s) selected | repo=${W} workflow=${q}`),S&&log(`(dry-run — nothing will be published or configured)`),log();let re=new OtpProvider(t.otp,N?async()=>``:void 0,{registry:I}),ie=createTrustRequester({npmrc:F,otpProvider:re}),ae=new RateLimitGate,oe=!1,onRateLimit=t=>{oe||(oe=!0,log(` npm rate limit hit. ${t.headers}. Waiting ${Math.round(t.waitMs/1e3)}s (${t.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:ae,onRateLimit},se=Math.max(1,Math.min(50,Math.ceil(ne.length/10))),ce=0,le=0,ue=0;ne.length>se&&log(`Reading trust state for ${ne.length} package(s)…`);let de=await probeAllTrustStates(ie,ne,Math.max(1,t.concurrency),{registryOverride:t.registry,npmrc:F,repository:W,workflow:q},{...Q,onProgress:(t,n,S)=>{if(S.action===`trust`||S.action===`publish-and-trust`?ce++:S.action===`skip`?le++:ue++,t%se!==0&&t!==n||n<=se)return;let C=[`${ce} to do`,`${le} already done`];ue>0&&C.push(`${ue} unreadable`),log(` read ${t}/${n} — ${C.join(`, `)}`)}}),fe=de.filter(t=>t.action===`publish-and-trust`),pe=de.filter(t=>t.action===`trust`),me=de.filter(t=>t.action===`skip`),he=de.filter(t=>t.action===`blocked`);for(let n of de)n.action===`skip`&&t.verbose!==!0||log(` ${statusCell(n)} ${n.ws.name}`);!t.verbose&&me.length>0&&log(` (${me.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${me.length} already done, ${fe.length} to publish+trust, ${pe.length} to trust, ${he.length} unreadable.`);let _e=he.filter(t=>t.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ve=[];if(S){for(let t of de)ve.push({name:t.ws.name,result:t.action===`skip`?`already-done`:t.action===`blocked`?`failed`:`skipped-dry-run`,detail:t.action===`publish-and-trust`?`would publish + trust`:t.action===`trust`?`would trust`:t.action===`blocked`?`state HTTP ${t.httpStatus}`:void 0});finish(ve,de,{asJson:C,dryRun:S,failed:he.length,root:X,sources:te,discovered:Z.length});return}let ye=githubTrustBody({repository:W,workflow:q,environment:Y}),be=Math.max(1,t[`write-concurrency`]),xe=fe.length+pe.length,Se=Array.from({length:de.length}),Ce=0,we=0,Te=0,configureTrust=async(t,n,S)=>{let C=await requestWaitingOutRateLimit(ie,`POST`,t.url,ye,Q),N=`${++we}/${xe}`;C.status>=200&&C.status<300?(log(` [${N}] trusted ${t.ws.name}`),Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}):C.status===409?Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}:C.status===404?(log(` [${N}] ${t.ws.name}: published but not yet trust-configurable (re-run onboard)`),Se[n]={name:t.ws.name,result:S?`published`:`failed`,detail:`trust config deferred (404)`},S||Ce++):(log(` [${N}] trust failed (HTTP ${C.status}) — ${t.ws.name}`),Se[n]={name:t.ws.name,result:`failed`,detail:`trust HTTP ${C.status}`},C.status===429&&Te++,Ce++)},Ee=[],De=new Set;for(let n=0;n<de.length;n++){let S=de[n];if(S.action===`skip`){Se[n]={name:S.ws.name,result:`already-done`};continue}if(S.action===`blocked`){log(`→ ${S.ws.name}: cannot read trust state (HTTP ${S.httpStatus}) — skipped`),Se[n]={name:S.ws.name,result:`failed`,detail:`state HTTP ${S.httpStatus}`},Ce++;continue}if(S.action===`trust`){Ee.push({p:S,i:n});continue}log(`→ ${S.ws.name}: building + publishing…`);try{t.build!==!1&&await buildIfPresent(S.ws,log)}catch(t){let C=t instanceof Error?t.message:String(t);log(` build failed: ${C}`),Se[n]={name:S.ws.name,result:`failed`,detail:`build: ${C}`},Ce++;continue}let C=await publishWorkspace({assumePresent:[...De],wsDir:S.ws.location,tag:`latest`,access:t.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:S.registry,verbose:!1,json:!1,otpProvider:re,seedOtpFirst:!1});if(!C.ok){let t=describePublishFailure(C);log(` publish failed: ${t}`),Se[n]={name:S.ws.name,result:`failed`,detail:`publish: ${t}`},Ce++;continue}log(` published ${C.name}@${`version`in C?C.version:``}`+(`readback`in C&&C.readback?.confirmed?` (verified on ${C.registry} — ${C.readback.attempts} probe(s))`:C.action===`skipped-untrusted-new`?``:` (UNVERIFIED)`)),De.add(C.name),await configureTrust(S,n,C.action!==`skipped-untrusted-new`)}Ee.length>0&&(Ee.length>1&&log(`→ configuring ${Ee.length} Trusted Publisher(s), ${be} at a time…`),await mapWithConcurrency(Ee,be,async({p:t,i:n})=>configureTrust(t,n,!1)));for(let t of Se)t&&ve.push(t);Te>0&&(log(),log(`${Te} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${be}) provokes the limit less.`)),S||(log(),log(_K)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?An:On}function isInside$1(t,n,S){let C=pathFor(S);if(!C.isAbsolute(t)||!C.isAbsolute(n))return!1;let N=n.endsWith(C.sep)?n:n+C.sep;return t===n||t.startsWith(N)}function classifyInstall(t){let n=t.env??process.env,S=t.platform??process.platform,C=pathFor(S),N=C.resolve(t.selfDir);if(n.FLATPAK_ID||isInside$1(N,Vq,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${Vq}`,updateWith:`flatpak update ${t}`,managedElsewhere:!0}}return isInside$1(N,C.resolve(t.xdgPrefix),S)?{kind:`xdg-global`,evidence:`running from the user-global prefix ${t.xdgPrefix}`,managedElsewhere:!1}:S!==`win32`&&Bq.some(t=>isInside$1(N,t,S))?{kind:`system-package`,evidence:`running from the system prefix ${N}`,updateWith:"your distribution package manager (`apt upgrade` / `dnf upgrade` / …), or install the newer package from https://github.com/gjsify/gjsify/releases/latest",managedElsewhere:!0}:N.split(C.sep).includes(`node_modules`)?{kind:`npm-global`,evidence:`running from a node_modules tree at ${N}`,updateWith:`npm install -g @gjsify/cli@latest (or switch to the Node-free bootstrap)`,managedElsewhere:!0}:{kind:`unknown`,evidence:`running from ${N}, which matches no known install layout`,managedElsewhere:!1}}var Bq,Vq,Hq=__esmMin(()=>{Xn(),Bq=[`/usr/`,`/opt/`,`/snap/`],Vq=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?An:On,norm=t=>n===`win32`?S.resolve(t).toLowerCase():S.resolve(t);if(t.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${t.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${t.binDir}`};if(norm(S.dirname(t.resolvedBin))===norm(t.binDir))return{ok:!0};let C=t.runningVersion?` (v${t.runningVersion})`:``;return{ok:!1,message:`BUT \`${t.binName}\` on PATH resolves to\n ${t.resolvedBin}${C}\nwhich is NOT the install that was just updated, so the next \`${t.binName}\`\nyou run will not be v${t.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${Uq}\`)\n or put ${t.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${t.binName} --version\`.`}}function isNextChannelVersion(t){return t?(parse(t)?.prerelease??[]).some(t=>t===`next`):!1}function nextChannelNotice(t){return t.requestedTag!==void 0||!isNextChannelVersion(t.currentVersion)?null:`Note: v${t.currentVersion} is a \`next\` prerelease; updating without --tag moves you to \`${Wq}\`. Use \`--tag next\` to stay on the next channel.`}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return Hn(In(t));let n=fileURLToPath(import.meta.url),S=Hn(In(n));for(let t=0;t<8&&S!==Hn(S);t++){if(existsSync(zn(S,`package.json`)))return S;S=Hn(S)}return Hn(In(n))}function readCurrentVersion(){try{let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t){let n=JSON.parse(readFileSync(t,`utf-8`));return n.name===Uq&&typeof n.version==`string`?n.version:null}let n=Hn(In(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==Hn(n);t++){let t=zn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===Uq&&typeof n.version==`string`)return n.version}n=Hn(n)}}catch{}return null}function resolveTag(t,n){let S=t[`dist-tags`]??{};return S[n]?S[n]:t.versions&&typeof t.versions==`object`&&t.versions[n]?n:null}var Uq,Wq,Gq,Kq,qq=__esmMin(()=>{_e(),af(),Xn(),cr(),xh(),HI(),Gz(),Hq(),Yz(),$z(),Az(),Mz(),Uq=`@gjsify/cli`,Wq=`latest`,Gq={command:`self-update`,description:`Update the installed ${Uq} to the latest release (or pinned --tag).`,builder:t=>t.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async t=>{let n=defaultGlobalLayout(),S=zn(zn(n.prefix,`node_modules`,Uq),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${Uq}: v${C??`(unknown)`}`);let F=classifyInstall({selfDir:readSelfDir(),xdgPrefix:n.prefix});if(F.managedElsewhere)return ge.error(`\ngjsify self-update: this gjsify is managed by something else — ${F.evidence}.\nUpdating it from here would write ${n.prefix} and leave you running two installs.\n\nUpdate with: ${F.updateWith}\n`),process.exit(1);N||ge.warn(`\nWarning: no @gjsify/cli install found under ${n.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`);let I=t.tag??Wq,H=nextChannelNotice({currentVersion:C,requestedTag:t.tag});H&&ge.log(H),ge.log(`Fetching dist-tags for ${Uq}@${I} ...`);let W;try{W=await fetchPackument(Uq)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`Failed to fetch packument: ${n}`),process.exit(1)}let q=resolveTag(W,I);if(!q)return ge.error(`Unknown dist-tag '${I}' on ${Uq}. Known tags: ${Object.keys(W[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ge.log(`Latest matching --tag ${I}: v${q}`);let Y=N&&!hasBundlerEngineInstalled(n.prefix),X=Y&&!t.skipDeps&&!t.check;if(C===q&&!t.force&&!X){ge.log(`Already up to date (v${q}).`),Y&&t.skipDeps&&ge.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),t.check||ge.log(`Run with --force to reinstall anyway.`);return}if(X&&C===q&&!t.force&&ge.log(`@gjsify/cli is at v${q} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),t.check)return ge.log(C?`Update available: v${C} → v${q}`:`Install required: → v${q}`),process.exit(1);let Z=!t.skipDeps,te=Z?` + runtime dependencies`:` (bundle only)`;ge.log(`Installing ${Uq}@${q}${te} ...`);let ne=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${Uq}@${q}`],verbose:!1,skipDeps:!Z,progress:ne})}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`self-update: install failed — ${n}`),ge.error("Re-run `gjsify self-update` to retry."),process.exit(1)}Z&&await installGjsEnginePackages(n.prefix,q,{verbose:!1}),t.prune!==!1&&pruneAfterInstall(n.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let re=linkGlobalBins([Uq],n);if(re.length===0)ge.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let t of re)ge.log(` • ${t.link} → ${t.target}`);if(globalLayoutIsDefault()){let t=verifyPathResolution({binName:Kq,binDir:n.binDir,resolvedBin:resolveBinOnPath(Kq,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:q});if(!t.ok)return ge.error(`\nInstalled ${Uq} v${q} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${Uq} to v${q}.`),Z?ge.log(`Runtime dependencies were resolved alongside the bundle.`):ge.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},Kq=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1309
|
+
`))}var Fq=__esmMin(()=>{af(),cv(),GI(),Xn(),Aq(),Mq(),qI()});function describeRateLimitHeaders(t){if(!t)return`no headers captured`;let n=[];return t.forEach((t,S)=>{(/^retry-after$/i.test(S)||/ratelimit/i.test(S))&&n.push(`${S}: ${t}`)}),n.length>0?n.join(`, `):`npm sent no Retry-After and no rate-limit headers`}function retryAfterMs(t){let n=t?.get(`retry-after`);if(!n)return null;let S=Number.parseInt(n.trim(),10);return!Number.isFinite(S)||S<0?null:S*1e3}async function packumentExists(t,n){let S=t.endsWith(`/`)?t.slice(0,-1):t;try{let t=await fetch(`${S}/${n.replace(`/`,`%2f`)}`,{method:`GET`,headers:{accept:`application/vnd.npm.install-v1+json`}});return t.status===404?!1:t.ok?!0:null}catch{return null}}function actionForState(t){switch(t){case`trusted`:return`skip`;case`untrusted`:return`trust`;case`unpublished`:return`publish-and-trust`;default:return`blocked`}}function defaultSleep(t){return new Promise(n=>setTimeout(n,t))}async function requestWaitingOutRateLimit(t,n,S,C,N={}){let F=N.sleep??defaultSleep,I=N.maxRateLimitWaitMs??3e5,H=N.rateLimitBaseDelayMs??2e3,W=N.gate;W&&await W.wait();let q=await t(n,S,C),Y=0;for(let X=0;q.status===429&&Y<I;X++){let Z=retryAfterMs(q.headers),te=Math.min(Z??H*2**X,Iq),ne=Math.min(te,I-Y);N.onRateLimit?.({url:S,headers:describeRateLimitHeaders(q.headers),waitMs:ne,fromRetryAfter:Z!==null}),W?.penalize(ne),await(W?W.wait():F(ne)),Y+=ne,q=await t(n,S,C)}return q}async function probeTrustState(t,n,S,C={}){let N=S.registryOverride??registryFor(n.name,S.npmrc)??ph,F=trustUrl(N,n.name),I={repository:S.repository,workflow:S.workflow},H=C.sleep??defaultSleep,W=await requestWaitingOutRateLimit(t,`GET`,F,void 0,C),q=classifyTrustList(W.status,W.json,I);return q===`auth-required`&&C.retryOn401!==!1&&(await H(C.retryDelayMs??400),W=await t(`GET`,F),q=classifyTrustList(W.status,W.json,I)),(q===`untrusted`||q===`auth-required`)&&await(C.exists??packumentExists)(N,n.name)===!1&&(q=`unpublished`),{ws:n,registry:N,url:F,state:q,httpStatus:W.status,action:actionForState(q)}}async function probeAllTrustStates(t,n,S,C,N={}){if(n.length===0)return[];let F=n.length,I=0,report=t=>(I++,N.onProgress?.(I,F,t),t);return[report(await probeTrustState(t,n[0],C,N)),...await mapWithConcurrency(n.slice(1),Math.max(1,S),async n=>report(await probeTrustState(t,n,C,N)))]}async function mapWithConcurrency(t,n,S){let C=Array.from({length:t.length}),N=0,F=Array.from({length:Math.min(Math.max(1,n),t.length)},async()=>{for(;;){let n=N++;if(n>=t.length)return;C[n]=await S(t[n])}});return await Promise.all(F),C}var Iq,RateLimitGate,Lq=__esmMin(()=>{xh(),Mq(),Iq=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(t={}){this.now=t.now??(()=>Date.now()),this.sleeper=t.sleep??defaultSleep}async wait(){let t=this.until-this.now();t>0&&await this.sleeper(t)}penalize(t){this.until=Math.max(this.until,this.now()+t)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(t,n,S){let C=S.failed??0;if(S.asJson)process.stdout.write(`${JSON.stringify({ok:C===0,dryRun:S.dryRun,root:S.root,sources:S.sources,discovered:S.discovered,total:n.length,published:t.filter(t=>t.result===`published`||t.result===`published+trusted`).length,trusted:t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length,alreadyDone:t.filter(t=>t.result===`already-done`).length,failed:C,results:t},null,2)}\n`);else{let n=S.dryRun?C>0?`Dry-run INCOMPLETE — nothing changed, but ${C} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${t.filter(t=>t.result.includes(`published`)).length} published, ${t.filter(t=>t.result===`trusted`||t.result===`published+trusted`).length} trusted, ${t.filter(t=>t.result===`already-done`).length} already done, ${C} failed.`;process.stdout.write(`\n${n}\n`)}process.exit(+(C>0))}function statusCell(t){switch(t.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${t.httpStatus})`}}async function ensureAuthenticated(t){let{npmrc:n,registry:S,cwd:C,nonInteractive:N,dryRun:F,otp:I,log:H}=t;if(hasAnyCredential(n))try{let t=await whoami(S,n);if(t.username)return t.username}catch{}if(F){H(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(N)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");H(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:S,otp:I,cwd:C})).username}catch(t){throw t instanceof LoginError?Error(t.message):t}}async function buildIfPresent(t,n){if(typeof(t.manifest.scripts??{}).build!=`string`)return;let S=detectPackageManager(),C=[`run`,`build`];n(` $ ${S} ${C.join(` `)}`);let{code:N}=await spawnToCompletion(S,C,{completion:`return`,cwd:t.location,env:{...process.env}});if(N!==0)throw Error(`build exited with code ${N}`)}function describePublishFailure(t){if(t.ok)return`unexpected successful publish outcome: ${t.action}`;switch(t.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:return`OIDC token exchange failed: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`oidc-no-token`:return`OIDC token exchange unavailable and no fallback token: ${t.error instanceof Error?t.error.message:String(t.error)}`;case`diagnostic`:return`HTTP 404 (${t.diag.reason})`;case`publish-unconfirmed`:return`npm ${t.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${t.putStatus}) but ${t.name}@${t.version} did not resolve on ${t.registry} after ${t.readback.attempts} probe(s) over ${(t.readback.elapsedMs/1e3).toFixed(1)}s [${t.readback.verdict}: ${t.readback.verdictDetail}]`;case`blocked-missing-dependency`:return`not published — ${t.missing.length} required pin(s) name a package ${t.registry} does not have: ${t.missing.map(t=>`${t.block}.${t.name}@${t.spec}`).join(`, `)}. Bootstrap the target BEFORE its dependent; that order is a correctness property`;case`held-unpublished-dependency`:{let n=t.reasons.map(t=>`${t.block}.${t.name}@${t.version} (${t.detail})`).join(`, `);return`not published — ${t.reasons.length} intra-repo pin(s) name a version ${t.registry} does not serve yet: ${n}. The package is held until the dependency is available.`}case`error`:return`HTTP ${t.status} ${t.statusText}: ${t.text}`;default:return assertNeverDescribeFailure(t)}}function assertNeverDescribeFailure(t){let n=t,S=typeof n.action==`string`?n.action:`unknown`,C=n.error,N=C instanceof Error?C.message:C?String(C):``;return`publish failed: ${S}${N?` — ${N}`:``}`}var Rq,zq,Bq=__esmMin(()=>{_e(),cv(),xh(),GI(),DB(),JK(),yK(),RK(),XK(),Pq(),Eq(),hB(),hv(),Fq(),Mq(),Lq(),Rq=4,zq={command:`onboard`,description:`Ensure every publishable package in a monorepo is both published on npm and has a Trusted Publisher configured for its release workflow — publishing/trusting only what is missing, one shared OTP across the whole sweep. Works on npm/yarn workspaces and, via --packages, on a monorepo with no workspace manifest at all. Idempotent.`,builder:t=>t.option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish via OIDC (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${ph}).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code, used as the initial shared code. Prompted on demand (once) if omitted and a challenge occurs.`,type:`string`}).option(`packages`,{description:'Directory glob naming package folders, resolved against the repo root (repeatable). For a monorepo that is not an npm/yarn workspace — `--packages "*"` in a repo whose 703 package directories sit at the top level. Merged with the root manifest\'s own `workspaces` globs when it has any. A pattern matching NO directory is a hard error.',type:`string`,array:!0}).option(`include`,{description:`Glob pattern to include packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`access`,{description:"npm access for a FIRST publish — `public` or `restricted`. Only ever applied to a package this sweep publishes; an already-published package keeps whatever access it has.",type:`string`,choices:[`public`,`restricted`],default:`public`}).option(`build`,{description:"Run each to-be-published package's `build` script first. `--no-build` skips it, for a repo whose packages are generated artifacts with nothing to build.",type:`boolean`,default:!0}).option(`verbose`,{description:`List every package in the plan table, including the ones already published + trusted (by default only the rows needing work are listed; the counts always cover all of them).`,type:`boolean`,alias:`v`,default:!1}).option(`concurrency`,{description:`How many packages to probe (read state) in parallel (kept small so a single token does not burst npm; the first read is always serial to prompt for the shared OTP once).`,type:`number`,default:4}).option(`write-concurrency`,{description:`How many Trusted-Publisher writes to issue in parallel. It buys FEWER 2FA PROMPTS more than it buys speed: an npm code lives about 30 seconds, so a serial sweep crosses a code boundary every ~38 packages. Raising it does not beat npm's rate limit — a 429 anywhere now pauses the whole sweep, so it self-paces down to whatever the registry will serve. Publishes are unaffected: they stay serial, because publish ORDER is a correctness property.`,type:`number`,default:Rq}).option(`dry-run`,{description:`Report the plan (what would be published / trusted) without changing anything.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit a machine-readable summary object as the final line of stdout.`,type:`boolean`,default:!1}).option(`yes`,{description:`Non-interactive: never prompt. Fail clearly if a login or an OTP is required and not supplied via flags.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t[`dry-run`]===!0,C=t.json===!0,N=t.yes===!0,log=(t=``)=>{C?process.stderr.write(`${t}\n`):writeAroundPrompt(`${t}\n`)},F=await loadNpmrc(n),I=t.registry??process.env.npm_config_registry??F.registry??ph,H;try{H=await ensureAuthenticated({npmrc:F,registry:I,cwd:n,nonInteractive:N,dryRun:S,otp:t.otp,log})}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:n})}\n`):ge.error(n),process.exit(1)}F=await loadNpmrc(n),H&&log(`gjsify onboard: authenticated as ${H}`);let W=t.repository;if(!W){let t=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:n,encoding:`utf8`});t.status===0&&(W=parseRepoFromGitRemote(t.stdout)??void 0)}if(!W||!validateRepository(W)){let t=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:t})}\n`):ge.error(t),process.exit(1)}let q=normalizeWorkflowFile(t.workflow),Y=t.environment,X=resolveRepoRoot(n),Z,te;try{t.packages&&t.packages.length>0&&assertEveryPatternMatches(X,t.packages);let S=collectOnboardPackages(X,n,{patterns:t.packages});Z=S.packages,te=describeSources(S.sources)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:n})}\n`):ge.error(n),process.exit(1)}let ne=filterWorkspaces(Z,{noPrivate:!0,include:t.include,exclude:t.exclude}).filter(t=>t.name);if(ne.length===0){let t=`gjsify onboard: no publishable packages found under ${X} (discovered ${Z.length}${te?` — ${te}`:``}). `+(Z.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:t})}\n`):ge.error(t),process.exit(1)}try{assertRepositoryAgreement(ne,W)}catch(t){let n=t instanceof Error?t.message:String(t);return C?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:n})}\n`):ge.error(n),process.exit(1)}log(`gjsify onboard: root=${X} | ${te}`),log(`gjsify onboard: ${ne.length} of ${Z.length} package(s) selected | repo=${W} workflow=${q}`),S&&log(`(dry-run — nothing will be published or configured)`),log();let re=new OtpProvider(t.otp,N?async()=>``:void 0,{registry:I}),ie=createTrustRequester({npmrc:F,otpProvider:re}),ae=new RateLimitGate,oe=!1,onRateLimit=t=>{oe||(oe=!0,log(` npm rate limit hit. ${t.headers}. Waiting ${Math.round(t.waitMs/1e3)}s (${t.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:ae,onRateLimit},se=Math.max(1,Math.min(50,Math.ceil(ne.length/10))),ce=0,le=0,ue=0;ne.length>se&&log(`Reading trust state for ${ne.length} package(s)…`);let de=await probeAllTrustStates(ie,ne,Math.max(1,t.concurrency),{registryOverride:t.registry,npmrc:F,repository:W,workflow:q},{...Q,onProgress:(t,n,S)=>{if(S.action===`trust`||S.action===`publish-and-trust`?ce++:S.action===`skip`?le++:ue++,t%se!==0&&t!==n||n<=se)return;let C=[`${ce} to do`,`${le} already done`];ue>0&&C.push(`${ue} unreadable`),log(` read ${t}/${n} — ${C.join(`, `)}`)}}),fe=de.filter(t=>t.action===`publish-and-trust`),pe=de.filter(t=>t.action===`trust`),me=de.filter(t=>t.action===`skip`),he=de.filter(t=>t.action===`blocked`);for(let n of de)n.action===`skip`&&t.verbose!==!0||log(` ${statusCell(n)} ${n.ws.name}`);!t.verbose&&me.length>0&&log(` (${me.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${me.length} already done, ${fe.length} to publish+trust, ${pe.length} to trust, ${he.length} unreadable.`);let _e=he.filter(t=>t.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ve=[];if(S){for(let t of de)ve.push({name:t.ws.name,result:t.action===`skip`?`already-done`:t.action===`blocked`?`failed`:`skipped-dry-run`,detail:t.action===`publish-and-trust`?`would publish + trust`:t.action===`trust`?`would trust`:t.action===`blocked`?`state HTTP ${t.httpStatus}`:void 0});finish(ve,de,{asJson:C,dryRun:S,failed:he.length,root:X,sources:te,discovered:Z.length});return}let ye=githubTrustBody({repository:W,workflow:q,environment:Y}),be=Math.max(1,t[`write-concurrency`]),xe=fe.length+pe.length,Se=Array.from({length:de.length}),Ce=0,we=0,Te=0,configureTrust=async(t,n,S)=>{let C=await requestWaitingOutRateLimit(ie,`POST`,t.url,ye,Q),N=`${++we}/${xe}`;C.status>=200&&C.status<300?(log(` [${N}] trusted ${t.ws.name}`),Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}):C.status===409?Se[n]={name:t.ws.name,result:S?`published+trusted`:`trusted`}:C.status===404?(log(` [${N}] ${t.ws.name}: published but not yet trust-configurable (re-run onboard)`),Se[n]={name:t.ws.name,result:S?`published`:`failed`,detail:`trust config deferred (404)`},S||Ce++):(log(` [${N}] trust failed (HTTP ${C.status}) — ${t.ws.name}`),Se[n]={name:t.ws.name,result:`failed`,detail:`trust HTTP ${C.status}`},C.status===429&&Te++,Ce++)},Ee=[],De=new Set;for(let n=0;n<de.length;n++){let S=de[n];if(S.action===`skip`){Se[n]={name:S.ws.name,result:`already-done`};continue}if(S.action===`blocked`){log(`→ ${S.ws.name}: cannot read trust state (HTTP ${S.httpStatus}) — skipped`),Se[n]={name:S.ws.name,result:`failed`,detail:`state HTTP ${S.httpStatus}`},Ce++;continue}if(S.action===`trust`){Ee.push({p:S,i:n});continue}log(`→ ${S.ws.name}: building + publishing…`);try{t.build!==!1&&await buildIfPresent(S.ws,log)}catch(t){let C=t instanceof Error?t.message:String(t);log(` build failed: ${C}`),Se[n]={name:S.ws.name,result:`failed`,detail:`build: ${C}`},Ce++;continue}let C=await publishWorkspace({assumePresent:[...De],wsDir:S.ws.location,tag:`latest`,access:t.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:S.registry,verbose:!1,json:!1,otpProvider:re,seedOtpFirst:!1});if(!C.ok){let t=describePublishFailure(C);log(` publish failed: ${t}`),Se[n]={name:S.ws.name,result:`failed`,detail:`publish: ${t}`},Ce++;continue}log(` published ${C.name}@${`version`in C?C.version:``}`+(`readback`in C&&C.readback?.confirmed?` (verified on ${C.registry} — ${C.readback.attempts} probe(s))`:C.action===`skipped-untrusted-new`?``:` (UNVERIFIED)`)),De.add(C.name),await configureTrust(S,n,C.action!==`skipped-untrusted-new`)}Ee.length>0&&(Ee.length>1&&log(`→ configuring ${Ee.length} Trusted Publisher(s), ${be} at a time…`),await mapWithConcurrency(Ee,be,async({p:t,i:n})=>configureTrust(t,n,!1)));for(let t of Se)t&&ve.push(t);Te>0&&(log(),log(`${Te} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${be}) provokes the limit less.`)),S||(log(),log(vK)),finish(ve,de,{asJson:C,dryRun:S,failed:Ce,root:X,sources:te,discovered:Z.length})}}});function pathFor(t){return t===`win32`?An:On}function isInside$1(t,n,S){let C=pathFor(S);if(!C.isAbsolute(t)||!C.isAbsolute(n))return!1;let N=n.endsWith(C.sep)?n:n+C.sep;return t===n||t.startsWith(N)}function classifyInstall(t){let n=t.env??process.env,S=t.platform??process.platform,C=pathFor(S),N=C.resolve(t.selfDir);if(n.FLATPAK_ID||isInside$1(N,Hq,S)){let t=n.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:n.FLATPAK_ID?`FLATPAK_ID=${n.FLATPAK_ID}`:`running from ${Hq}`,updateWith:`flatpak update ${t}`,managedElsewhere:!0}}return isInside$1(N,C.resolve(t.xdgPrefix),S)?{kind:`xdg-global`,evidence:`running from the user-global prefix ${t.xdgPrefix}`,managedElsewhere:!1}:S!==`win32`&&Vq.some(t=>isInside$1(N,t,S))?{kind:`system-package`,evidence:`running from the system prefix ${N}`,updateWith:"your distribution package manager (`apt upgrade` / `dnf upgrade` / …), or install the newer package from https://github.com/gjsify/gjsify/releases/latest",managedElsewhere:!0}:N.split(C.sep).includes(`node_modules`)?{kind:`npm-global`,evidence:`running from a node_modules tree at ${N}`,updateWith:`npm install -g @gjsify/cli@latest (or switch to the Node-free bootstrap)`,managedElsewhere:!0}:{kind:`unknown`,evidence:`running from ${N}, which matches no known install layout`,managedElsewhere:!1}}var Vq,Hq,Uq=__esmMin(()=>{Xn(),Vq=[`/usr/`,`/opt/`,`/snap/`],Hq=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(t){let n=t.platform??process.platform,S=n===`win32`?An:On,norm=t=>n===`win32`?S.resolve(t).toLowerCase():S.resolve(t);if(t.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${t.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${t.binDir}`};if(norm(S.dirname(t.resolvedBin))===norm(t.binDir))return{ok:!0};let C=t.runningVersion?` (v${t.runningVersion})`:``;return{ok:!1,message:`BUT \`${t.binName}\` on PATH resolves to\n ${t.resolvedBin}${C}\nwhich is NOT the install that was just updated, so the next \`${t.binName}\`\nyou run will not be v${t.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${Wq}\`)\n or put ${t.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${t.binName} --version\`.`}}function isNextChannelVersion(t){return t?(parse(t)?.prerelease??[]).some(t=>t===`next`):!1}function nextChannelNotice(t){return t.requestedTag!==void 0||!isNextChannelVersion(t.currentVersion)?null:`Note: v${t.currentVersion} is a \`next\` prerelease; updating without --tag moves you to \`${Gq}\`. Use \`--tag next\` to stay on the next channel.`}function readSelfDir(){let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t)return Hn(In(t));let n=fileURLToPath(import.meta.url),S=Hn(In(n));for(let t=0;t<8&&S!==Hn(S);t++){if(existsSync(zn(S,`package.json`)))return S;S=Hn(S)}return Hn(In(n))}function readCurrentVersion(){try{let t=process.env.GJSIFY_CLI_PACKAGE_JSON;if(t){let n=JSON.parse(readFileSync(t,`utf-8`));return n.name===Wq&&typeof n.version==`string`?n.version:null}let n=Hn(In(fileURLToPath(import.meta.url)));for(let t=0;t<8&&n!==Hn(n);t++){let t=zn(n,`package.json`);if(existsSync(t)){let n=JSON.parse(readFileSync(t,`utf-8`));if(n.name===Wq&&typeof n.version==`string`)return n.version}n=Hn(n)}}catch{}return null}function resolveTag(t,n){let S=t[`dist-tags`]??{};return S[n]?S[n]:t.versions&&typeof t.versions==`object`&&t.versions[n]?n:null}var Wq,Gq,Kq,qq,Jq=__esmMin(()=>{_e(),af(),Xn(),cr(),xh(),HI(),Gz(),Uq(),Yz(),$z(),Az(),Mz(),Wq=`@gjsify/cli`,Gq=`latest`,Kq={command:`self-update`,description:`Update the installed ${Wq} to the latest release (or pinned --tag).`,builder:t=>t.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async t=>{let n=defaultGlobalLayout(),S=zn(zn(n.prefix,`node_modules`,Wq),`package.json`),C=readCurrentVersion(),N=existsSync(S);ge.log(`Current ${Wq}: v${C??`(unknown)`}`);let F=classifyInstall({selfDir:readSelfDir(),xdgPrefix:n.prefix});if(F.managedElsewhere)return ge.error(`\ngjsify self-update: this gjsify is managed by something else — ${F.evidence}.\nUpdating it from here would write ${n.prefix} and leave you running two installs.\n\nUpdate with: ${F.updateWith}\n`),process.exit(1);N||ge.warn(`\nWarning: no @gjsify/cli install found under ${n.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`);let I=t.tag??Gq,H=nextChannelNotice({currentVersion:C,requestedTag:t.tag});H&&ge.log(H),ge.log(`Fetching dist-tags for ${Wq}@${I} ...`);let W;try{W=await fetchPackument(Wq)}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`Failed to fetch packument: ${n}`),process.exit(1)}let q=resolveTag(W,I);if(!q)return ge.error(`Unknown dist-tag '${I}' on ${Wq}. Known tags: ${Object.keys(W[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ge.log(`Latest matching --tag ${I}: v${q}`);let Y=N&&!hasBundlerEngineInstalled(n.prefix),X=Y&&!t.skipDeps&&!t.check;if(C===q&&!t.force&&!X){ge.log(`Already up to date (v${q}).`),Y&&t.skipDeps&&ge.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),t.check||ge.log(`Run with --force to reinstall anyway.`);return}if(X&&C===q&&!t.force&&ge.log(`@gjsify/cli is at v${q} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),t.check)return ge.log(C?`Update available: v${C} → v${q}`:`Install required: → v${q}`),process.exit(1);let Z=!t.skipDeps,te=Z?` + runtime dependencies`:` (bundle only)`;ge.log(`Installing ${Wq}@${q}${te} ...`);let ne=makeProgressReporter();try{await installPackages({prefix:n.prefix,specs:[`${Wq}@${q}`],verbose:!1,skipDeps:!Z,progress:ne})}catch(t){let n=t instanceof Error?t.message:String(t);return ge.error(`self-update: install failed — ${n}`),ge.error("Re-run `gjsify self-update` to retry."),process.exit(1)}Z&&await installGjsEnginePackages(n.prefix,q,{verbose:!1}),t.prune!==!1&&pruneAfterInstall(n.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let re=linkGlobalBins([Wq],n);if(re.length===0)ge.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let t of re)ge.log(` • ${t.link} → ${t.target}`);if(globalLayoutIsDefault()){let t=verifyPathResolution({binName:qq,binDir:n.binDir,resolvedBin:resolveBinOnPath(qq,{pathValue:pathWithoutSelfShim()}),runningVersion:C,targetVersion:q});if(!t.ok)return ge.error(`\nInstalled ${Wq} v${q} at ${n.prefix}`),ge.error(t.message),process.exit(1)}ge.log(`\nUpdated ${Wq} to v${q}.`),Z?ge.log(`Runtime dependencies were resolved alongside the bundle.`):ge.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},qq=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1310
1310
|
/**
|
|
1311
1311
|
* gjsify universal installer — bootstraps \`@gjsify/cli\` (or any GJS app on npm)
|
|
1312
1312
|
* on a system that has only \`gjs\` and libsoup: no Node, no npm. Decision and
|
|
@@ -1882,28 +1882,28 @@ async function main() {
|
|
|
1882
1882
|
}
|
|
1883
1883
|
|
|
1884
1884
|
await main();
|
|
1885
|
-
`}function pickDefaultBinName(t,n){let S=t?.gjsify?.bin;if(S&&typeof S==`object`){let t=Object.keys(S)[0];if(t)return t}let C=t?.bin;if(C&&typeof C==`object`){let t=Object.keys(C)[0];if(t)return t}return n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n}var
|
|
1886
|
-
`).find(t=>/^exec (?:gjs -m )?'/.test(t));if(!S)continue;let F=S.match(/'([^']+)'/);if(!F)continue;let I=F[1];if(isInside(n,I)){C.push(N);for(let t of[`.cmd`,`.ps1`])existsSync(N+t)&&C.push(N+t)}}catch(t){S&&ge.warn(` ? could not inspect ${N}: ${t.message}`)}}return C}var
|
|
1885
|
+
`}function pickDefaultBinName(t,n){let S=t?.gjsify?.bin;if(S&&typeof S==`object`){let t=Object.keys(S)[0];if(t)return t}let C=t?.bin;if(C&&typeof C==`object`){let t=Object.keys(C)[0];if(t)return t}return n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n}var Yq,Xq,Zq=__esmMin(()=>{_e(),af(),Xn(),Yq=`https://github.com/gjsify/gjsify/releases/latest/download/cli.gjs.mjs`,Xq={command:`generate-installer [target]`,description:`Scaffold an install.mjs in the current directory for a GJS-runnable npm package.`,builder:t=>t.positional(`target`,{description:`Npm package name to install (default: current package.json name).`,type:`string`}).option(`bin-name`,{description:"Bin name produced by the installer (default: first key of `gjsify.bin` or `bin`).",type:`string`}).option(`bootstrap-url`,{description:`Override the cli.gjs.mjs bootstrap bundle URL (default: gjsify GitHub releases/latest).`,type:`string`}).option(`output`,{description:`Where to write the generated installer.`,type:`string`,default:`install.mjs`}).option(`force`,{description:`Overwrite an existing output file.`,type:`boolean`,default:!1}),handler:t=>{let n=In(process.cwd(),t.output);if(existsSync(n)&&!t.force)return ge.error(`${t.output} already exists. Re-run with --force to overwrite.`),process.exit(1);let S=In(process.cwd(),`package.json`),C=null;if(existsSync(S))try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{}let N=t.target??C?.name;if(!N)return ge.error("No target package: pass `gjsify generate-installer <pkg>` or run inside a directory with a package.json."),process.exit(1);let F=t[`bin-name`]??pickDefaultBinName(C,N),I=t[`bootstrap-url`]??Yq;writeFileSync(n,loadInstallerTemplate().replace(/const DEFAULT_TARGET = '[^']+';/,`const DEFAULT_TARGET = ${JSON.stringify(N)};`).replace(/const DEFAULT_BIN_NAME = '[^']+';/,`const DEFAULT_BIN_NAME = ${JSON.stringify(F)};`).replace(/const DEFAULT_BOOTSTRAP_URL =\s*'[^']+';/,`const DEFAULT_BOOTSTRAP_URL = ${JSON.stringify(I)};`),{mode:493}),ge.log(`Wrote ${t.output} (target=${N}, bin=${F}).`),ge.log(``),ge.log(`Install one-liner for your README:`),ge.log(` curl -fsSL https://github.com/<you>/<repo>/raw/main/${t.output} -o /tmp/i.mjs \\`),ge.log(` && gjs -m /tmp/i.mjs && rm /tmp/i.mjs`)}}}),Qq,$q=__esmMin(()=>{_e(),af(),gz(),Yz(),Az(),Mz(),Qq={command:`prune`,description:`Remove installed packages this host cannot use (foreign os/cpu/libc). Reads each package manifest — a package that declares no platform is never touched.`,builder:t=>t.option(`global`,{description:"Prune the user-global XDG prefix (the `install -g` target) instead of the project.",type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Report what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`List every package rather than the first few.`,type:`boolean`,default:!1}).option(`os`,{description:`Prune AS IF the host were this OS (linux, darwin, win32). Defaults to this host.`,type:`string`}).option(`cpu`,{description:`Prune AS IF the host were this architecture (x64, arm64, …). Defaults to this host.`,type:`string`}).option(`libc`,{description:`Prune AS IF the host used this libc (glibc, musl). Defaults to this host.`,type:`string`}),handler:async t=>{let n=t.global?defaultGlobalLayout():null,S=n?n.prefix:process.cwd();if(!existsSync(`${S}/node_modules`)){ge.log(`gjsify prune: nothing installed at ${S}`);return}let C=resolveHostPlatform({env:{...t.os?{npm_config_os:t.os}:{},...t.cpu?{npm_config_cpu:t.cpu}:{},...t.libc?{npm_config_libc:t.libc}:{}}}),N=await acquireInstallLock(S,{}),F;try{F=executePrune(planPrune({prefix:S,target:C}),{dryRun:t.dryRun})}finally{N.release()}if(ge.log(formatPruneReport(F,{dryRun:t.dryRun,verbose:t.verbose})),F.failed.length>0)return process.exit(1)}}});function isInside(t,n){let S=Bn(t,n);return S===``?!0:S!==`..`&&!S.startsWith(`..${qn}`)&&!Rn(S)}function findBinShimsForPackage(t,n,S){if(!existsSync(t))return[];let C=[],N;try{N=readdirSync(t)}catch{return[]}for(let F of N){let N=zn(t,F);try{if(!statSync(N).isFile())continue;let t=readFileSync(N,`utf-8`);if(!t.startsWith(`#!/bin/sh`))continue;let S=t.split(`
|
|
1886
|
+
`).find(t=>/^exec (?:gjs -m )?'/.test(t));if(!S)continue;let F=S.match(/'([^']+)'/);if(!F)continue;let I=F[1];if(isInside(n,I)){C.push(N);for(let t of[`.cmd`,`.ps1`])existsSync(N+t)&&C.push(N+t)}}catch(t){S&&ge.warn(` ? could not inspect ${N}: ${t.message}`)}}return C}var eJ,tJ=__esmMin(()=>{_e(),af(),Xn(),Yz(),eJ={command:`uninstall <packages..>`,description:"Uninstall a previously installed package. Currently only `--global` mode is supported.",builder:t=>t.positional(`packages`,{description:`Package(s) to uninstall (npm names, optionally with version).`,type:`string`,array:!0,demandOption:!0}).option(`global`,{description:`Uninstall from the user-global XDG location (the install -g target).`,type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Show what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Verbose logging.`,type:`boolean`,default:!1}),handler:t=>{if(!t.global)return ge.error("gjsify uninstall currently only supports --global. For project-local removal, edit package.json + re-run `gjsify install`."),process.exit(1);let n=defaultGlobalLayout(),S=t[`dry-run`]??!1,C=t.verbose??!1,N=`gjsify uninstall${S?` (dry-run)`:``} --global`;ge.log(`${N} ← ${n.prefix}`),ge.log(`${` `.repeat(N.length)} bins ← ${n.binDir}`);let F=!1;for(let N of t.packages){let t=specToPackageName(N),I=zn(n.prefix,`node_modules`,t);if(!existsSync(I)){ge.warn(` ✗ ${t} — not installed at ${I}`);continue}let H=findBinShimsForPackage(n.binDir,I,C);if(S){ge.log(` • would remove ${I}`);for(let t of H)ge.log(` • would remove ${t}`)}else{rmSync(I,{recursive:!0,force:!0}),ge.log(` • removed ${I}`);for(let t of H)unlinkSync(t),ge.log(` • removed ${t}`)}F=!0}F||(ge.error(`
|
|
1887
1887
|
No packages removed.`),process.exit(1))}}});function globToRegexSource(t){let n=``,S=0;for(;S<t.length;){let C=t[S];if(C===`*`&&t[S+1]===`*`&&(S===0||t[S-1]===`/`)){if(S+2===t.length){n+=`.*`,S+=2;continue}if(t[S+2]===`/`){n+=`(?:.*/)?`,S+=3;continue}}if(C===`*`)for(n+=`[^/]*`;t[S+1]===`*`;)S++;else if(C===`?`)n+=`[^/]`;else if(C===`[`){let C=findClassEnd(t,S);if(C===-1)n+=`\\[`;else{let N=t.slice(S+1,C),F=!1;(N.startsWith(`!`)||N.startsWith(`^`))&&(F=!0,N=N.slice(1)),N=N.replace(/\]/g,`\\]`),n+=`[${F?`^/`:``}${N}]`,S=C}}else C===`\\`&&S+1<t.length?(S++,n+=escapeRegex(t[S])):n+=escapeRegex(C);S++}return n}function findClassEnd(t,n){let S=n+1;for((t[S]===`!`||t[S]===`^`)&&S++,t[S]===`]`&&S++;S<t.length;S++)if(t[S]===`]`)return S;return-1}function escapeRegex(t){return/[.+^${}()|[\]\\*?]/.test(t)?`\\${t}`:t}function parseLine(t){let n=t.replace(/\r$/,``);if(n=n.replace(/(?<!\\)\s+$/,``),n===``||n.startsWith(`#`))return null;let S=!1;n.startsWith(`!`)?(S=!0,n=n.slice(1)):(n.startsWith(`\\!`)||n.startsWith(`\\#`))&&(n=n.slice(1));let C=!1;if(n.endsWith(`/`)&&!n.endsWith(`\\/`)&&(C=!0,n=n.slice(0,-1)),n===``)return null;let N=n.includes(`/`);n.startsWith(`/`)&&(n=n.slice(1));let F=globToRegexSource(n);return{re:RegExp(`^${N?``:`(?:.*/)?`}${F}$`),negate:S,dirOnly:C}}function compileGitignore(t,n){let S=[];for(let n of t){let t=parseLine(n);t&&S.push(t)}let relOf=t=>{let S=Bn(n,t);return S===``||S===`..`||S.startsWith(`..${qn}`)||Rn(S)?null:qn===`/`?S:S.split(qn).join(`/`)},decide=(t,n)=>{for(let C=S.length-1;C>=0;C--){let N=S[C];if(!(N.dirOnly&&!n)&&N.re.test(t))return N.negate?`whitelist`:`ignore`}return null};return{base:n,matched(t,n){if(S.length===0)return null;let C=relOf(t);return C===null?null:decide(C,n)},matchedPathOrAnyParents(t,n){if(S.length===0)return null;let C=relOf(t);if(C===null)return null;let N=n;for(;;){let t=decide(C,N);if(t!==null)return t;let n=C.lastIndexOf(`/`);if(n===-1)return null;C=C.slice(0,n),N=!0}}}}function readGitignoreFile(t,n=Hn(t)){let S;try{S=readFileSync(t,`utf-8`)}catch{return null}return compileGitignore(S.split(`
|
|
1888
|
-
`),n)}var
|
|
1889
|
-
`,n);return(S===-1?t.length:S)-n}if(t.startsWith(`/*`,n)){let S=t.indexOf(`*/`,n+2);return(S===-1?t.length:S+2)-n}return 0});return JSON.parse(pass(n,(t,n)=>t[n]===`,`&&/^\s*[}\]]/.test(t.slice(n+1))?1:0))}var parsers,
|
|
1890
|
-
`);ge.error(`[gjsify format] ERROR: ${t.skipped.length} file(s) skipped — the native oxfmt (GJS) has no Prettier host for them (Markdown/HTML/Vue/YAML/…):\n${S}\n The format check is INCOMPLETE. Run \`gjsify format --check\` under Node to check these files, or add them to \`ignorePatterns\`.`),setOxcExitCode(1);return}}try{setOxcExitCode(await runOxfmt(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),
|
|
1891
|
-
[gjsify upgrade --align] --dry-run: no files changed.`);else{let t=applyToFiles(N,S);ge.log(`\n✏️ updated ${N.length} dep(s) across ${t} package.json file(s).`)}}if(F.length>0)return reportUnrepairable(F)}async function resolveCandidateGroups(t,n,S,C){let N=[],F=0;async function worker(){for(;;){let I=F++;if(I>=t.length)return;let H=t[I];try{let t=(await fetchPackument(H.name,{npmrc:n}))[`dist-tags`]?.latest;if(!t){S&&ge.warn(` ${H.name}: no dist-tags.latest, skipping`);continue}let F=H.highestVersion;if(!F){S&&ge.warn(` ${H.name}: unable to parse any current range`);continue}let I=classifyDiff(F,t);if(I===`none`||C===`minor`&&I===`major`||C===`patch`&&(I===`major`||I===`minor`))continue;N.push({...H,latestVersion:t,diff:I})}catch(t){S&&ge.warn(` ${H.name}: fetch failed (${t.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),N.sort((t,n)=>t.name.localeCompare(n.name)),N}function classifyDiff(t,n){let S=parse(t),C=parse(n);return!S||!C?`none`:S.major===C.major?S.minor===C.minor?S.patch===C.patch?(S.prerelease??[]).join(`.`)===(C.prerelease??[]).join(`.`)?`none`:`prerelease`:C.patch>S.patch?`patch`:`none`:C.minor>S.minor?`minor`:`none`:C.major>S.major?`major`:`none`}function colorForDiff(t){switch(t){case`major`:return
|
|
1892
|
-
Select upgrades: comma- or space-separated indices, `+
|
|
1888
|
+
`),n)}var nJ=__esmMin(()=>{af(),Xn()});function externalParserFor(t,n=!1){if(aJ.has(t))return null;let S=Wn(t).slice(1),C=iJ[t]??(S?rJ[S]:void 0)??null;return C===`svelte`&&!n?null:C}function scanForNativeSkips(t,n=process.cwd(),S={}){let C=[],N=0,F=t.filter(t=>t.startsWith(`!`)).map(t=>t.slice(1)),I=[],H=readGitignoreFile(zn(n,`.prettierignore`));H&&I.push(H),F.length&&I.push(compileGitignore(F,n));let globallyIgnored=(t,n,S)=>I.some(C=>(S?C.matchedPathOrAnyParents(t,n):C.matched(t,n))===`ignore`),W=S.configPath?In(n,S.configPath):null,q=loadScope(W??discoverConfig(n)),Y=W===null,scopeFor=t=>Y?nearestScope(t,q):q,expandBraces=t=>{let n=/\{([^{}]*)\}/.exec(t);return n?n[1].split(`,`).flatMap(S=>expandBraces(t.slice(0,n.index)+S+t.slice(n.index+n[0].length))):[t]},X=[],Z=new Set;for(let S of t){if(S.startsWith(`!`))continue;let t=In(n,S);if(/[*?[{]/.test(S)&&!existsSync(t))for(let t of expandBraces(S))X.push(RegExp(`^${globToRegexSource(t.includes(`/`)?t:`**/${t}`)}$`));else Z.add(t)}(X.length||Z.size===0)&&Z.add(In(n));let record=(t,n)=>{n?.ignore?.matchedPathOrAnyParents(t,!1)!==`ignore`&&(N++,externalParserFor(Un(t),n?.svelte)&&C.push(t))},te=[];for(let t of Z){let n;try{n=statSync(t)}catch{continue}globallyIgnored(t,n.isDirectory(),!0)||(n.isDirectory()?te.push(t):n.isFile()&&record(t,scopeFor(Hn(t))))}let matchesGlob=t=>{if(!X.length||Z.has(t))return!0;let S=Bn(n,t).split(qn).join(`/`);return X.some(t=>t.test(S))},ne=new Set,walk=(t,n,S)=>{if(ne.has(t))return;ne.add(t);let C=readGitignoreFile(zn(t,`.gitignore`)),N=C?[C,...n]:n;Y&&t!==S?.dir&&(S=scopeAt(t)??S);let F;try{F=readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of F){let C=zn(t,n.name),F=n.isDirectory();!F&&!n.isFile()||F&&(oJ.has(n.name)||n.name===`node_modules`)||globallyIgnored(C,F,!1)||gitIgnored(N,C,F)||(F?walk(C,N,S):matchesGlob(C)&&record(C,S))}},re=te.every(t=>repoRootOf(t)!==null);for(let t of te)walk(t,parentGitignores(t,re?repoRootOf(t):null,re),scopeFor(t));return{skipped:C,total:N}}function gitIgnored(t,n,S){for(let C of t){let t=C.matched(n,S);if(t!==null)return t===`ignore`}return!1}function parentGitignores(t,n,S){if(S&&n===null)return[];let C=[];for(let S=t;S!==n;){let t=Hn(S);if(t===S)break;S=t;let n=readGitignoreFile(zn(S,`.gitignore`));n&&C.push(n)}let N=n?readGitignoreFile(zn(n,`.git`,`info`,`exclude`),n):null;return N&&C.push(N),C}function repoRootOf(t){for(let n=t;;n=Hn(n)){if(existsSync(zn(n,`.git`))||existsSync(zn(n,`.jj`)))return n;if(Hn(n)===n)return null}}function configIn(t){for(let n of sJ){let S=zn(t,n);if(existsSync(S))return S}return null}function discoverConfig(t){for(let n=In(t);;n=Hn(n)){let t=configIn(n);if(t)return t;if(Hn(n)===n)return null}}function scopeAt(t){let n=configIn(t);return n?loadScope(n):null}function nearestScope(t,n){for(;;t=Hn(t)){if(n&&t===n.dir)return n;let S=scopeAt(t);if(S)return S;if(Hn(t)===t)return n}}function loadScope(t){if(!t)return null;let n=Hn(t),S={};try{S=parseJsonc(readFileSync(t,`utf-8`))}catch{S={}}let C=Array.isArray(S.ignorePatterns)?S.ignorePatterns.filter(t=>typeof t==`string`):[];return{dir:n,ignore:C.length?compileGitignore(C,n):null,svelte:S.svelte!==void 0&&S.svelte!==null&&S.svelte!==!1}}function parseJsonc(t){let pass=(t,n)=>{let S=``;for(let C=0;C<t.length;){if(t[C]===`"`){let n=C+1;for(;n<t.length&&t[n]!==`"`;)n+=t[n]===`\\`?2:1;S+=t.slice(C,n+1),C=n+1;continue}let N=n(t,C);N>0?C+=N:S+=t[C++]}return S},n=pass(t,(t,n)=>{if(t.startsWith(`//`,n)){let S=t.indexOf(`
|
|
1889
|
+
`,n);return(S===-1?t.length:S)-n}if(t.startsWith(`/*`,n)){let S=t.indexOf(`*/`,n+2);return(S===-1?t.length:S+2)-n}return 0});return JSON.parse(pass(n,(t,n)=>t[n]===`,`&&/^\s*[}\]]/.test(t.slice(n+1))?1:0))}var parsers,rJ,iJ,aJ,oJ,sJ,cJ=__esmMin(()=>{af(),Xn(),nJ(),parsers=(t,n)=>Object.fromEntries(n.map(n=>[n,t])),rJ={...parsers(`yaml`,[`yml`,`mir`,`reek`,`rviz`,`sublime-syntax`,`syntax`,`yaml`,`yaml-tmlanguage`]),...parsers(`markdown`,[`md`,`livemd`,`markdown`,`mdown`,`mdwn`,`mkd`,`mkdn`,`mkdown`,`ronn`,`scd`,`workbook`]),...parsers(`html`,[`html`,`hta`,`htm`,`inc`,`xht`,`xhtml`]),...parsers(`glimmer`,[`handlebars`,`hbs`]),mdx:`mdx`,vue:`vue`,svelte:`svelte`,mjml:`mjml`},iJ={...parsers(`yaml`,[`.clang-format`,`.clang-tidy`,`.clangd`,`.gemrc`,`CITATION.cff`,`glide.lock`]),...parsers(`yaml`,[`pixi.lock`,`.prettierrc`,`.stylelintrc`,`.lintstagedrc`]),...parsers(`markdown`,[`contents.lr`,`README`])},aJ=new Set([`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`MODULE.bazel.lock`,`bun.lock`,`deno.lock`,`composer.lock`,`Package.resolved`,`Pipfile.lock`,`flake.lock`,`mcmod.info`,`Cargo.lock`,`Gopkg.lock`,`pdm.lock`,`poetry.lock`,`uv.lock`]),oJ=new Set([`.git`,`.jj`,`.sl`,`.svn`,`.hg`]),sJ=[`.oxfmtrc.json`,`.oxfmtrc.jsonc`]});function handleInit({cwd:t,force:n}){let writeOne=(S,C)=>{let N=In(t,S);if(existsSync(N)&&!n){ge.log(`[gjsify format] ${S} exists at ${N} — pass --force to overwrite.`);return}writeFileSync(N,C,`utf-8`),ge.log(`[gjsify format] wrote ${N}`)};writeOne(`.oxlintrc.json`,loadOxlintTemplate()),writeOne(`.oxfmtrc.json`,loadOxfmtTemplate()),ge.log("[gjsify format] Run `gjsify format` to apply the formatter to the project.")}var lJ,uJ=__esmMin(()=>{_e(),af(),Xn(),xV(),cJ(),lJ={command:`format [paths..]`,description:`Format source files via oxfmt (Markdown/YAML/HTML/Vue need the napi build).`,builder:t=>t.positional(`paths`,{description:"Files or directories to format. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Modify files in place (default: true). Pass --no-write to report drift instead.`,type:`boolean`,default:!0}).option(`check`,{description:`Report formatting drift without modifying files; exit non-zero if any file is unformatted. Useful for CI.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxfmtrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`init`,{description:`Write recommended .oxlintrc.json + .oxfmtrc.json into cwd (skips existing files unless --force).`,type:`boolean`,default:!1}).option(`force`,{description:`Overwrite existing .oxlintrc.json / .oxfmtrc.json with --init.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo the resolved oxfmt launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd();if(t.init){handleInit({cwd:n,force:t.force??!1});return}let S=t.paths?.length?t.paths:[`.`],C=[];t.check?C.push(`--check`):t.write===!1?C.push(`--list-different`):C.push(`--write`);let N=t.configPath??findOxfmtConfig(n)??void 0;if(N&&C.push(`--config`,In(N)),C.push(...S),t.check&&await shouldUseNativeOxfmt()){let t=scanForNativeSkips(S,n,{configPath:N});if(t.skipped.length>0){let S=t.skipped.map(t=>` ${Bn(n,t)||t}`).join(`
|
|
1890
|
+
`);ge.error(`[gjsify format] ERROR: ${t.skipped.length} file(s) skipped — the native oxfmt (GJS) has no Prettier host for them (Markdown/HTML/Vue/YAML/…):\n${S}\n The format check is INCOMPLETE. Run \`gjsify format --check\` under Node to check these files, or add them to \`ignorePatterns\`.`),setOxcExitCode(1);return}}try{setOxcExitCode(await runOxfmt(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),dJ,fJ=__esmMin(()=>{Xn(),xV(),dJ={command:`lint [paths..]`,description:`Run oxlint diagnostics (spawned via its Node launcher to support JS plugins).`,builder:t=>t.positional(`paths`,{description:"Files or directories to lint. Default: `.`",type:`string`,array:!0}).option(`fix`,{description:`Apply safe lint fixes in place.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxlint launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=[];t.fix&&C.push(`--fix`);let N=t.configPath??findOxlintConfig(n)??void 0;N&&C.push(`--config`,In(N)),C.push(...S);try{setOxcExitCode(await runOxlint(C,{cwd:n,verbose:t.verbose}))}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}}),pJ,mJ=__esmMin(()=>{Xn(),xV(),pJ={command:`fix [paths..]`,description:`Run oxfmt --write then oxlint --fix — format + safe lint fixes in one pass.`,builder:t=>t.positional(`paths`,{description:"Files or directories to fix. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Apply fixes in place (default: true). Pass --no-write to report only.`,type:`boolean`,default:!0}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxc launchers + args before spawning.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=t.paths?.length?t.paths:[`.`],C=t.verbose??!1,N=t.write!==!1;try{let F=[N?`--write`:`--list-different`],I=t.configPath??findOxfmtConfig(n)??void 0;I&&F.push(`--config`,In(I)),F.push(...S);let H=await runOxfmt(F,{cwd:n,verbose:C}),W=[];N&&W.push(`--fix`);let q=t.configPath??findOxlintConfig(n)??void 0;q&&W.push(`--config`,In(q)),W.push(...S);let Y=await runOxlint(W,{cwd:n,verbose:C});setOxcExitCode(H||Y)}catch(t){if(t instanceof OxcNotFoundError){printOxcNotFound(t),setOxcExitCode(1);return}throw t}}}});function createInterface(t,n){return typeof t==`object`&&t&&!(`read`in t&&typeof t.read==`function`)?new Interface(t):new Interface({input:t,output:n})}var Interface,hJ=__esmMin(()=>{Xd(),Interface=class extends Interface$1{question(t,n){return new Promise(n=>{super.question(t,n)})}}});function semverGt(t,n){try{return compare(t,n)===1}catch{return!1}}function groupByDependency(t){let n=new Map;for(let S of t){let t=n.get(S.name);t||(t={name:S.name,occurrences:[],declaredRanges:new Set,dominantRange:S.currentRange,highestVersion:S.currentVersion},n.set(S.name,t)),t.occurrences.push(S),t.declaredRanges.add(S.currentRange),S.currentVersion&&(!t.highestVersion||semverGt(S.currentVersion,t.highestVersion))&&(t.highestVersion=S.currentVersion)}for(let t of n.values()){let n=new Map;for(let S of t.occurrences)n.set(S.currentRange,(n.get(S.currentRange)??0)+1);let S=t.occurrences[0].currentRange,C=-1,N=null;for(let[t,F]of n.entries()){let n=parse(t.replace(/^[\^~>=<]+/,``))?.version??null;(F>C||F===C&&n&&N&&semverGt(n,N)||F===C&&t<S)&&(S=t,C=F,N=n)}t.dominantRange=S}return[...n.values()].sort((t,n)=>t.name.localeCompare(n.name))}function isInconsistent(t){return t.declaredRanges.size>1}function findInconsistencies(t){return t.filter(isInconsistent)}var gJ=__esmMin(()=>{HI()});function discoverContext(t){let n=findWorkspaceRoot(t);if(n)return{root:n,workspaces:discoverWorkspaces(n,{includeRoot:!0}),isMonorepo:!0};let S=zn(t,`package.json`);if(!existsSync(S))throw Error(`[gjsify upgrade] no package.json at ${S}`);let C=JSON.parse(readFileSync(S,`utf-8`));return{root:t,workspaces:[{name:C.name??`<root>`,location:t,relativeLocation:`.`,version:C.version??`0.0.0`,manifest:C,private:C.private===!0}],isMonorepo:!1}}function applyWorkspaceFilter(t,n,S){let C=n?.split(`,`).map(t=>t.trim()).filter(Boolean),N=S?.split(`,`).map(t=>t.trim()).filter(Boolean);return(!C||C.length===0)&&(!N||N.length===0)?t:filterWorkspaces(t,{include:C,exclude:N})}function parseFilterList(t){return t?t.split(`,`).map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function collectAllDeclarations(t,n){let S=[];for(let C of t)for(let t of collectFromWorkspace(C,n))S.push(t);return S}function collectFromWorkspace(t,n){let S=[],C=t.manifest;for(let N of vJ){let F=C[N];if(!(!F||typeof F!=`object`))for(let[C,I]of Object.entries(F)){if(typeof I!=`string`||n.length&&!n.some(t=>C.toLowerCase().includes(t))||isDistTagSpec(I)||I.startsWith(`workspace:`)||I.startsWith(`file:`)||I.startsWith(`link:`)||I.startsWith(`git+`)||I.startsWith(`git:`)||I.startsWith(`http:`)||I.startsWith(`https:`)||I.startsWith(`npm:`)||I.startsWith(`portal:`))continue;let{prefix:F,version:H}=splitRange(I);S.push({workspace:t.name,workspaceLocation:t.location,name:C,field:N,currentRange:I,currentVersion:H,prefix:F})}}return S}function isDistTagSpec(t){let n=t.trim();return yJ.has(n)||!/^[A-Za-z]/.test(n)||/^v\d/.test(n)||/^v[xX*]/.test(n)?!1:/^[A-Za-z][\w.-]*$/.test(n)}function splitRange(t){let n=t.match(/^(\^|~|>=|<=|>|<|=)?\s*([0-9].*)$/);if(!n)return{prefix:``,version:null};let S=n[1]??``,C=n[2]?.split(/\s|[|&,]/)[0]??null;return{prefix:S,version:(C?parse(C):null)?.version??null}}function reportInexactRanges(t){let n=t.map(t=>({name:t.name,loose:t.occurrences.filter(t=>t.prefix!==``)})).filter(t=>t.loose.length>0);if(n.length===0)return 0;let S=n.reduce((t,n)=>t+n.loose.length,0);ge.error(`gjsify upgrade --check --exact: FAIL. ${S} declaration(s) across ${n.length} dep(s) carry a range operator:\n`);for(let t of n){let n=new Map;for(let S of t.loose){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${bJ.bold}${t.name}${bJ.reset}`);for(let[t,S]of n.entries()){let n=S.length>6?`${S.slice(0,6).join(`, `)} … +${S.length-6}`:S.join(`, `);ge.error(` ${t.padEnd(16)} — ${n}`)}}return S}function checkLockfileRangeViolations(t,n){let S=zn(n,`gjsify-lock.json`);if(!existsSync(S))return 0;let C;try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{return 0}if(!C.packages)return 0;let N=new Map;for(let n of t){let t=N.get(n.name)??new Set;for(let S of n.occurrences)t.add(S.currentRange);N.set(n.name,t)}let F=0;for(let[t,n]of Object.entries(C.packages)){if(!n.version)continue;let S=t.split(`node_modules/`);if(S.length!==2)continue;let C=S[1],I=N.get(C);if(!I||I.size===0)continue;let H=!1;for(let t of I)try{if(n.version&&satisfies(n.version,t)){H=!0;break}}catch{}H||(ge.error(` ${C}: lockfile has ${n.version}, but declared ranges are ${[...I].join(`, `)}`),F++)}return F>0&&ge.error(`gjsify upgrade --check: FAIL. ${F} lockfile entr${F===1?`y`:`ies`} violate declared ranges:\n`),F}function runCheckMode(t,n=!1,S=process.cwd()){checkLockfileRangeViolations(t,S);let C=n?reportInexactRanges(t):0,N=findInconsistencies(t);if(N.length===0&&C>0)return ge.error("\nFix: run `gjsify upgrade --align --exact` (offline; drops the operator and keeps the version)."),process.exit(1);if(N.length===0){ge.log(`gjsify upgrade --check: OK. ${t.length} dep(s) consistently declared across workspaces`+(n?`, every declaration pinned exactly.`:`.`));return}ge.error(`gjsify upgrade --check: FAIL. ${N.length} dep(s) declared at inconsistent ranges:\n`);for(let t of N){let n=new Map;for(let S of t.occurrences){let t=n.get(S.currentRange)??[];t.push(S.workspace),n.set(S.currentRange,t)}ge.error(` ${bJ.bold}${t.name}${bJ.reset}`);for(let[t,S]of n.entries())ge.error(` ${t.padEnd(16)} — ${S.join(`, `)}`)}ge.error(n?"\nFix: run `gjsify upgrade --align --exact` (offline; aligns each dep to its highest declared version and drops the operator).":"\nFix: run `gjsify upgrade --align` (offline; aligns each dep to its highest declared range)."),process.exit(1)}function alignTargets(t,n){return n?t.filter(t=>isInconsistent(t)||t.occurrences.some(t=>t.prefix!==``)):findInconsistencies(t)}function reportUnrepairable(t){ge.error(`\ngjsify upgrade --align: ${t.length} dep(s) left unrepaired — no version to align on:\n`);for(let n of t)ge.error(` ${bJ.bold}${n.name}${bJ.reset} ${[...n.declaredRanges].join(`, `)}`);return ge.error("\nThose ranges name no single version. Edit them by hand, or resolve one with `--latest`."),process.exit(1)}function runAlignMode(t,n){let S=n.exact??!1,C=alignTargets(t,S);if(C.length===0){ge.log(`gjsify upgrade --align: nothing to do. ${t.length} dep(s) already consistent`+(S?`, every declaration pinned exactly.`:`.`));return}let N=[],F=[];for(let t of C){if(!t.highestVersion){F.push(t);continue}let n=t.occurrences.find(n=>n.currentRange===t.dominantRange)?.prefix||`^`;N.push({...t,latestVersion:t.highestVersion,diff:`none`,occurrences:t.occurrences.map(t=>({...t,prefix:n}))})}if(N.length>0){ge.log(S?`gjsify upgrade --align --exact: pinning ${N.length} dep(s) to their highest declared version, without a range operator:\n`:`gjsify upgrade --align: aligning ${N.length} inconsistent dep(s) to their highest declared version:\n`);for(let t of N){let n=t.occurrences[0]?.prefix??`^`;ge.log(` ${t.name.padEnd(28)} ranges: ${[...t.declaredRanges].join(`, `)} → ${targetRange(n,t.latestVersion,S)}`)}if(n.dryRun)ge.log(`
|
|
1891
|
+
[gjsify upgrade --align] --dry-run: no files changed.`);else{let t=applyToFiles(N,S);ge.log(`\n✏️ updated ${N.length} dep(s) across ${t} package.json file(s).`)}}if(F.length>0)return reportUnrepairable(F)}async function resolveCandidateGroups(t,n,S,C){let N=[],F=0;async function worker(){for(;;){let I=F++;if(I>=t.length)return;let H=t[I];try{let t=(await fetchPackument(H.name,{npmrc:n}))[`dist-tags`]?.latest;if(!t){S&&ge.warn(` ${H.name}: no dist-tags.latest, skipping`);continue}let F=H.highestVersion;if(!F){S&&ge.warn(` ${H.name}: unable to parse any current range`);continue}let I=classifyDiff(F,t);if(I===`none`||C===`minor`&&I===`major`||C===`patch`&&(I===`major`||I===`minor`))continue;N.push({...H,latestVersion:t,diff:I})}catch(t){S&&ge.warn(` ${H.name}: fetch failed (${t.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),N.sort((t,n)=>t.name.localeCompare(n.name)),N}function classifyDiff(t,n){let S=parse(t),C=parse(n);return!S||!C?`none`:S.major===C.major?S.minor===C.minor?S.patch===C.patch?(S.prerelease??[]).join(`.`)===(C.prerelease??[]).join(`.`)?`none`:`prerelease`:C.patch>S.patch?`patch`:`none`:C.minor>S.minor?`minor`:`none`:C.major>S.major?`major`:`none`}function colorForDiff(t){switch(t){case`major`:return bJ.red;case`minor`:return bJ.yellow;case`patch`:return bJ.green;case`prerelease`:return bJ.cyan;default:return``}}function printTable(t){let n=Math.max(...t.map(t=>t.name.length),4),S=Math.max(...t.map(t=>`${t.occurrences.length}`.length+2),3),C=Math.max(...t.map(t=>declaredCellWidth(t)),7),N=Math.max(...t.map(t=>t.latestVersion.length),6),F=String(t.length).length+2,I=` `.repeat(F+2)+bJ.bold+`name`.padEnd(n)+` `+`fan`.padEnd(S)+` `+`declared`.padEnd(C)+` `+`latest`.padEnd(N)+` kind`+bJ.reset;ge.log(I),ge.log(` `.repeat(F+2)+bJ.dim+`─`.repeat(n+S+C+N+16)+bJ.reset);for(let I=0;I<t.length;I++){let H=t[I],W=`${I+1}.`.padEnd(F),q=H.declaredRanges.size>1?`${bJ.magenta}⚠ ${bJ.reset}`:` `,Y=colorForDiff(H.diff);ge.log(W+q+H.name.padEnd(n)+` `+bJ.dim+`${H.occurrences.length}`.padEnd(S)+bJ.reset+` `+bJ.dim+renderDeclaredCell(H).padEnd(C)+bJ.reset+` `+Y+H.latestVersion.padEnd(N)+bJ.reset+` `+Y+H.diff+bJ.reset)}let H=t.filter(t=>t.declaredRanges.size>1).length;H>0&&ge.log(`\n${bJ.magenta}⚠${bJ.reset} ${H} dep(s) declared at inconsistent ranges across workspaces.`)}function declaredCellWidth(t){return renderDeclaredCell(t).length}function renderDeclaredCell(t){if(t.declaredRanges.size===1)return[...t.declaredRanges][0];let n=[...t.declaredRanges].sort().join(`, `);return n.length<=32?n:n.slice(0,29)+`…`}function printChangePlan(t,n=!1){for(let S of t)for(let t of S.occurrences)ge.log(` ${t.workspace.padEnd(38)} ${S.name.padEnd(28)} ${t.currentRange.padEnd(12)} → ${targetRange(t.prefix,S.latestVersion,n)}`)}async function promptSelection(t){if(!process.stdin.isTTY)return ge.log(`[gjsify upgrade] non-TTY stdin: pass --latest / --minor / --patch (or --yes for interactive-all) to upgrade non-interactively.`),[];let n=createInterface({input:process.stdin,output:process.stdout});try{ge.log(`
|
|
1892
|
+
Select upgrades: comma- or space-separated indices, `+bJ.bold+`a`+bJ.reset+` for all, ranges like `+bJ.bold+`1-3`+bJ.reset+`, or `+bJ.bold+`ENTER`+bJ.reset+` to skip:`);let S=(await n.question(`> `)).trim();if(!S)return[];if(S.toLowerCase()===`a`||S.toLowerCase()===`all`)return[...t];let C=new Set;for(let t of S.split(/[\s,]+/).filter(Boolean)){let n=t.match(/^(\d+)-(\d+)$/);if(n){let t=Number(n[1]),S=Number(n[2]);for(let n=Math.min(t,S);n<=Math.max(t,S);n++)C.add(n-1)}else/^\d+$/.test(t)&&C.add(Number(t)-1)}return[...C].filter(n=>n>=0&&n<t.length).map(n=>t[n])}finally{n.close()}}function targetRange(t,n,S){return S?n:`${t}${n}`}function applyToFiles(t,n=!1){let S=new Map;for(let n of t)for(let t of n.occurrences){let C=S.get(t.workspaceLocation)??[];C.push({...n,occurrences:[t]}),S.set(t.workspaceLocation,C)}let C=0;for(let[t,N]of S.entries()){let S=zn(t,`package.json`),F=readFileSync(S,`utf-8`),I=JSON.parse(F),H=!1,W=[];for(let t of N){let S=t.occurrences[0],C=I[S.field];if(!C)continue;let N=targetRange(S.prefix,t.latestVersion,n);C[t.name]!==N&&(C[t.name]=N,H=!0,W.push(t.name))}if(H){let t=detectIndent(F);writeFileSync(S,keepUntouchedLines(F,JSON.stringify(I,null,t)+(F.endsWith(`
|
|
1893
1893
|
`)?`
|
|
1894
1894
|
`:``),W),`utf-8`),C++}}return C}function keepUntouchedLines(t,n,S){let C=t.split(`
|
|
1895
1895
|
`),N=n.split(`
|
|
1896
1896
|
`);return C.length===N.length?N.map((t,n)=>S.some(n=>t.includes(`"${n}"`))?t:C[n]).join(`
|
|
1897
|
-
`):n}function uniqueLocations(t){let n=new Set;for(let S of t)for(let t of S.occurrences)n.add(t.workspaceLocation);return[...n]}function detectIndent(t){let n=t.match(/^\{\n( +)/);return n?n[1].length:2}async function loadNpmrcLight(t){let n={registry:ph,scopes:{},authTokens:{},basicAuth:{}};for(let S of[zn(homedir(),`.npmrc`),zn(t,`.npmrc`)])if(existsSync(S))try{let t=parseNpmrc(readFileSync(S,`utf-8`));n={...n,...t,scopes:{...n.scopes,...t.scopes}}}catch{}return process.env.npm_config_registry&&(n.registry=process.env.npm_config_registry),n}var
|
|
1897
|
+
`):n}function uniqueLocations(t){let n=new Set;for(let S of t)for(let t of S.occurrences)n.add(t.workspaceLocation);return[...n]}function detectIndent(t){let n=t.match(/^\{\n( +)/);return n?n[1].length:2}async function loadNpmrcLight(t){let n={registry:ph,scopes:{},authTokens:{},basicAuth:{}};for(let S of[zn(homedir(),`.npmrc`),zn(t,`.npmrc`)])if(existsSync(S))try{let t=parseNpmrc(readFileSync(S,`utf-8`));n={...n,...t,scopes:{...n.scopes,...t.scopes}}}catch{}return process.env.npm_config_registry&&(n.registry=process.env.npm_config_registry),n}var _J,vJ,yJ,bJ,xJ=__esmMin(()=>{_e(),af(),Xn(),o_(),hJ(),HI(),xh(),GI(),qI(),gJ(),_J={command:`upgrade`,description:"Workspace-aware dependency upgrades. Walks every package.json in the monorepo, groups by dep, flags inconsistencies. `--latest` / `--minor` / `--patch` for bulk-mode, `--align` for offline consistency-only mode, `--check` for CI drift detection.",builder:t=>t.option(`latest`,{description:`Non-interactive: bump every dependency to its latest version (allows major).`,type:`boolean`,default:!1}).option(`minor`,{description:`Non-interactive: bump every dependency to the latest within the same major (semver-minor + semver-patch).`,type:`boolean`,default:!1}).option(`patch`,{description:`Non-interactive: bump every dependency to the latest within the same minor (semver-patch only).`,type:`boolean`,default:!1}).option(`filter`,{description:`Only consider deps whose name matches this substring (case-insensitive). Repeatable; comma-separated values are split.`,type:`string`}).option(`workspace`,{alias:`p`,description:`Restrict to a subset of workspaces. Patterns are matched against the workspace package name AND its directory path (substring + glob). Repeatable; comma-separated values are split.`,type:`string`}).option(`exclude-workspace`,{description:`Skip workspaces matching this pattern (glob-shaped; matched against workspace package name AND directory path). Repeatable; comma-separated values are split. Use for workspaces with intentional dependency drift — e.g. integration tests pinned to specific upstream versions.`,type:`string`}).option(`align`,{description:"Offline repair mode: find deps declared at multiple ranges across the workspace and align them to the highest. With `--exact`, also drop the range operator from declarations that already agree. No registry calls.",type:`boolean`,default:!1}).option(`check`,{description:"CI gate: exit non-zero when any dep is declared inconsistently across workspaces. Implies offline (no registry calls). Pairs with `--align` as the fix.",type:`boolean`,default:!1}).option(`exact`,{description:"Pin without a range operator. When writing, emits `1.2.3` instead of `^1.2.3`; with `--check`, fails on any matched dep that carries one; with `--align`, repairs exactly that. Pair with `--filter` — a repository-wide exactness run touches every ordinary caret dep by design.",type:`boolean`,default:!1}).option(`dry-run`,{description:`Print the upgrade plan without writing package.json files.`,type:`boolean`,default:!1}).option(`cwd`,{description:`Project directory. Default: process.cwd(). When inside a workspace, walks up to the monorepo root.`,type:`string`}).option(`yes`,{alias:`y`,description:`Interactive mode: select all without prompting.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print extra resolution details.`,type:`boolean`,default:!1}),handler:async t=>{let n=discoverContext(In(t.cwd??process.cwd())),S=applyWorkspaceFilter(n.workspaces,t.workspace,t.excludeWorkspace);if(S.length===0){ge.log(`[gjsify upgrade] no matching workspaces.`);return}let C=collectAllDeclarations(S,parseFilterList(t.filter));if(C.length===0){ge.log(`[gjsify upgrade] no external npm dependencies to check.`);return}let N=groupByDependency(C);if(t.check)return runCheckMode(N,t.exact);if(t.align)return runAlignMode(N,t);let F=await loadNpmrcLight(n.root),I=t.latest?`latest`:t.minor?`minor`:t.patch?`patch`:`interactive`;ge.log(`[gjsify upgrade] checking ${N.length} unique deps across ${S.length} workspace(s) against ${F.registry}…`);let H=await resolveCandidateGroups(N,F,t.verbose??!1,I);if(H.length===0){ge.log(`✅ all dependencies are up to date`);let t=findInconsistencies(N);t.length>0&&ge.log(`\n⚠ ${t.length} dep(s) declared at inconsistent ranges across workspaces. Run \`gjsify upgrade --align\` to fix.`);return}printTable(H);let W;if(I===`interactive`&&!t.yes?W=await promptSelection(H):(t.yes&&I===`interactive`&&ge.log(`[gjsify upgrade] -y / --yes: selecting all`),W=H),W.length===0){ge.log(`[gjsify upgrade] nothing selected; no files changed.`);return}if(t.dryRun){let n=uniqueLocations(W).length;ge.log(`[gjsify upgrade] --dry-run: would update ${W.length} deps across ${n} package.json file(s).`),printChangePlan(W,t.exact);return}let q=applyToFiles(W,t.exact);ge.log(`✏️ updated ${W.length} dep(s) across ${q} package.json file(s). Run \`gjsify install\` to apply.`)}},vJ=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`],yJ=new Set([`x`,`X`,`*`,``]),bJ={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,green:`\x1B[32m`,cyan:`\x1B[36m`,magenta:`\x1B[35m`}});async function unscannableBarrelPaths(t,n){let S=[];for(let C of n){let n=In(t,C);try{(await stat$1(n)).isDirectory()||S.push(`${n} is not a directory`)}catch(t){S.push(`${n}: ${t.message}`)}}return S}async function generateBarrels(t){let n=t.singleQuotes?`'`:`"`,S=t.noSemicolon?``:`;`,C=t.extension===`none`?``:`.${t.extension}`,N=0;for(let F of t.paths){let I=In(t.baseDir,F),H=Un(I)===`types`,W;try{W=(await readdir$1(I,{withFileTypes:!0})).filter(t=>t.isFile()).filter(t=>CJ.test(t.name)).filter(t=>t.name!==`index.ts`).filter(n=>!t.exclude.some(t=>t.test(n.name))).sort((t,n)=>t.name.localeCompare(n.name))}catch(n){t.verbose&&ge.error(`[gjsify barrels] skip ${I}: ${n.message}`);continue}let q=W.map(t=>{let N=Un(t.name,Wn(t.name));return`${H?`export type *`:`export *`} from ${n}./${N}${C}${n}${S}`}),Y=q.length?`${q.join(`
|
|
1898
1898
|
`)}\n`:`export {};
|
|
1899
|
-
`,X=`${t.header}\n\n${Y}`,Z=zn(I,`index.ts`);if(await readFile$1(Z,`utf-8`).catch(()=>``)===X){t.verbose&&ge.log(`[gjsify barrels] up-to-date: ${Z}`);continue}t.check?(ge.error(`[gjsify barrels] drift: ${Z}`),N++):(await writeFile$1(Z,X,`utf-8`),t.verbose&&ge.log(`[gjsify barrels] wrote: ${Z}`))}return N}var
|
|
1900
|
-
`).map(t=>t.trim()).filter(Boolean)}var
|
|
1899
|
+
`,X=`${t.header}\n\n${Y}`,Z=zn(I,`index.ts`);if(await readFile$1(Z,`utf-8`).catch(()=>``)===X){t.verbose&&ge.log(`[gjsify barrels] up-to-date: ${Z}`);continue}t.check?(ge.error(`[gjsify barrels] drift: ${Z}`),N++):(await writeFile$1(Z,X,`utf-8`),t.verbose&&ge.log(`[gjsify barrels] wrote: ${Z}`))}return N}var SJ,CJ,wJ=__esmMin(()=>{_e(),Vd(),Xn(),SJ=[`\\.test\\.`,`\\.spec\\.`,`\\.test-data\\.`],CJ=/\.(ts|tsx|mts|cts)$/}),TJ,EJ=__esmMin(()=>{_e(),wJ(),TJ={command:`barrels [paths..]`,description:"Regenerate `index.ts` barrel files for the given directories. Drop-in replacement for `barrelsby`.",builder:t=>t.positional(`paths`,{description:"Directories whose `index.ts` to (re)generate. May also be passed via `--paths`.",type:`string`,array:!0}).option(`paths`,{alias:`p`,description:`Alternative to positional — repeatable list of directories.`,type:`string`,array:!0}).option(`ext`,{description:"Import-specifier extension. Default: `none` (bundler-mode resolution).",type:`string`,choices:[`js`,`ts`,`none`],default:`none`}).option(`base-dir`,{alias:`b`,description:"Resolve `paths` against this directory. Default: cwd.",type:`string`}).option(`exclude`,{description:"Regex(es) of file names to skip. Repeatable. Defaults: `\\.test\\.`, `\\.spec\\.`, `\\.test-data\\.`.",type:`string`,array:!0}).option(`header`,{description:`Header comment prepended to every generated file.`,type:`string`}).option(`semicolon`,{description:"Emit trailing `;` on each export line. Negate with `--no-semicolon`. Default: omitted.",type:`boolean`,default:!1}).option(`single-quotes`,{description:"Use `'` for import specifiers. Default: true. Pass `--no-single-quotes` for `\"`.",type:`boolean`,default:!0}).option(`check`,{description:`Report drift without modifying files; exit non-zero if any barrel is stale.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Log each file scanned + written.`,type:`boolean`,default:!1}),handler:async t=>{let n=Array.from(new Set((t.paths??[]).filter(Boolean)));if(n.length===0){ge.error(`[gjsify barrels] no paths provided. Pass directories as positional arguments or via --paths.`),process.exitCode=1;return}let S=t.baseDir??process.cwd(),C=await unscannableBarrelPaths(S,n);if(C.length>0){for(let t of C)ge.error(`[gjsify barrels] cannot scan ${t}`);ge.error(`[gjsify barrels] ${C.length} of ${n.length} path(s) could not be scanned — refusing to report on the rest as if that were the whole set.`),process.exitCode=1;return}let N=t.exclude?.length?t.exclude:[...SJ],F=await generateBarrels({paths:n,extension:t.ext??`none`,baseDir:S,exclude:N.map(t=>new RegExp(t)),header:t.header??"// Auto-generated by `gjsify barrels` — do not edit by hand.",noSemicolon:t.semicolon===!1||t.semicolon===void 0,singleQuotes:t.singleQuotes!==!1,check:t.check??!1,verbose:t.verbose??!1});t.check&&F>0&&(ge.error(`[gjsify barrels] ${F} barrel file(s) drifted. Run without --check to fix.`),process.exitCode=1)}}}),DJ,OJ=__esmMin(()=>{_e(),eu(),Xn(),cr(),gL(),dL(),af(),YG(),UR(),qI(),hv(),Fz(),DJ={command:`tsc [tscArgs..]`,description:"Run TypeScript compiler (tsc) under GJS via the @gjsify/tsc bundle. All arguments are passed through to tsc. Equivalent to `gjsify-tsc <args>` from the @gjsify/tsc bin.",builder:t=>t.parserConfiguration({"unknown-options-as-args":!0}).version(!1).help(!1).positional(`tscArgs`,{description:"Arguments forwarded verbatim to tsc (e.g. `--version`, `-p tsconfig.json`).",type:`string`,array:!0,default:[]}),handler:async t=>{let n=(t._??[]).slice(1).map(String),S=t.tscArgs??[],C=process.cwd(),N=tscArgsUnderLink(n.length>0?n:S,existsSync(devLinkPath(devLinkRoot(C)))),F=[pathToFileURL(`${findWorkspaceRoot(C)??C}/__gjsify_tsc__.js`).href,import.meta.url],I;for(let t of F)try{I=createRequire(t).resolve(`@gjsify/tsc/bundle`);break}catch{}let H;for(let t of F)try{H=zn(Hn(createRequire(t).resolve(`typescript/package.json`)),`lib`,`tsc.js`);break}catch{}if(!I&&!H)return ge.error("gjsify tsc: neither @gjsify/tsc (GJS bundle) nor npm `typescript` (Node) is installed."),ge.error(" Install with: gjsify install --save-dev @gjsify/tsc (or add `typescript`)."),forceExit(1);let W=buildNativeEnv(detectNativePackages(C)),q={...process.env,...W},runNodeTsc=async()=>{let t=nodeBinary();if(!(t.includes(`/`)||t.includes(`\\`)?existsSync(t):isOnPath(t)))return ge.error(`gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and \`${t}\` cannot be run, so upstream \`typescript\` cannot run either.`),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`),ge.error(" …or install Node.js so the upstream `typescript` fallback can be spawned."),forceExit(1);try{await new Promise((n,S)=>{spawnToCompletion(t,[H,...N],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(S)})}catch(t){let n=t;return n.code===`ENOENT`?(ge.error("gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and `node` is not on PATH, so upstream `typescript` cannot run either."),ge.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`)):ge.error(`gjsify tsc (node typescript): ${n.message}`),forceExit(1)}};if(I)try{await new Promise((t,n)=>{spawnToCompletion(`gjs`,[`-m`,I,...N],{completion:`exit`,env:q,onSpawn:t=>{let n=!1;t.on(`error`,()=>{n=!0}),t.on(`close`,t=>{n||forceExit(t??1)})}}).catch(n)})}catch(t){let n=t;return n.code===`ENOENT`&&H?await runNodeTsc():(n.code===`ENOENT`?(ge.error("gjsify tsc: `gjs` not found on PATH and no npm `typescript` fallback."),ge.error(" Install GJS (e.g. `dnf install gjs`), or add `typescript` to the project.")):ge.error(`gjsify tsc: ${n.message}`),forceExit(1))}else await runNodeTsc()}}});function readStdinText(){return readFileSync(0,`utf-8`)}function readStdinLines(){return splitStdinLines(readStdinText())}function splitStdinLines(t){return t.split(`
|
|
1900
|
+
`).map(t=>t.trim()).filter(Boolean)}var kJ=__esmMin(()=>{af()});function isResolvableScript(t){return PJ.test(t)&&!AJ.some(n=>n.test(t))&&!NJ.some(n=>n.match.test(t))}function resolveRootScripts(t,n){let S=new Set,C=[];for(let n of t)isResolvableScript(n)?C.push(n):S.add(n);let N=new Set;for(;C.length>0;){let t=C.shift();if(!N.has(t)){N.add(t);for(let N of n(t))jJ.some(t=>t.test(N))||(isResolvableScript(N)?C.push(N):S.add(N))}}return{files:[...S],scripts:N.size}}function classifyAndExpand(t,n,S){let C=n.map(t=>t.replace(/\\/g,`/`)).filter(t=>t.length>0);if(C.length===0)return{global:!1,reason:`empty-diff`,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};let N=[];for(let t of C)jJ.some(n=>n.test(t))||N.push(t);let F=``;if(S){let t=resolveRootScripts(N,S);t.scripts>0&&(N=t.files,F=`; ${t.scripts} root script(s) resolved to their readers`)}if(N.length===0)return{global:!1,reason:`ignored-only`+F,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};for(let n of N)for(let S of AJ)if(S.test(n))return{global:!0,reason:`global-trigger ${S.source} matched ${n}${F}`,workspaces:t.map(t=>t.name),runE2E:!0,runIntegration:!0,skipAll:!1};let{matched:I,unmatched:H}=workspacesForChangedFiles(t,N),W=new Set(t.map(t=>t.name)),q=new Set,Y=new Set,X=!1;for(let n of NJ){let S=N.filter(t=>n.match.test(t));if(S.length!==0){for(let t of S)Y.add(t);for(let S of n.seeds){if(!W.has(S))return{global:!0,reason:`script-coupling seed ${S} is not a workspace (${n.match.source} → ${n.why}); SCRIPT_COUPLINGS in commands/affected.ts is stale`,workspaces:t.map(t=>t.name),runE2E:!0,runIntegration:!0,skipAll:!1};q.add(S)}n.runE2E&&(X=!0)}}let Z=H.filter(t=>!Y.has(t));if(Z.length>0)return{global:!0,reason:`unmatched files (${Z.length}): ${Z.slice(0,3).join(`, `)}${Z.length>3?`…`:``}${F}`,workspaces:t.map(t=>t.name),runE2E:!0,runIntegration:!0,skipAll:!1};for(let t of q)I.add(t);if(q.size===0&&N.every(t=>MJ.some(n=>n.test(t)))&&I.size===1){let t=[...I][0],n=N.some(t=>t.startsWith(`tests/e2e/`)),S=N.some(t=>t.startsWith(`tests/integration/`));return{global:!1,reason:`test-only (${N.length} file(s) in ${t})${F}`,workspaces:[t],runE2E:n||X,runIntegration:S||isIntegrationWorkspace(t),skipAll:!1}}let te=affectedClosure(buildReverseDependencyGraph(t,{includeDev:!1}),[...I]),ne=buildDependencyGraph(t,{includeDev:!0}),re=!1;for(let[t,n]of ne.edges)if(isIntegrationWorkspace(t)){for(let S of n)if(te.has(S)){te.add(t),re=!0;break}}let ie=N.some(t=>t.startsWith(`tests/e2e/`))||X;return{global:!1,reason:`closure (${te.size} ws from ${I.size} seed(s))`+(q.size>0?`, ${q.size} via script-coupling`:``)+F,workspaces:[...te].sort(),runE2E:ie,runIntegration:re,skipAll:!1}}function isIntegrationWorkspace(t){return t.startsWith(`@gjsify/integration-`)}var AJ,jJ,MJ,NJ,PJ,FJ=__esmMin(()=>{GI(),AJ=[/^packages\/infra\/workspace\//,/^packages\/infra\/cli\//,/^packages\/infra\/rolldown-plugin-gjsify\//,/^packages\/infra\/resolve-npm\//,/^packages\/gjs\/unit\//,/^\.github\/actions\//,/^gjsify-lock\.json$/,/^package\.json$/,/^tsconfig[^/]*\.json$/,/^\.github\/workflows\/main\.yml$/,/^scripts\/audit-runtimes\.mjs$/],jJ=[/\.md$/i,/^refs\//,/^website\//,/^docs\//,/^\.github\/workflows\/(deploy-docs|commitlint|release|release-cut|audit-runtimes|prebuilds|node-gi|napi|cli-cross-platform|build-ci-image|cancel-pr-runs|macos-suites|windows-suites|gtk-os-suites)\.yml$/,/^\.github\/prebuild-toolchain\//,/^scripts\/manifest-conformance\//,/^status\//,/^scripts\/generate-status\.mjs$/,/^packages\/node-gi\//,/^packages\/napi\//,/^flatpak\//,/^LICENSE/,/^\.gitignore$/,/^\.gjsify-[^/]*\.md$/,/^STATUS\.md$/,/^CHANGELOG\.md$/,/^AGENTS\.md$/,/^CLAUDE\.md$/,/^README\.md$/],MJ=[/\.spec\.[mc]?[tj]sx?$/,/^tests\/(e2e|integration)\//],NJ=[{match:/^\.githooks\//,seeds:[],runE2E:!0,why:`tests/e2e/git-hooks-cli-bundle-staleness drives .githooks/pre-commit`},{match:/^templates\//,seeds:[`@gjsify/create-app`],runE2E:!0,why:`@gjsify/create-app build → node scripts/process-template.mjs reads templates/`},{match:/^packages\/framework\/react-native\//,seeds:[],runE2E:!0,why:`tests/e2e/react-native-devtools is the only external observer of AppRegistry.runApplication`}],PJ=/^scripts\/[^/]+$/});function stripCommentLines(t,n){let S=/\.(ya?ml|sh|bash|py|toml)$|(^|\/)\.git[a-z]*$|Dockerfile$/.test(t)?/^\s*#/:/^\s*(\/\/|\/\*|\*)/;return n.split(`
|
|
1901
1901
|
`).filter(t=>!S.test(t)).join(`
|
|
1902
1902
|
`)}function scriptNamePattern(t){let n=On.basename(t),S=/^(.*?)(\.d)?\.[mc]?[jt]sx?$/.exec(n),C=S?`${escapeRe(S[1])}(\\.d)?\\.[mc]?[jt]sx?\\b`:`${escapeRe(n)}\\b`;return RegExp(`(^|[^\\w.-])${C}`)}function gatedJobs(t){let n=new Map,S=new Set;for(let{job:C,text:N}of t){if(!C)continue;n.has(C)||n.set(C,[]);let t=/^ {4}needs:\s*\[(.*)\]/.exec(N)??/^ {4}needs:\s*([A-Za-z0-9_-]+)\s*$/.exec(N);t&&n.set(C,t[1].split(`,`).map(t=>t.trim()).filter(Boolean)),(/needs\.changes\b/.test(N)||/^ {4}needs:\s*$/.test(N))&&S.add(C)}let C=new Set([`changes`,...S]),N=!0;for(;N;){N=!1;for(let[t,S]of n)!C.has(t)&&S.some(t=>C.has(t))&&(C.add(t),N=!0)}return C.delete(`changes`),C}function workflowLines(t){let n=t.split(`
|
|
1903
|
-
`),S=[],C,N=!1;for(let t of n){/^jobs:\s*$/.test(t)?N=!0:/^\S/.test(t)&&(N=!1);let n=N?/^ {2}([A-Za-z0-9_-]+):\s*$/.exec(t):null;n&&(C=n[1]),!/^\s*#/.test(t)&&S.push({job:N?C:void 0,text:t})}return S}function buildScriptReferrers(t){let n=new Map;for(let[S,C]of t)S===
|
|
1903
|
+
`),S=[],C,N=!1;for(let t of n){/^jobs:\s*$/.test(t)?N=!0:/^\S/.test(t)&&(N=!1);let n=N?/^ {2}([A-Za-z0-9_-]+):\s*$/.exec(t):null;n&&(C=n[1]),!/^\s*#/.test(t)&&S.push({job:N?C:void 0,text:t})}return S}function buildScriptReferrers(t){let n=new Map;for(let[S,C]of t)S===IJ||S===LJ||n.set(S,stripCommentLines(S,C));let S=t.get(IJ),C=S===void 0?[]:workflowLines(S),N=gatedJobs(C),gatedWorkflowNames=t=>C.some(n=>t.test(n.text)&&(n.job===void 0||N.has(n.job))),F,I=t.get(LJ);I!==void 0&&(F=JSON.parse(I));let manifestReads=t=>{if(!F)return!1;for(let[n,S]of Object.entries(F))if(n!==`scripts`&&t.test(JSON.stringify(S)))return!0;let n=F.scripts??{};for(let[S,C]of Object.entries(n)){if(!t.test(C))continue;if(zJ.test(S))return!0;let N=RegExp(`(^|[\\s"'])${escapeRe(S)}($|[\\s"'&;|])`);if(Object.entries(n).some(([t,n])=>t!==S&&N.test(n))||gatedWorkflowNames(N))return!0}return!1};return t=>{let S=scriptNamePattern(t),C=[];for(let[N,F]of n)N!==t&&S.test(F)&&C.push(N);return gatedWorkflowNames(S)&&C.push(IJ),manifestReads(S)&&C.push(LJ),C.sort()}}function readTrackedTexts(t){let n=spawnSync(`git`,[`ls-files`,`-z`],{cwd:t,encoding:`utf8`});if(n.status!==0)throw Error(`git ls-files failed (${n.status}): ${String(n.stderr).trim()}`);let S=new Map;for(let C of n.stdout.split(`\0`)){if(!C||C.startsWith(`refs/`))continue;let n=zn(t,C),N=statSync(n,{throwIfNoEntry:!1});if(!N?.isFile()||N.size>RJ)continue;let F=readFileSync(n,`utf8`);F.includes(`\0`)||S.set(C,F)}return S}var IJ,LJ,RJ,zJ,escapeRe,BJ=__esmMin(()=>{cv(),af(),Xn(),IJ=`.github/workflows/main.yml`,LJ=`package.json`,RJ=2*1024*1024,zJ=/^(pre|post)?(install|prepare|build|test)(:|$)/,escapeRe=t=>t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)});function scriptReadersFor(t,n){if(n.some(t=>/^scripts\/[^/]+$/.test(t.replace(/\\/g,`/`))))try{return buildScriptReferrers(readTrackedTexts(t))}catch(t){process.stderr.write(`gjsify affected: cannot index the tree for script readers (${String(t)}); root scripts stay unmatched\n`);return}}function runGitDiff(t,n,S){let C=spawnSync(`git`,[`diff`,`--no-renames`,`--name-only`,`${n}...${S}`],{cwd:t,encoding:`utf8`});if(C.status!==0)throw process.stderr.write(`gjsify affected: git diff failed (${C.status}): ${C.stderr.trim()}\n`),process.exit(2),Error(`gjsify affected: git diff failed (${C.status})`);return C.stdout.split(`
|
|
1904
1904
|
`).filter(Boolean)}function emit(t,n){if(t===`json`){process.stdout.write(JSON.stringify(n)+`
|
|
1905
1905
|
`);return}if(t===`globs`){for(let t of n.workspaces)process.stdout.write(`${t}\n`);return}if(t===`github-actions`){let t=n.global?``:n.workspaces.map(t=>`--include ${assertShellSafeWorkspaceName(t)}`).join(` `),S=process.env.GITHUB_OUTPUT,C=[`skip-all=${n.skipAll}`,`global=${n.global}`,`include-args=${t}`,`run-integration=${n.runIntegration}`,`run-e2e=${n.runE2E}`,`reason=${n.reason}`];if(S)for(let t of C)appendFileSync(S,`${t}\n`);else for(let t of C)process.stdout.write(`${t}\n`);return}process.stdout.write(`affected:
|
|
1906
|
-
`),process.stdout.write(` reason: ${n.reason}\n`),process.stdout.write(` global: ${n.global}\n`),process.stdout.write(` skip-all: ${n.skipAll}\n`),process.stdout.write(` run-integration: ${n.runIntegration}\n`),process.stdout.write(` run-e2e: ${n.runE2E}\n`),process.stdout.write(` workspaces (${n.workspaces.length}):\n`);for(let t of n.workspaces)process.stdout.write(` - ${t}\n`)}function assertShellSafeWorkspaceName(t){if(
|
|
1906
|
+
`),process.stdout.write(` reason: ${n.reason}\n`),process.stdout.write(` global: ${n.global}\n`),process.stdout.write(` skip-all: ${n.skipAll}\n`),process.stdout.write(` run-integration: ${n.runIntegration}\n`),process.stdout.write(` run-e2e: ${n.runE2E}\n`),process.stdout.write(` workspaces (${n.workspaces.length}):\n`);for(let t of n.workspaces)process.stdout.write(` - ${t}\n`)}function assertShellSafeWorkspaceName(t){if(HJ.test(t))return t;throw process.stderr.write(`gjsify affected: workspace name ${JSON.stringify(t)} is not shell-safe, so it cannot be emitted as an\n \`include-args\` token (the value is consumed by an UNQUOTED $INCLUDE_ARGS expansion — see the\n contract at the top of commands/affected.ts). Rename the workspace, or teach this command a\n transport the consumers can unquote. Refusing to emit a filter that would silently mis-match.\n`),process.exit(2),Error(`gjsify affected: unsafe workspace name ${t}`)}var VJ,HJ,UJ=__esmMin(()=>{cv(),af(),kJ(),GI(),FJ(),BJ(),qI(),VJ={command:`affected`,description:"Classify changed files against the workspace tree and print the set of workspaces affected (seeds + transitive dependents). Designed for CI to gate `gjsify foreach test --include …` so unrelated workspaces are not re-tested on every PR.",builder:t=>t.option(`base`,{description:"Diff base. Default: `origin/main`. Resolved via `git rev-parse`. On a PR set this to `${{ github.event.pull_request.base.sha }}`.",type:`string`}).option(`head`,{description:"Diff head. Default: `HEAD`.",type:`string`,default:`HEAD`}).option(`format`,{description:`Output shape.`,choices:[`text`,`json`,`globs`,`github-actions`],default:`text`}).option(`changed-from-stdin`,{description:"Skip `git diff`. Read a newline-separated list of repo-relative paths from stdin instead. Lets callers — tests, ad-hoc scripts — control the input exactly.",type:`boolean`,default:!1}).option(`cwd`,{description:"Workspace root. Default: discovered from `process.cwd()`.",type:`string`}),handler:async t=>{let n=t.cwd??findWorkspaceRoot(process.cwd())??process.cwd(),S=discoverWorkspaces(n,{includeRoot:!0}),C=t[`changed-from-stdin`]?readStdinLines():runGitDiff(n,t.base??`origin/main`,t.head??`HEAD`),N=classifyAndExpand(S,C,scriptReadersFor(n,C));emit(t.format,N)}},HJ=/^[A-Za-z0-9@][A-Za-z0-9@._/-]*$/}),WJ=__exportAll$5({isSelfWrite:()=>isSelfWrite,runWatchLoop:()=>runWatchLoop,spawnBundleSupervised:()=>spawnBundleSupervised,spawnSupervised:()=>spawnSupervised});function spawnSupervised(t,n,S){return new Promise((C,N)=>{spawnToCompletion(t,n,{completion:`daemon`,env:S,onSpawn:C}).catch(N)})}async function spawnBundleSupervised(t,n,S,C){if(t!==`gjs`){let{bundleRequiresNodeGi:N,resolveNodeGiForBundle:F}=await Promise.resolve().then(()=>(UR(),HR));if(N(n)&&!F(n,S))throw Error(`Cannot run ${C} on ${t}: \`@gjsify/node-gi\` is not installed. Add @gjsify/node-gi as a dependency to run ${C} on ${t}.`)}let{computeNativeEnvForBundle:N}=await Promise.resolve().then(()=>(VR(),BR)),{env:F}=N(n,S),I={...process.env,...F};if(t===`gjs`)return spawnSupervised(`gjs`,[`-m`,n],I);if(t===`node`){let{nodeBinary:t}=await Promise.resolve().then(()=>(UR(),HR));return spawnSupervised(t(),[n],I)}let[H,W]=_v[t].launch(n);return spawnSupervised(H,W,I)}function isSelfWrite(t,n,S){if(n===void 0||S===null)return!1;let C=In(t,S),N=In(t,n);if(C===N||C.startsWith(`${N}.`))return!0;let F=Hn(N);return F===In(t)?!1:C===F||C.startsWith(`${F}${qn}`)}async function runWatchLoop(t){let{dir:n,label:S,prepare:C,build:N,spawnChild:F,output:I,ignore:H,debounceMs:W=200}=t;markDaemonCommand();let q=null,Y=!1,X=!1,rebuild=async()=>{if(Y){X=!0;return}Y=!0;try{C&&await C(),q&&=(q.kill(),null),await N(),F&&(q=await F())}catch(t){ge.error(`[${S}] rebuild failed: ${t.message}`)}finally{Y=!1,X&&(X=!1,rebuild())}};await rebuild();let Z=null,te=(t.watch??[{path:n,recursive:!0}]).map(t=>watch(t.path,{recursive:t.recursive},(n,S)=>{let C=typeof S==`string`?S:null;isSelfWrite(t.path,I,C)||H&&C!==null&&H(In(t.path,C))||(Z&&clearTimeout(Z),Z=setTimeout(()=>void rebuild(),W))}));holdMainLoop();let ne=!1,shutdown=()=>{if(!ne){ne=!0,Z&&clearTimeout(Z),q?.kill();for(let t of te)t.close();process.exit(0)}};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),ge.log(`[${S}] watching ${t.dirLabel??n} — press Ctrl+C to stop`)}var GJ=__esmMin(()=>{_e(),af(),Xn(),Ue(),tB(),hv(),vv()});function readPackage$4(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function findStoryFiles(t){let n=[];if(!existsSync(t))return n;for(let S of readdirSync(t,{withFileTypes:!0})){if(S.name===`node_modules`||S.name.startsWith(`.`))continue;let C=zn(t,S.name);S.isDirectory()?n.push(...findStoryFiles(C)):/\.story\.(ts|js|mts|mjs)$/.test(S.name)&&n.push(C)}return n}function generateEntry$4(t,n,S){let C=t.map((t,n)=>`import * as m${n} from ${JSON.stringify(t)};`).join(`
|
|
1907
1907
|
`),N=t.map((t,n)=>`m${n}`).join(`, `),F=S?`\n title: ${JSON.stringify(S)},`:``;return`// Auto-generated by \`gjsify storybook\` — do not edit by hand.
|
|
1908
1908
|
import { collectStoryModules, runStorybook } from '@gjsify/storybook';
|
|
1909
1909
|
${C}
|
|
@@ -1912,10 +1912,10 @@ await runStorybook({
|
|
|
1912
1912
|
applicationId: ${JSON.stringify(n)},${F}
|
|
1913
1913
|
stories: collectStoryModules([${N}]),
|
|
1914
1914
|
});
|
|
1915
|
-
`}var
|
|
1915
|
+
`}var KJ,qJ=__esmMin(()=>{_e(),af(),Xn(),P_(),__name$1(readPackage$4,`readPackage`),__name$1(generateEntry$4,`generateEntry`),KJ={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:t=>t.option(`stories`,{description:`Directory scanned recursively for *.story.ts (default: src, or gjsify.storybook.stories)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.storybook.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto; use auto,dom for canvas/DOM stories)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-storybook)`,type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle (gi:// → @gjsify/node-gi) and require @gjsify/node-gi installed in the project.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`watch`,{description:`Rebuild and relaunch when a story file changes`,type:`boolean`,default:!1}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$4(n),C=S.gjsify?.storybook??{},N=In(n,t.stories??C.stories??`src`),F=t.appId??C.applicationId??deriveAppId(S.name),I=t.title??C.title,H=t.globals??C.globals??`auto`,W=t.runtime??C.runtime??hostRuntime$1(),q=W===`gjs`?`gjs`:`node`,Y=zn(n,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`storybook.${q}.mjs`),writeEntry=()=>{let t=findStoryFiles(N).sort();return writeFileSync(X,generateEntry$4(t,F,I)),t.length},te=writeEntry();if(te===0)return ge.error(`No *.story.ts files found under ${Bn(n,N)||N}\n\n \`gjsify storybook\` renders the stories of the CURRENT project: it discovers\n \`*.story.ts\` files and launches a component browser over them. Point it at a\n different directory with --stories <dir> (or \`gjsify.storybook.stories\` in\n package.json) if yours live elsewhere.\n\n To SEE a storybook without authoring one first, run the curated Libadwaita\n component browser — it is a showcase, so it needs no project at all:\n\n gjsify showcase adwaita-storybook`),process.exit(1);ge.log(`Found ${te} story file(s) under ${Bn(n,N)||`.`} (runtime: ${W})`);let{runCli:ne}=await Promise.resolve().then(()=>(HX(),VX)),buildBundle=()=>ne([`build`,X,`--app`,q,`--globals`,H,`--outfile`,Z]),launch=async()=>{if(W===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(VR(),BR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else if(W===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(UR(),HR));await t(Z,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:t}=await Promise.resolve().then(()=>(UR(),HR));await t(W,Z,[],{completion:`exit`,exitOnSuccess:!0})}};if(!t.watch){if(await buildBundle(),t.buildOnly)return;await launch();return}let{runWatchLoop:re,spawnBundleSupervised:ie}=await Promise.resolve().then(()=>(GJ(),WJ));await re({dir:N,dirLabel:Bn(n,N)||`.`,label:`storybook`,prepare:()=>{writeEntry()},build:buildBundle,spawnChild:t.buildOnly?null:()=>ie(W,Z,n,`the storybook`),output:Z})}}});function resolveSitePackage(t){let n=In(t);for(;;){let t=zn(n,`node_modules`,`@gjsify`,`site`);if(existsSync(zn(t,`package.json`)))return t;let S=Hn(n);if(S===n)return;n=S}}function gjsOnPath(){return spawnSync(`gjs`,[`--version`],{stdio:`ignore`}).status===0}function pickRuntime(t,n){if(t)return t;let S=hostRuntime$1();return S===`gjs`||resolveNodeGi(n)?S:gjsOnPath()?`gjs`:S}function generateEntry$3(t,n=`gjsify site`){let S=`// Auto-generated by \`${n}\` — do not edit by hand.\nimport { runSiteCli } from '@gjsify/site';\n`;return t===`gjs`?`${S}import system from 'system';\n\nsystem.exit(await runSiteCli(system.programArgs));\n`:`${S}\nprocess.exit(await runSiteCli(process.argv.slice(2)));\n`}async function dispatchSite(t){let n=process.cwd(),S=resolveSitePackage(n);if(!S)return ge.error(`${t.invokedAs}: @gjsify/site is not installed in this project.\n\n The generator ships as its own package so a project only pays for it when it
|
|
1916
1916
|
publishes a page or a store listing. Add it, then run this again:
|
|
1917
1917
|
|
|
1918
|
-
npm install --save-dev @gjsify/site`),process.exit(1);if(t.needsClient&&!existsSync(zn(S,`lib`,`client`,`site.js`)))return ge.error(`${t.invokedAs}: ${S} has no built client bundle (lib/client/site.js).\n In a source checkout, build the package first: \`gjsify workspace site build\`.`),process.exit(1);let C=pickRuntime(t.runtime,n),N=C===`gjs`?`gjs`:`node`,F=zn(n,`node_modules`,`.cache`,`gjsify-site`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.${N}.ts`),H=zn(F,`site.${N}.mjs`);writeFileSync(I,generateEntry$3(N,t.invokedAs));let W=t.globals??`auto`;if(N===`gjs`){let{BuildAction:t}=await Promise.resolve().then(()=>(mR(),dR));await t.bundleFileForGjs(I,H,{globals:W,preserveDefaultExport:!1,toolchainAnchor:t.runningCliFile(),logLevel:`silent`})}else{let{runCli:t}=await Promise.resolve().then(()=>(
|
|
1918
|
+
npm install --save-dev @gjsify/site`),process.exit(1);if(t.needsClient&&!existsSync(zn(S,`lib`,`client`,`site.js`)))return ge.error(`${t.invokedAs}: ${S} has no built client bundle (lib/client/site.js).\n In a source checkout, build the package first: \`gjsify workspace site build\`.`),process.exit(1);let C=pickRuntime(t.runtime,n),N=C===`gjs`?`gjs`:`node`,F=zn(n,`node_modules`,`.cache`,`gjsify-site`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.${N}.ts`),H=zn(F,`site.${N}.mjs`);writeFileSync(I,generateEntry$3(N,t.invokedAs));let W=t.globals??`auto`;if(N===`gjs`){let{BuildAction:t}=await Promise.resolve().then(()=>(mR(),dR));await t.bundleFileForGjs(I,H,{globals:W,preserveDefaultExport:!1,toolchainAnchor:t.runningCliFile(),logLevel:`silent`})}else{let{runCli:t}=await Promise.resolve().then(()=>(HX(),VX));await t([`build`,I,`--app`,N,`--globals`,W,`--outfile`,H])}let q=[...t.argv.slice(0,1),`--package-dir`,S,...t.argv.slice(1)];if(C===`gjs`){let{runGjsBundle:t}=await Promise.resolve().then(()=>(VR(),BR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}if(C===`node`){let{runNodeBundle:t}=await Promise.resolve().then(()=>(UR(),HR));await t(H,q,{completion:`exit`,exitOnSuccess:!0});return}let{runRuntimeBundle:Y}=await Promise.resolve().then(()=>(UR(),HR));await Y(C,H,q,{completion:`exit`,exitOnSuccess:!0})}var JJ=__esmMin(()=>{_e(),cv(),af(),Xn(),P_(),UR(),__name$1(generateEntry$3,`generateEntry`)}),YJ,XJ=__esmMin(()=>{Xn(),JJ(),YJ={command:`site <operation>`,description:`Render this project's static landing page from its AppStream metainfo (downloads, screenshots, release notes, support links), or sync the page catalogues.`,builder:t=>t.positional(`operation`,{description:`build — render the pages; i18n — update the page catalogues`,type:`string`,choices:[`build`,`i18n`],demandOption:!0}).option(`root`,{description:`Repository to read from (default: the working directory)`,type:`string`}).option(`out`,{description:`Output directory, emptied first (default: <root>/dist)`,type:`string`}).option(`offline`,{description:`Skip every network call`,type:`boolean`,default:!1}).option(`drafts`,{description:"build: include blog posts marked `draft: true`",type:`boolean`,default:!1}).option(`cache`,{description:`Use the one-hour HTTP response cache (--no-cache to ignore it)`,type:`boolean`,default:!0}).option(`cache-dir`,{description:`Where the response cache and the image renditions live`,defaultDescription:`<root>/node_modules/.cache/gjsify-site`,type:`string`}).option(`check`,{description:`i18n: report what is out of date instead of writing it`,type:`boolean`,default:!1}).option(`package`,{description:`i18n: sync @gjsify/site's own catalogues instead of this project's`,type:`boolean`,default:!1}).option(`runtime`,{description:"Runtime to build for and run on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle and require @gjsify/node-gi in the project; without it the default falls back to gjs.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}),handler:async t=>{let n=process.cwd(),S=[t.operation];t.root&&S.push(`--root`,In(n,t.root)),t.out&&S.push(`--out`,In(n,t.out)),t.offline&&S.push(`--offline`),t.drafts&&S.push(`--drafts`),t.cache?t.cacheDir&&S.push(`--cache-dir`,In(n,t.cacheDir)):S.push(`--no-cache`),t.check&&S.push(`--check`),t.package&&S.push(`--package`),await dispatchSite({invokedAs:`gjsify site`,argv:S,runtime:t.runtime,globals:t.globals,needsClient:t.operation===`build`})}}});function readFlag(t,n){let S=`--${n}`;for(let n=0;n<t.length;n++){let C=t[n];if(C===S)return t[n+1];if(C.startsWith(`${S}=`))return C.slice(S.length+1)}}function withFlag(t,n,S){let C=`--${n}`,N=[...t];for(let t=0;t<N.length;t++){let n=N[t];if(n===C)return N[t+1]=S,N;if(n.startsWith(`${C}=`))return N[t]=`${C}=${S}`,N}return N.push(C,S),N}function buildEntryPoint(t){let n=t[1];if(!(n===void 0||n.startsWith(`-`)))return n}function noEntryError(t,n){let S=n?`\`${t}\` is not a plain \`gjsify build <entry> …\` command, so its entry point cannot be read`:`this package declares no \`${t}\` script`;return Error(`gjsify dev: nothing to build — ${S}.\n Name the entry point directly: gjsify dev src/index.ts\n or point at another script: gjsify dev --script <name>`)}function planDev(t){let n=t.scripts[t.scriptName],S=typeof n==`string`?gjsifyCommandArgv(n):null,C=S&&S[0]===`build`?S:null,N=t.entry??(C?buildEntryPoint(C):void 0);if(N===void 0)throw noEntryError(t.scriptName,typeof n==`string`);let F;return C?(F=[...C],buildEntryPoint(C)===void 0?F.splice(1,0,N):F[1]=N):F=[`build`,N],F=withFlag(F,`app`,t.app),t.globals!==void 0&&(F=withFlag(F,`globals`,t.globals)),t.outfile!==void 0&&(F=withFlag(F,`outfile`,t.outfile)),{buildArgv:F,bundle:readFlag(F,`outfile`)??t.declaredBundle,watchDir:t.watchDir??Hn(N)}}function noBundleError(t,n){return Error(`gjsify dev: nothing to launch — neither \`${t}\` nor --outfile names an output file, and this package declares no ${n===`gjs`?"`gjsify.main`":"`gjsify.example.node`"}.\n Pass one: gjsify dev --outfile dist/index.${n}.mjs\n or rebuild without launching: gjsify dev --build-only`)}var ZJ=__esmMin(()=>{Xn(),sR()});function readPackage$3(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}var QJ,$J=__esmMin(()=>{_e(),af(),Xn(),ZJ(),vv(),P_(),__name$1(readPackage$3,`readPackage`),QJ={command:`dev [entry]`,description:`Watch this project, rebuild on change and relaunch the app.`,builder:t=>t.positional(`entry`,{description:"Entry point to build (default: the one the build script names, e.g. src/index.ts from `build:gjs`).",type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle.",type:`string`,choices:gv,defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`script`,{description:`package.json script the build flags are read from (default: build:gjs, or build:node for node/bun/deno).`,type:`string`}).option(`globals`,{description:"Override the build script `--globals` value.",type:`string`}).option(`outfile`,{description:"Override the build script `--outfile` path.",type:`string`}).option(`watch-dir`,{description:`Directory watched recursively (default: the directory of the entry point).`,type:`string`}).option(`debounce`,{description:`Quiet window in ms after a change before rebuilding.`,type:`number`,default:200}).option(`build-only`,{description:`Rebuild on every change but never launch the app.`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$3(n),C=t.runtime??hostRuntime$1(),N=buildAppForRuntime(C),F=t.script??(N===`gjs`?`build:gjs`:`build:node`),I;try{I=planDev({scripts:S.scripts??{},scriptName:F,app:N,declaredBundle:N===`gjs`?S.gjsify?.main:S.gjsify?.example?.node,entry:t.entry,globals:t.globals,outfile:t.outfile,watchDir:t.watchDir})}catch(t){return ge.error(t.message),process.exit(1)}let H=I.bundle===void 0?void 0:In(n,I.bundle);if(H===void 0&&!t.buildOnly)return ge.error(noBundleError(F,N).message),process.exit(1);let W=In(n,I.watchDir);if(!existsSync(W))return ge.error(`gjsify dev: nothing to watch — ${Bn(n,W)||W} does not exist.\n Point the loop at your sources: gjsify dev --watch-dir <dir>`),process.exit(1);let q=H===void 0?`\`${F}\` output`:Bn(n,H);ge.log(`Watching ${Bn(n,W)||`.`} → ${q} (runtime: ${C})`);let{runCli:Y}=await Promise.resolve().then(()=>(HX(),VX)),{runWatchLoop:X,spawnBundleSupervised:Z}=await Promise.resolve().then(()=>(GJ(),WJ));await X({dir:W,dirLabel:Bn(n,W)||`.`,label:`dev`,build:()=>Y(I.buildArgv),spawnChild:t.buildOnly||H===void 0?null:()=>Z(C,H,n,`this project`),output:H,debounceMs:t.debounce})}}});function readPackage$2(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveStorybookAppId(t){return t?`org.gjsify.storybook.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function deriveBrowserAppId$1(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function hasDep(t,n){return!!(t.dependencies?.[n]||t.devDependencies?.[n])}function generateEntry$2(t,n,S,C,N){let F=JSON.stringify(n),I=N?`, { address: ${JSON.stringify(N)} }`:``;return t===`storybook`?`// Auto-generated by \`gjsify debug\` — do not edit by hand.
|
|
1919
1919
|
import { runDevtoolsMcp, storybookProfile } from '@gjsify/devtools-mcp';
|
|
1920
1920
|
|
|
1921
1921
|
await runDevtoolsMcp(storybookProfile(${F}${I}));
|
|
@@ -1935,24 +1935,24 @@ await runDevtoolsMcp({
|
|
|
1935
1935
|
version: ${JSON.stringify(C)},
|
|
1936
1936
|
busNameBase: ${F},${N?`\n address: ${JSON.stringify(N)},`:``}
|
|
1937
1937
|
});
|
|
1938
|
-
`}var
|
|
1938
|
+
`}var eY,tY=__esmMin(()=>{_e(),af(),Xn(),__name$1(readPackage$2,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$2,`generateEntry`),eY={command:`debug`,description:`Launch an MCP bridge for a devtools-enabled gjsify app (org.gjsify.Devtools).`,builder:t=>t.option(`bus-name`,{description:`App DBus base name (default: gjsify.devtools.busNameBase, or the storybook app-id)`,type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`profile`,{description:`Tool profile: generic | storybook | browser | cdp (default: auto — storybook if @gjsify/storybook is a dep, browser if @gjsify/devtools-browser is, cdp if @gjsify/devtools-cdp is, else generic)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-debug)`,type:`string`}).option(`build-only`,{description:`Build the bridge bundle but do not launch it (for a .mcp.json command pointing at the bundle)`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage$2(n),C=S.gjsify?.devtools??{},N=t.profile??C.profile??(hasDep(S,`@gjsify/storybook`)?`storybook`:hasDep(S,`@gjsify/devtools-browser`)?`browser`:hasDep(S,`@gjsify/devtools-cdp`)?`cdp`:`generic`),F=t.busName??C.busNameBase??(N===`storybook`?S.gjsify?.storybook?.applicationId??deriveStorybookAppId(S.name):N===`browser`||N===`cdp`?S.gjsify?.browse?.applicationId??deriveBrowserAppId$1(S.name):void 0);if(!F)return ge.error(`gjsify debug: no bus name — set package.json#gjsify.devtools.busNameBase or pass --bus-name <org.example.App>`),process.exit(1);let I=t.globals??C.globals??`auto`,H=S.name?`${S.name}-devtools`:`gjsify-devtools`,W=zn(n,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(W,{recursive:!0});let q=zn(W,`entry.ts`),Y=t.out?In(n,t.out):zn(W,`bridge.gjs.mjs`),X=t.address??C.address;writeFileSync(q,generateEntry$2(N,F,H,`0.8.0`,X)),ge.error(`[gjsify debug] profile=${N} bus=${F}${X?` address=${X}`:``}`);let{runCli:Z}=await Promise.resolve().then(()=>(HX(),VX));if(await Z([`build`,q,`--app`,`gjs`,`--shebang`,`--globals`,I,`--outfile`,Y]),t.buildOnly){ge.error(`[gjsify debug] built ${Y}`);return}let{runGjsBundle:te}=await Promise.resolve().then(()=>(VR(),BR));await te(Y,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage$1(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function generateEntry$1(){return`// Auto-generated by \`gjsify devtools\` — do not edit by hand.
|
|
1939
1939
|
import system from 'system';
|
|
1940
1940
|
|
|
1941
1941
|
import { runDevtoolsCli } from '@gjsify/devtools-mcp';
|
|
1942
1942
|
|
|
1943
1943
|
system.exit(await runDevtoolsCli(system.programArgs));
|
|
1944
|
-
`}var
|
|
1944
|
+
`}var nY,rY=__esmMin(()=>{_e(),af(),Xn(),__name$1(readPackage$1,`readPackage`),__name$1(generateEntry$1,`generateEntry`),nY={command:`devtools <operation> [operands..]`,description:"Drive a running devtools-enabled app from a script: capture a screenshot to a file, find a widget, activate it, send a key. Peer of `gjsify debug`, which speaks MCP for an AI agent.",builder:t=>t.positional(`operation`,{description:`Control-plane operation: shot | find | activate | key | tree | property | …`,type:`string`,demandOption:!0}).positional(`operands`,{description:"Subcommand arguments — e.g. the output path for `shot`, the selector for `find`.",type:`string`,array:!0}).option(`bus-name`,{description:"App DBus base name — the app's Gtk application id (default: gjsify.devtools.busNameBase, then the storybook app-id). Unlike `gjsify debug` there is no derived fallback: the bus name IS the application id, and guessing it produces a name nothing answers to",type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`instance`,{description:`App instance label for a multi-instance app (default: GJSIFY_DEVTOOLS_INSTANCE)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-devtools)`,type:`string`}).option(`timeout`,{description:`Seconds to keep polling GetStatus for the control plane to answer (default: 30). 0 = do not wait`,type:`number`,default:30}),handler:async t=>{let n=process.cwd(),S=readPackage$1(n),C=S.gjsify?.devtools??{},N=t.busName??C.busNameBase??S.gjsify?.storybook?.applicationId??S.gjsify?.browse?.applicationId;if(!N)return ge.error(`gjsify devtools: no bus name — the bus name IS the app's Gtk application id, so it cannot be derived from the package name. Pass --bus-name <org.example.App> (the app prints it when it exports the control plane) or set package.json#gjsify.devtools.busNameBase.`),process.exit(1);let F=zn(n,`node_modules`,`.cache`,`gjsify-devtools`);mkdirSync(F,{recursive:!0});let I=zn(F,`entry.ts`),H=t.out?In(n,t.out):zn(F,`cli.gjs.mjs`),W=t.globals??`auto`;writeFileSync(I,generateEntry$1()),ge.error(`[gjsify devtools] bus=${N}${t.address?` address=${t.address}`:``}${t.instance?` instance=${t.instance}`:``}`);let{runCli:q}=await Promise.resolve().then(()=>(HX(),VX));await q([`build`,I,`--app`,`gjs`,`--globals`,W,`--outfile`,H]);let Y=[t.operation,...t.operands??[],`--bus-name`,N];t.address&&Y.push(`--address`,t.address),t.instance&&Y.push(`--instance`,t.instance),Y.push(`--timeout`,String(t.timeout));let{runGjsBundle:X}=await Promise.resolve().then(()=>(VR(),BR));await X(H,Y,{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(t){try{return JSON.parse(readFileSync(zn(t,`package.json`),`utf8`))}catch{return{}}}function deriveBrowserAppId(t){return t?`org.gjsify.browser.${t.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function generateEntry(t,n,S,C,N){let F=S?`\n title: ${JSON.stringify(S)},`:``,I=n?`\n homeUrl: ${JSON.stringify(n)},`:``,H=C===void 0?``:`\n inspectorPort: ${C},`,W=N?`\n screenshot: ${JSON.stringify(N)},`:``;return`// Auto-generated by \`gjsify browse\` — do not edit by hand.
|
|
1945
1945
|
import { runBrowserDevtools } from '@gjsify/devtools-browser';
|
|
1946
1946
|
|
|
1947
1947
|
await runBrowserDevtools({
|
|
1948
1948
|
applicationId: ${JSON.stringify(t)},${F}${I}${H}${W}
|
|
1949
1949
|
});
|
|
1950
|
-
`}var
|
|
1951
|
-
`)}`);let W=`en`in I?`en`:Object.keys(I)[0];return{input:{description:C,...Object.keys(N).length>0?{privacyPolicy:N}:{},...W===void 0?{}:{approvalNotesText:I[W]}},locales:F}}var
|
|
1952
|
-
`).trim(),createAmoBackend=(t,n={})=>{let S=t.AMO_ADDON_ID,C=t.AMO_WEB_EXT_API_KEY,N=t.AMO_WEB_EXT_API_SECRET,F=secretValuesOf(cY,t),I=n.now??(()=>Date.now()),H=`${lY}/addons/addon/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,uY),W=null;async function send(t,S,F={},H=[]){let W={Authorization:`JWT ${signJwt(C,N,I())}`},q;F.json===void 0?F.form!==void 0&&(q=F.form):(W[`Content-Type`]=`application/json`,q=JSON.stringify(F.json)),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(W))}`);let Y=n.fetchImpl??globalThis.fetch,X;try{X=await Y(S,{method:t,headers:W,body:q})}catch(t){throw new StoreApiError(cY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${X.status}`),X.status>=200&&X.status<300||H.includes(X.status))return X;let Z=await X.text().catch(()=>``);throw new StoreApiError(cY,X.status,failureDetail(X.status,Z))}function failureDetail(t,n){let C=clean(n.trim()),N=C===``?``:` Store said: ${C}`;return t===401?fY+N:t===403?`the account is not an author of ${clean(S)}, or lacks permission.${N}`:t===404?`unknown add-on or version — check AMO_ADDON_ID (slug, numeric id or GUID).${N}`:t===429?`throttled — too many requests; retry later.`:C===``?`the store gave no reason.`:C}async function json(t,n){try{return JSON.parse(await t.text())}catch{throw new StoreApiError(cY,t.status,`${n} answered something that is not JSON.`)}}async function versionExists(t){return(await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404])).status!==404}function judge(t,n){if(t.valid===!0)return;let S=validationLines(t.validation).map(clean);throw S.some(t=>/already exists/i.test(t))?new StoreVersionAlreadyThereError(cY,n):new StoreApiError(cY,200,S.length===0?`AMO validation rejected the package and gave no message.`:`AMO validation rejected the package: ${S.join(` | `)}`)}async function upload(t){if(await versionExists(t.version))throw new StoreVersionAlreadyThereError(cY,t.version);let n=new FormData;n.append(`upload`,new Blob([new Uint8Array(readFileSync(t.zipPath))]),Un(t.zipPath)),n.append(`channel`,`listed`);let S=await send(`POST`,`${lY}/addons/upload/`,{form:n}),C=await json(S,`the upload`);if(typeof C.uuid!=`string`||C.uuid===``)throw new StoreApiError(cY,S.status,`the upload answered without a uuid.`);return W={uuid:C.uuid,version:t.version},C.processed===!0?(judge(C,t.version),{operationId:C.uuid,ingested:!0,detail:`upload ${C.uuid} validated; no version created.`}):{operationId:C.uuid,ingested:!1,detail:`HTTP ${S.status} — upload ${C.uuid} is being validated.`}}async function operation(t,n,S){if(t!==`upload`)throw new StoreApiError(cY,void 0,`AMO has no publish operation to read; a version create answers directly.`);let C=await json(await send(`GET`,`${lY}/addons/upload/${encodeURIComponent(n)}/`),`the upload detail`);return C.processed===!0?(judge(C,S??C.version??`in the upload`),{state:`succeeded`,detail:`upload ${n} passed validation; no version created yet.`}):{state:`in-progress`,detail:`upload ${n} is still being validated.`}}async function publish(t){if(W===null)throw new StoreApiError(cY,void 0,`publish needs an upload from this run; none was made.`);let n=await send(`POST`,`${H}/versions/`,{json:{upload:W.uuid,...t.notes===void 0||t.notes===``?{}:{approval_notes:t.notes}}}),S=(await json(n,`the version create`)).id??t.version;if(t.sourceZip!==void 0){let n=new FormData;n.append(`source`,new Blob([new Uint8Array(readFileSync(t.sourceZip))]),Un(t.sourceZip)),await send(`PATCH`,`${H}/versions/${encodeURIComponent(String(S))}/`,{form:n})}return{state:`in-review`,detail:`HTTP ${n.status} — version ${t.version} created from upload ${W.uuid}, which puts it into review`+(t.sourceZip===void 0?` (no source archive attached).`:`; source archive attached.`)}}async function status(){if(W===null){let t=await json(await send(`GET`,`${H}/`),`the add-on detail`);return{state:`unknown`,version:t.current_version?.version,detail:`AMO reports ${t.current_version?.version??`no public version`} as the current version.`}}let{version:t}=W,n=await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404]);if(n.status===404)return{state:`draft`,version:t,detail:`AMO has no version ${t}; only a validated upload.`};let S=(await json(n,`the version detail`)).file?.status;return{state:S===`public`?`published`:`in-review`,version:t,detail:`AMO has version ${t} with file status ${clean(String(S))}.`}}async function verifyCredentials(){await send(`GET`,`${H}/`)}let versionRef=t=>/^\d+$/.test(t)?t:`v${encodeURIComponent(t)}`;async function readBack(t,n){try{return{body:await json(await send(`GET`,t),n)}}catch(t){if(t instanceof StoreApiError)return{unread:t.message};throw t}}function compareLocales(t,n,S,C){return Object.entries(n).map(([n,N])=>{let F={field:t,locale:n,sent:N.length};if(C!==null)return{...F,verdict:`unread`,detail:C.unread};if(typeof S!=`object`||!S)return{...F,verdict:`unread`,detail:`AMO returned no per-locale ${t}.`};let I=S[n];return typeof I==`string`?sameText(I,N)?{...F,verdict:`match`,detail:`read back ${I.length} chars.`}:{...F,verdict:`mismatch`,detail:`AMO holds ${I.length} chars, sent ${N.length}.`}:{...F,verdict:`mismatch`,detail:`AMO holds no ${t} for ${n}.`}})}async function updateListing(t){await send(`PATCH`,`${H}/`,{json:{description:t.description}}),t.privacyPolicy!==void 0&&await send(`PATCH`,`${H}/eula_policy/`,{json:{privacy_policy:t.privacyPolicy}});let n=t.approvalNotes,S=n===void 0?``:`${H}/versions/${versionRef(n.version)}/`;n!==void 0&&await send(`PATCH`,S,{json:{approval_notes:n.text}});let C=[],N=await readBack(`${H}/`,`the add-on detail`),F=`unread`in N?N:null,I=`body`in N?N.body:{};if(C.push(...compareLocales(`description`,t.description,I.description,F)),t.privacyPolicy!==void 0){let n=await readBack(`${H}/eula_policy/`,`the eula_policy`);C.push(...compareLocales(`privacy_policy`,t.privacyPolicy,`body`in n?n.body.privacy_policy:void 0,`unread`in n?n:null))}if(n!==void 0){let t=await readBack(S,`the version detail`),N={field:`approval_notes`,sent:n.text.length};`unread`in t?C.push({...N,verdict:`unread`,detail:t.unread}):typeof t.body.approval_notes==`string`?sameText(t.body.approval_notes,n.text)?C.push({...N,verdict:`match`,detail:`read back ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`mismatch`,detail:`AMO holds ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`unread`,detail:`AMO returned no approval_notes.`})}return{fields:C}}return{store:cY,upload,publish,status,operation,verifyCredentials,updateListing}}});function createChromeBackend(t,n={}){let S=t.CHROME_WEB_STORE_PUBLISHER_ID,C=t.CHROME_WEB_STORE_ITEM_ID,N=`publishers/${encodeURIComponent(S)}/items/${encodeURIComponent(C)}`,F=[...secretValuesOf(`chrome`,t)],I=n.fetchImpl??((...t)=>globalThis.fetch(...t)),H,scrub=t=>redactSecrets(t,F),fail=(t,n)=>new StoreApiError(`chrome`,t,scrub(n)),describe=async t=>{let n=await t.text().catch(()=>``);try{let t=JSON.parse(n),S=typeof t.error==`string`?[t.error,t.error_description].filter(Boolean).join(`: `):t.error?.message;if(S)return S.slice(0,400)}catch{}return n.trim().slice(0,200)||`empty response`},send=async(t,S)=>{n.log?.(`${S.method??`GET`} ${t} ${JSON.stringify(redactHeaders(S.headers))}`);try{return await I(t,S)}catch(t){throw fail(void 0,t instanceof Error?t.message:String(t))}},token=async()=>{if(H!==void 0)return H;let n=new URLSearchParams({client_id:t.CHROME_WEB_STORE_CLIENT_ID,client_secret:t.CHROME_WEB_STORE_CLIENT_SECRET,refresh_token:t.CHROME_WEB_STORE_REFRESH_TOKEN,grant_type:`refresh_token`}),S=await send(hY,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:n.toString()});if(!S.ok){let t=await describe(S),n=S.status===400||S.status===401?` ${_Y}`:``;throw fail(S.status,`token exchange refused: ${t}.${n}`)}let C=await S.json().catch(()=>({}));if(typeof C.access_token!=`string`||C.access_token===``)throw fail(S.status,`token exchange answered without an access_token`);return H=C.access_token,F.push(H),H},call=async(t,n)=>{let S=await token();return send(t,{...n,headers:{...n.headers,authorization:`Bearer ${S}`}})},readStatus=async()=>{let t=await call(`${gY}/v2/${N}:fetchStatus`,{method:`GET`});if(!t.ok)throw fail(t.status,`fetchStatus failed: ${await describe(t)}`);return await t.json().catch(()=>{throw fail(t.status,`fetchStatus answered with something that is not JSON`)})},refuseIfBusy=(t,n)=>{let S=t.submittedItemRevisionStatus,C=versionOf(S);if(S?.state===`PENDING_REVIEW`)throw C===n?new StoreVersionAlreadyThereError(`chrome`,n):new StoreInReviewError(`chrome`,`version ${C??`(unknown)`} is pending review; wait for it or cancel it in the Developer Dashboard.`);if(versionOf(t.publishedItemRevisionStatus)===n||C===n)throw new StoreVersionAlreadyThereError(`chrome`,n)},classify=t=>{switch(t){case`PENDING_REVIEW`:return`in-review`;case`PUBLISHED`:case`PUBLISHED_TO_TESTERS`:return`published`;case`REJECTED`:return`rejected`;case`STAGED`:case`CANCELLED`:return`draft`;default:return`unknown`}},verifyCredentials=async()=>{let t=await call(`${gY}/v2/${N}:fetchStatus`,{method:`GET`});if(t.ok)return;let n=await describe(t);throw t.status===401?fail(t.status,`fetchStatus refused the access token: ${n}. ${_Y}`):t.status===403?fail(t.status,`fetchStatus is forbidden: ${n}. The Google account behind CHROME_WEB_STORE_REFRESH_TOKEN is not a publisher of this item, or CHROME_WEB_STORE_PUBLISHER_ID / CHROME_WEB_STORE_ITEM_ID name someone else’s item — check both ids, or renew the refresh token with the account that owns the item.`):t.status===404?fail(t.status,`fetchStatus found no such item: ${n}. Check CHROME_WEB_STORE_PUBLISHER_ID and CHROME_WEB_STORE_ITEM_ID.`):fail(t.status,`fetchStatus failed: ${n}`)};return{store:`chrome`,verifyCredentials,async upload(t){refuseIfBusy(await readStatus(),t.version);let n=await call(`${gY}/upload/v2/${N}:upload`,{method:`POST`,headers:{"content-type":`application/zip`},body:readFileSync(t.zipPath)});if(!n.ok)throw fail(n.status,`upload failed: ${await describe(n)}`);let S=await n.json().catch(()=>({}));switch(S.uploadState){case`SUCCEEDED`:return{operationId:S.name,ingested:!0,detail:`uploadState SUCCEEDED, crxVersion ${S.crxVersion??`(not reported)`}`};case`IN_PROGRESS`:return{operationId:S.name,ingested:!1,detail:`uploadState IN_PROGRESS — poll fetchStatus`};case`FAILED`:throw fail(n.status,`upload accepted but the store reports uploadState FAILED; check the package in the Developer Dashboard`);default:throw fail(n.status,`upload answered with uploadState ${S.uploadState??`(none)`}, which is not a state this client knows`)}},async publish(t){let n=(await readStatus()).submittedItemRevisionStatus;if(n?.state===`PENDING_REVIEW`)throw new StoreInReviewError(`chrome`,`version ${versionOf(n)??`(unknown)`} is pending review already.`);let S=t.deployPercentage!==void 0&&t.deployPercentage<100?{deployInfos:[{deployPercentage:t.deployPercentage}]}:{},C=await call(`${gY}/v2/${N}:publish`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(S)});if(!C.ok){let t=await describe(C),n=C.status===400||C.status===409||C.status===412?` ${vY}`:``;throw fail(C.status,`publish refused: ${t}.${n}`)}let F=await C.json().catch(()=>({}));return{state:classify(F.state),detail:`publish answered state ${F.state??`(none)`}`}},async status(){let t=await readStatus();if(t.takenDown===!0)return{state:`rejected`,detail:`takenDown is true — a policy violation; see the Developer Dashboard`};if(t.lastAsyncUploadState===`IN_PROGRESS`)return{state:`unknown`,ingesting:!0,detail:`lastAsyncUploadState IN_PROGRESS`};if(t.lastAsyncUploadState===`FAILED`)return{state:`rejected`,detail:`lastAsyncUploadState FAILED — the store could not ingest the package`};let n=t.submittedItemRevisionStatus;if(n?.state!==void 0)return{state:classify(n.state),version:versionOf(n),detail:`submittedItemRevisionStatus.state ${n.state}`};let S=t.publishedItemRevisionStatus;return S?.state===void 0?{state:`unknown`,detail:`fetchStatus carried no revision status and no upload state in the past 24 h`}:{state:classify(S.state),version:versionOf(S),detail:`publishedItemRevisionStatus.state ${S.state}`}}}}var hY,gY,_Y,vY,versionOf,yY=__esmMin(()=>{af(),MY(),hY=`https://oauth2.googleapis.com/token`,gY=`https://chromewebstore.googleapis.com`,_Y=`Create a new OAuth client in the Google Cloud Console (APIs & Services → Credentials) and a new refresh token with the scope https://www.googleapis.com/auth/chromewebstore, e.g. in https://developers.google.com/oauthplayground ("Use your own OAuth credentials"); then update CHROME_WEB_STORE_CLIENT_ID, CHROME_WEB_STORE_CLIENT_SECRET and CHROME_WEB_STORE_REFRESH_TOKEN.`,vY=`If the visibility was changed in the Developer Dashboard, the API refuses to publish until the item has been published by hand once with the new visibility: publish once in the Developer Dashboard by hand (einmal im Dashboard von Hand veröffentlichen), then retry.`,versionOf=t=>t?.distributionChannels?.find(t=>t.crxVersion!==void 0)?.crxVersion});function operationIdFrom(t){if(t===null)return null;let n=t.trim().split(`?`)[0].split(`/`).filter(Boolean);return n.length>0?n[n.length-1]:null}function errorLines(t){return Array.isArray(t)?t.map(t=>typeof t==`string`?t:typeof t==`object`&&t&&typeof t.message==`string`?t.message:JSON.stringify(t)):[]}var bY,xY,SY,CY,wY,createEdgeBackend,TY=__esmMin(()=>{af(),MY(),bY=`edge`,xY=`https://api.addons.microsoftedge.microsoft.com`,SY=`00000000-0000-0000-0000-000000000000`,CY=400,wY=`The API key was rejected. API keys expire (Microsoft announced 72 days — unverified in the API docs); renew it in Partner Center → Microsoft Edge → Publish API → "Create API credentials", then update EDGE_ADDONS_API_KEY.`,createEdgeBackend=(t,n={})=>{let S=t.EDGE_ADDONS_PRODUCT_ID,C=t.EDGE_ADDONS_CLIENT_ID,N=t.EDGE_ADDONS_API_KEY,F=[...secretValuesOf(bY,t),C],I=`${xY}/v1/products/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,CY),H=null;async function send(t,S,F={}){let I={Authorization:`ApiKey ${N}`,"X-ClientID":C};F.contentType!==void 0&&(I[`Content-Type`]=F.contentType),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(I))}`);let H=n.fetchImpl??globalThis.fetch,W;try{W=await H(S,{method:t,headers:I,body:F.body})}catch(t){throw new StoreApiError(bY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${W.status}`),W.status>=200&&W.status<300)return W;let q=await W.text().catch(()=>``);throw new StoreApiError(bY,W.status,failureDetail(W.status,q))}function failureDetail(t,n){let S=clean(n.trim());return t===401?S===``?wY:`${wY} Store said: ${S}`:t===404?`the product id or operation id is unknown, or the product is not yours — check EDGE_ADDONS_PRODUCT_ID.`+(S===``?``:` Store said: ${S}`):t===429?`throttled — too many requests; retry later.`:S===``?`the store gave no reason.`:S}async function accepted(t,n){let S=operationIdFrom(t.headers.get(`location`));if(S===null)throw new StoreApiError(bY,t.status,`${n} was accepted but the response has no Location header.`);return S}async function upload(t){let n=new Uint8Array(readFileSync(t.zipPath)),S=await send(`POST`,`${I}/submissions/draft/package`,{contentType:`application/zip`,body:n}),C=await accepted(S,`the upload`);return{operationId:C,ingested:!1,detail:`HTTP ${S.status} accepted — upload operation ${C} is pending.`}}async function publish(t){let n=t.notes??``,S=JSON.stringify({notes:n}),C=await send(`POST`,`${I}/submissions`,{contentType:`application/json`,body:S}),N=await accepted(C,`the publish request`);return H={operationId:N,version:t.version},{state:`unknown`,operationId:N,detail:`HTTP ${C.status} accepted — publish operation ${N} is pending; the submission is not confirmed yet.`}}async function operation(t,n,S){let C=await send(`GET`,`${I}/${t===`upload`?`submissions/draft/package/operations`:`submissions/operations`}/${encodeURIComponent(n)}`),N=await C.text(),F;try{F=JSON.parse(N)}catch{throw new StoreApiError(bY,C.status,`the ${t} operation answered something that is not JSON.`)}let H=clean(F.message??``);switch(F.status){case`InProgress`:return{state:`in-progress`,detail:`${t} operation ${n} is still running.`};case`Succeeded`:return{state:`succeeded`,detail:H===``?`${t} operation succeeded.`:H};case`Failed`:throw failure(F,H,S);default:throw new StoreApiError(bY,C.status,`the ${t} operation has an unrecognised status: ${clean(String(F.status))}.`)}}function failure(t,n,S){let C=t.errorCode??``;if(C===`NoModulesUpdated`)return new StoreVersionAlreadyThereError(bY,S??`in the draft`);if(C===`InProgressSubmission`)return new StoreInReviewError(bY,n===``?`a submission is already in progress.`:n);let N=errorLines(t.errors).map(clean),F=[C===``?null:`${C}:`,n===``?null:n,...N].filter(t=>t!==null).join(` `);return new StoreApiError(bY,200,F===``?`the operation failed without a reason.`:F)}async function status(){if(H===null)return{state:`unknown`,detail:`Edge Add-ons has no endpoint that reads a product; only an operation id can be read, and this run has none.`};let t=await operation(`publish`,H.operationId,H.version);return t.state===`succeeded`?{state:`in-review`,version:H.version,detail:t.detail}:{state:`unknown`,version:H.version,detail:t.detail}}async function verifyCredentials(){try{await send(`GET`,`${I}/submissions/operations/${SY}`)}catch(t){if(t instanceof StoreApiError&&t.httpStatus===404)return;throw t}}return{store:bY,upload,publish,status,operation,verifyCredentials}}});function asStoreId(t){return EY.includes(t)?t:null}function resolveStoreCredentials(t,n){let S=DY[t],C={},N=[];for(let t of S){let S=n[t.env];S===void 0||S===``?N.push(t):C[t.env]=S}if(N.length>0)throw new StoreCredentialsMissingError(t,N);return C}function secretValuesOf(t,n){return DY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function redactHeaders(t){let n={};for(let[S,C]of Object.entries(t)){let t=S.toLowerCase();n[t]=AY.includes(t)||/token|secret|key/.test(t)?kY:C}return n}function redactSecrets(t,n){let S=t;for(let t of[...n].filter(t=>t.length>1).sort((t,n)=>n.length-t.length))S=S.split(t).join(kY);return S}function isIdempotentSkip(t){return t instanceof StoreVersionAlreadyThereError||t instanceof StoreInReviewError}function createStoreBackend(t,n,S){let C=jY[t];if(C===void 0)throw new StoreUnsupportedError(t,`no backend is registered for it`);return C(resolveStoreCredentials(t,n),S)}var EY,DY,OY,kY,AY,StoreCredentialsMissingError,StoreUnsupportedError,StoreVersionAlreadyThereError,StoreInReviewError,StoreApiError,jY,MY=__esmMin(()=>{mY(),yY(),TY(),EY=[`chrome`,`edge`,`amo`],DY={chrome:[{env:`CHROME_WEB_STORE_PUBLISHER_ID`,secret:!1,what:`the publisher the item belongs to`},{env:`CHROME_WEB_STORE_ITEM_ID`,secret:!1,what:`the item id from the Developer Dashboard`},{env:`CHROME_WEB_STORE_CLIENT_ID`,secret:!1,what:`the OAuth client id`},{env:`CHROME_WEB_STORE_CLIENT_SECRET`,secret:!0,what:`the OAuth client secret`},{env:`CHROME_WEB_STORE_REFRESH_TOKEN`,secret:!0,what:`the refresh token the access token is minted from`}],edge:[{env:`EDGE_ADDONS_PRODUCT_ID`,secret:!1,what:`the product id from Partner Center`},{env:`EDGE_ADDONS_CLIENT_ID`,secret:!1,what:`the client id sent as X-ClientID`},{env:`EDGE_ADDONS_API_KEY`,secret:!0,what:"the API key sent as `Authorization: ApiKey …`"}],amo:[{env:`AMO_ADDON_ID`,secret:!1,what:`the add-on slug, numeric id or GUID of the existing listing`},{env:`AMO_WEB_EXT_API_KEY`,secret:!1,what:"the AMO JWT issuer (API key, `user:…`) — also in every token payload"},{env:`AMO_WEB_EXT_API_SECRET`,secret:!0,what:`the AMO JWT secret`}]},OY={chrome:{id:`chrome`,label:`Chrome Web Store`,implemented:!0,createsListings:!1},edge:{id:`edge`,label:`Edge Add-ons`,implemented:!0,createsListings:!1},amo:{id:`amo`,label:`addons.mozilla.org`,implemented:!0,createsListings:!1}},kY=`<redacted>`,AY=[`authorization`,`x-clientid`,`x-goog-api-key`,`cookie`,`set-cookie`],StoreCredentialsMissingError=class extends Error{store;missing;constructor(t,n){super(`gjsify webext submit: ${OY[t].label} needs ${n.length} environment variable(s) this run does not set:\n`+n.map(t=>` ${t.env} — ${t.what}`).join(`
|
|
1950
|
+
`}var iY,aY=__esmMin(()=>{_e(),af(),Xn(),iY={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:t=>t.positional(`url`,{description:`Initial URL to load (default: page:welcome)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.browse.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto,dom — WebKit/iframe need DOM globals)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-browse)`,type:`string`}).option(`devtools`,{description:`Enable the MCP devtools control plane (sets GJSIFY_DEVTOOLS=1)`,type:`boolean`,default:!1}).option(`inspector-port`,{description:`Enable WebKit's remote inspector protocol on this port + the Cdp* methods (implies --devtools)`,type:`number`}).option(`screenshot`,{description:`One-shot: load the URL, capture a WebKit screenshot to this path, and exit (CI / quick captures).`,type:`string`}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async t=>{let n=process.cwd(),S=readPackage(n),C=S.gjsify?.browse??{},N=t.appId??C.applicationId??deriveBrowserAppId(S.name),F=t.title??C.title,I=t.globals??C.globals??`auto,dom`,H=t.url,W=t.inspectorPort??C.inspectorPort,q=t.devtools||W!==void 0,Y=zn(n,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(Y,{recursive:!0});let X=zn(Y,`entry.ts`),Z=t.out?In(n,t.out):zn(Y,`browse.gjs.mjs`);writeFileSync(X,generateEntry(N,H,F,W,t.screenshot?In(n,t.screenshot):void 0)),ge.log(`[gjsify browse] app=${N}${H?` url=${H}`:``}${q?` devtools=1`:``}${W===void 0?``:` inspector-port=${W}`}`);let{runCli:te}=await Promise.resolve().then(()=>(HX(),VX));if(await te([`build`,X,`--app`,`gjs`,`--globals`,I,`--outfile`,Z]),t.buildOnly){ge.log(`[gjsify browse] built ${Z}`);return}q&&(process.env.GJSIFY_DEVTOOLS=`1`),W!==void 0&&(process.env.WEBKIT_INSPECTOR_HTTP_SERVER=`127.0.0.1:${W}`);let{runGjsBundle:ne}=await Promise.resolve().then(()=>(VR(),BR));await ne(Z,[],{completion:`exit`,exitOnSuccess:!0})}}});function amoLocale(t){let[n=``,S]=t.replace(/_/g,`-`).split(`-`),C=n.toLowerCase(),N=oY.find(t=>t.toLowerCase()===(S===void 0?C:`${C}-${S.toLowerCase()}`));if(N!==void 0)return N;if(C===`en`)return`en-US`;if(oY.includes(C))return C;let F=oY.filter(t=>t.startsWith(`${C}-`));return F.length===1?F[0]:null}function readAmoListing(t){let n=zn(t,`amo`);if(!existsSync(n))throw Error(`${n} does not exist. Run \`gjsify webext listing --store amo\` first.`);let S=[],C={},N={},F={},I={},H=readdirSync(n).filter(t=>statSync(zn(n,t)).isDirectory()&&existsSync(zn(n,t,`description.txt`))).sort();for(let t of H){let H=zn(n,t),W=amoLocale(t);if(W===null){S.push(`language "${t}" has no AMO locale (known: ${oY.join(`, `)}).`);continue}let q=Object.entries(F).find(([,t])=>t===W);if(q!==void 0){S.push(`languages "${q[0]}" and "${t}" both map to AMO locale ${W}.`);continue}F[t]=W;let Y=readText(H,`description.txt`);Y===void 0||Y===``?S.push(`${t}/description.txt is missing or empty.`):C[W]=Y;let X=readText(H,`privacy.txt`);X!==void 0&&X!==``&&(N[W]=X);let Z=readText(H,`reviewer-notes.txt`);Z!==void 0&&Z!==``&&(I[t]=Z)}if(H.length===0&&S.push(`${n} holds no language directory with a description.txt.`),S.length>0)throw Error(`the AMO listing in ${n} cannot be sent:\n ${S.join(`
|
|
1951
|
+
`)}`);let W=`en`in I?`en`:Object.keys(I)[0];return{input:{description:C,...Object.keys(N).length>0?{privacyPolicy:N}:{},...W===void 0?{}:{approvalNotesText:I[W]}},locales:F}}var oY,readText,sY=__esmMin(()=>{af(),Xn(),oY=`ar.bg.ca.cak.cs.da.de.dsb.el.en-CA.en-GB.en-US.es.eu.fa.fi.fr.fy-NL.ga-IE.he.hsb.hu.id.it.ja.ka.kab.ko.mk.mn.nl.pl.pt-BR.pt-PT.ro.ru.sk.sl.sq.sv-SE.tr.uk.vi.zh-CN.zh-TW`.split(`.`),readText=(t,n)=>{let S=zn(t,n);return existsSync(S)?readFileSync(S,`utf8`).trim():void 0}});async function runListingUpload(t){let{approvalNotesText:n,...S}=readAmoListing(In(t.listingRoot)).input;if(t.notesVersion!==void 0&&n===void 0)throw Error(`--notes-version is set but no amo/<lang>/reviewer-notes.txt exists.`);let C={...S,...t.notesVersion!==void 0&&n!==void 0?{approvalNotes:{version:t.notesVersion,text:n}}:{}};if(t.dryRun){t.out(`addons.mozilla.org listing: dry run — nothing is sent, no request is made.`);let lines=(n,S)=>{for(let[C,N]of Object.entries(S))t.out(` would send ${n} [${C}]: ${N.length} chars`)};return lines(`description`,C.description),C.privacyPolicy!==void 0&&lines(`privacy_policy (eula_policy)`,C.privacyPolicy),C.approvalNotes!==void 0&&t.out(` would send approval_notes (version ${C.approvalNotes.version}): ${C.approvalNotes.text.length} chars`),t.out(` name and summary are never sent: AMO takes the name from the manifest, and the store summary is the manifest description.`),0}let N=t.backend();if(N.updateListing===void 0)throw Error(`this store has no listing API; only AMO takes listing texts.`);let F=await N.updateListing(C),I=0;for(let n of F.fields)n.verdict!==`match`&&(I+=1),t.out(` ${n.field}${n.locale===void 0?``:` [${n.locale}]`}: ${n.verdict} — ${n.detail}`);return t.out(I===0?`addons.mozilla.org listing: ${F.fields.length} field(s) written and read back, all match.`:`addons.mozilla.org listing: ${I} of ${F.fields.length} field(s) NOT confirmed by the read-back.`),I===0?0:1}var cY=__esmMin(()=>{Xn(),sY()});function signJwt(t,n,S){let C=Math.floor(S/1e3),N=b64url(JSON.stringify({alg:`HS256`,typ:`JWT`})),F=b64url(JSON.stringify({iss:t,jti:randomBytes(16).toString(`hex`),iat:C,exp:C+fY})),I=createHmac(`sha256`,n).update(`${N}.${F}`).digest();return`${N}.${F}.${b64url(I)}`}function validationLines(t){if(typeof t!=`object`||!t)return[];let n=t.messages;if(!Array.isArray(n))return[];let S=[];for(let t of n){if(typeof t!=`object`||!t)continue;let n=t;n.type!==void 0&&n.type!==`error`||(typeof n.message==`string`?S.push(n.message):typeof n.description==`string`&&S.push(n.description))}return S}var lY,uY,dY,fY,pY,b64url,sameText,mY,normalizeText,createAmoBackend,hY=__esmMin(()=>{gl(),af(),Xn(),NY(),lY=`amo`,uY=`https://addons.mozilla.org/api/v5`,dY=400,fY=60,pY=`the JWT was rejected — check AMO_WEB_EXT_API_KEY / AMO_WEB_EXT_API_SECRET (addons.mozilla.org → Developer Hub → Manage API Keys) and that this machine's clock is correct; AMO refuses a JWT whose iat/exp are off.`,b64url=t=>Buffer.from(t).toString(`base64url`),sameText=(t,n)=>normalizeText(t)===normalizeText(n),mY={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`},normalizeText=t=>t.replace(/<\/?a\b[^>]*>/gi,``).replace(/&(?:#(\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos));/gi,(t,n,S,C)=>{if(C!==void 0)return mY[C.toLowerCase()];let N=n===void 0?parseInt(S,16):Number(n);return N<=1114111?String.fromCodePoint(N):t}).replace(/\r\n/g,`
|
|
1952
|
+
`).trim(),createAmoBackend=(t,n={})=>{let S=t.AMO_ADDON_ID,C=t.AMO_WEB_EXT_API_KEY,N=t.AMO_WEB_EXT_API_SECRET,F=secretValuesOf(lY,t),I=n.now??(()=>Date.now()),H=`${uY}/addons/addon/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,dY),W=null;async function send(t,S,F={},H=[]){let W={Authorization:`JWT ${signJwt(C,N,I())}`},q;F.json===void 0?F.form!==void 0&&(q=F.form):(W[`Content-Type`]=`application/json`,q=JSON.stringify(F.json)),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(W))}`);let Y=n.fetchImpl??globalThis.fetch,X;try{X=await Y(S,{method:t,headers:W,body:q})}catch(t){throw new StoreApiError(lY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${X.status}`),X.status>=200&&X.status<300||H.includes(X.status))return X;let Z=await X.text().catch(()=>``);throw new StoreApiError(lY,X.status,failureDetail(X.status,Z))}function failureDetail(t,n){let C=clean(n.trim()),N=C===``?``:` Store said: ${C}`;return t===401?pY+N:t===403?`the account is not an author of ${clean(S)}, or lacks permission.${N}`:t===404?`unknown add-on or version — check AMO_ADDON_ID (slug, numeric id or GUID).${N}`:t===429?`throttled — too many requests; retry later.`:C===``?`the store gave no reason.`:C}async function json(t,n){try{return JSON.parse(await t.text())}catch{throw new StoreApiError(lY,t.status,`${n} answered something that is not JSON.`)}}async function versionExists(t){return(await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404])).status!==404}function judge(t,n){if(t.valid===!0)return;let S=validationLines(t.validation).map(clean);throw S.some(t=>/already exists/i.test(t))?new StoreVersionAlreadyThereError(lY,n):new StoreApiError(lY,200,S.length===0?`AMO validation rejected the package and gave no message.`:`AMO validation rejected the package: ${S.join(` | `)}`)}async function upload(t){if(await versionExists(t.version))throw new StoreVersionAlreadyThereError(lY,t.version);let n=new FormData;n.append(`upload`,new Blob([new Uint8Array(readFileSync(t.zipPath))]),Un(t.zipPath)),n.append(`channel`,`listed`);let S=await send(`POST`,`${uY}/addons/upload/`,{form:n}),C=await json(S,`the upload`);if(typeof C.uuid!=`string`||C.uuid===``)throw new StoreApiError(lY,S.status,`the upload answered without a uuid.`);return W={uuid:C.uuid,version:t.version},C.processed===!0?(judge(C,t.version),{operationId:C.uuid,ingested:!0,detail:`upload ${C.uuid} validated; no version created.`}):{operationId:C.uuid,ingested:!1,detail:`HTTP ${S.status} — upload ${C.uuid} is being validated.`}}async function operation(t,n,S){if(t!==`upload`)throw new StoreApiError(lY,void 0,`AMO has no publish operation to read; a version create answers directly.`);let C=await json(await send(`GET`,`${uY}/addons/upload/${encodeURIComponent(n)}/`),`the upload detail`);return C.processed===!0?(judge(C,S??C.version??`in the upload`),{state:`succeeded`,detail:`upload ${n} passed validation; no version created yet.`}):{state:`in-progress`,detail:`upload ${n} is still being validated.`}}async function publish(t){if(W===null)throw new StoreApiError(lY,void 0,`publish needs an upload from this run; none was made.`);let n=await send(`POST`,`${H}/versions/`,{json:{upload:W.uuid,...t.notes===void 0||t.notes===``?{}:{approval_notes:t.notes}}}),S=(await json(n,`the version create`)).id??t.version;if(t.sourceZip!==void 0){let n=new FormData;n.append(`source`,new Blob([new Uint8Array(readFileSync(t.sourceZip))]),Un(t.sourceZip)),await send(`PATCH`,`${H}/versions/${encodeURIComponent(String(S))}/`,{form:n})}return{state:`in-review`,detail:`HTTP ${n.status} — version ${t.version} created from upload ${W.uuid}, which puts it into review`+(t.sourceZip===void 0?` (no source archive attached).`:`; source archive attached.`)}}async function status(){if(W===null){let t=await json(await send(`GET`,`${H}/`),`the add-on detail`);return{state:`unknown`,version:t.current_version?.version,detail:`AMO reports ${t.current_version?.version??`no public version`} as the current version.`}}let{version:t}=W,n=await send(`GET`,`${H}/versions/v${encodeURIComponent(t)}/`,{},[404]);if(n.status===404)return{state:`draft`,version:t,detail:`AMO has no version ${t}; only a validated upload.`};let S=(await json(n,`the version detail`)).file?.status;return{state:S===`public`?`published`:`in-review`,version:t,detail:`AMO has version ${t} with file status ${clean(String(S))}.`}}async function verifyCredentials(){await send(`GET`,`${H}/`)}let versionRef=t=>/^\d+$/.test(t)?t:`v${encodeURIComponent(t)}`;async function readBack(t,n){try{return{body:await json(await send(`GET`,t),n)}}catch(t){if(t instanceof StoreApiError)return{unread:t.message};throw t}}function compareLocales(t,n,S,C){return Object.entries(n).map(([n,N])=>{let F={field:t,locale:n,sent:N.length};if(C!==null)return{...F,verdict:`unread`,detail:C.unread};if(typeof S!=`object`||!S)return{...F,verdict:`unread`,detail:`AMO returned no per-locale ${t}.`};let I=S[n];return typeof I==`string`?sameText(I,N)?{...F,verdict:`match`,detail:`read back ${I.length} chars.`}:{...F,verdict:`mismatch`,detail:`AMO holds ${I.length} chars, sent ${N.length}.`}:{...F,verdict:`mismatch`,detail:`AMO holds no ${t} for ${n}.`}})}async function updateListing(t){await send(`PATCH`,`${H}/`,{json:{description:t.description}}),t.privacyPolicy!==void 0&&await send(`PATCH`,`${H}/eula_policy/`,{json:{privacy_policy:t.privacyPolicy}});let n=t.approvalNotes,S=n===void 0?``:`${H}/versions/${versionRef(n.version)}/`;n!==void 0&&await send(`PATCH`,S,{json:{approval_notes:n.text}});let C=[],N=await readBack(`${H}/`,`the add-on detail`),F=`unread`in N?N:null,I=`body`in N?N.body:{};if(C.push(...compareLocales(`description`,t.description,I.description,F)),t.privacyPolicy!==void 0){let n=await readBack(`${H}/eula_policy/`,`the eula_policy`);C.push(...compareLocales(`privacy_policy`,t.privacyPolicy,`body`in n?n.body.privacy_policy:void 0,`unread`in n?n:null))}if(n!==void 0){let t=await readBack(S,`the version detail`),N={field:`approval_notes`,sent:n.text.length};`unread`in t?C.push({...N,verdict:`unread`,detail:t.unread}):typeof t.body.approval_notes==`string`?sameText(t.body.approval_notes,n.text)?C.push({...N,verdict:`match`,detail:`read back ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`mismatch`,detail:`AMO holds ${t.body.approval_notes.length} chars.`}):C.push({...N,verdict:`unread`,detail:`AMO returned no approval_notes.`})}return{fields:C}}return{store:lY,upload,publish,status,operation,verifyCredentials,updateListing}}});function createChromeBackend(t,n={}){let S=t.CHROME_WEB_STORE_PUBLISHER_ID,C=t.CHROME_WEB_STORE_ITEM_ID,N=`publishers/${encodeURIComponent(S)}/items/${encodeURIComponent(C)}`,F=[...secretValuesOf(`chrome`,t)],I=n.fetchImpl??((...t)=>globalThis.fetch(...t)),H,scrub=t=>redactSecrets(t,F),fail=(t,n)=>new StoreApiError(`chrome`,t,scrub(n)),describe=async t=>{let n=await t.text().catch(()=>``);try{let t=JSON.parse(n),S=typeof t.error==`string`?[t.error,t.error_description].filter(Boolean).join(`: `):t.error?.message;if(S)return S.slice(0,400)}catch{}return n.trim().slice(0,200)||`empty response`},send=async(t,S)=>{n.log?.(`${S.method??`GET`} ${t} ${JSON.stringify(redactHeaders(S.headers))}`);try{return await I(t,S)}catch(t){throw fail(void 0,t instanceof Error?t.message:String(t))}},token=async()=>{if(H!==void 0)return H;let n=new URLSearchParams({client_id:t.CHROME_WEB_STORE_CLIENT_ID,client_secret:t.CHROME_WEB_STORE_CLIENT_SECRET,refresh_token:t.CHROME_WEB_STORE_REFRESH_TOKEN,grant_type:`refresh_token`}),S=await send(gY,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:n.toString()});if(!S.ok){let t=await describe(S),n=S.status===400||S.status===401?` ${vY}`:``;throw fail(S.status,`token exchange refused: ${t}.${n}`)}let C=await S.json().catch(()=>({}));if(typeof C.access_token!=`string`||C.access_token===``)throw fail(S.status,`token exchange answered without an access_token`);return H=C.access_token,F.push(H),H},call=async(t,n)=>{let S=await token();return send(t,{...n,headers:{...n.headers,authorization:`Bearer ${S}`}})},readStatus=async()=>{let t=await call(`${_Y}/v2/${N}:fetchStatus`,{method:`GET`});if(!t.ok)throw fail(t.status,`fetchStatus failed: ${await describe(t)}`);return await t.json().catch(()=>{throw fail(t.status,`fetchStatus answered with something that is not JSON`)})},refuseIfBusy=(t,n)=>{let S=t.submittedItemRevisionStatus,C=versionOf(S);if(S?.state===`PENDING_REVIEW`)throw C===n?new StoreVersionAlreadyThereError(`chrome`,n):new StoreInReviewError(`chrome`,`version ${C??`(unknown)`} is pending review; wait for it or cancel it in the Developer Dashboard.`);if(versionOf(t.publishedItemRevisionStatus)===n||C===n)throw new StoreVersionAlreadyThereError(`chrome`,n)},classify=t=>{switch(t){case`PENDING_REVIEW`:return`in-review`;case`PUBLISHED`:case`PUBLISHED_TO_TESTERS`:return`published`;case`REJECTED`:return`rejected`;case`STAGED`:case`CANCELLED`:return`draft`;default:return`unknown`}},verifyCredentials=async()=>{let t=await call(`${_Y}/v2/${N}:fetchStatus`,{method:`GET`});if(t.ok)return;let n=await describe(t);throw t.status===401?fail(t.status,`fetchStatus refused the access token: ${n}. ${vY}`):t.status===403?fail(t.status,`fetchStatus is forbidden: ${n}. The Google account behind CHROME_WEB_STORE_REFRESH_TOKEN is not a publisher of this item, or CHROME_WEB_STORE_PUBLISHER_ID / CHROME_WEB_STORE_ITEM_ID name someone else’s item — check both ids, or renew the refresh token with the account that owns the item.`):t.status===404?fail(t.status,`fetchStatus found no such item: ${n}. Check CHROME_WEB_STORE_PUBLISHER_ID and CHROME_WEB_STORE_ITEM_ID.`):fail(t.status,`fetchStatus failed: ${n}`)};return{store:`chrome`,verifyCredentials,async upload(t){refuseIfBusy(await readStatus(),t.version);let n=await call(`${_Y}/upload/v2/${N}:upload`,{method:`POST`,headers:{"content-type":`application/zip`},body:readFileSync(t.zipPath)});if(!n.ok)throw fail(n.status,`upload failed: ${await describe(n)}`);let S=await n.json().catch(()=>({}));switch(S.uploadState){case`SUCCEEDED`:return{operationId:S.name,ingested:!0,detail:`uploadState SUCCEEDED, crxVersion ${S.crxVersion??`(not reported)`}`};case`IN_PROGRESS`:return{operationId:S.name,ingested:!1,detail:`uploadState IN_PROGRESS — poll fetchStatus`};case`FAILED`:throw fail(n.status,`upload accepted but the store reports uploadState FAILED; check the package in the Developer Dashboard`);default:throw fail(n.status,`upload answered with uploadState ${S.uploadState??`(none)`}, which is not a state this client knows`)}},async publish(t){let n=(await readStatus()).submittedItemRevisionStatus;if(n?.state===`PENDING_REVIEW`)throw new StoreInReviewError(`chrome`,`version ${versionOf(n)??`(unknown)`} is pending review already.`);let S=t.deployPercentage!==void 0&&t.deployPercentage<100?{deployInfos:[{deployPercentage:t.deployPercentage}]}:{},C=await call(`${_Y}/v2/${N}:publish`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(S)});if(!C.ok){let t=await describe(C),n=C.status===400||C.status===409||C.status===412?` ${yY}`:``;throw fail(C.status,`publish refused: ${t}.${n}`)}let F=await C.json().catch(()=>({}));return{state:classify(F.state),detail:`publish answered state ${F.state??`(none)`}`}},async status(){let t=await readStatus();if(t.takenDown===!0)return{state:`rejected`,detail:`takenDown is true — a policy violation; see the Developer Dashboard`};if(t.lastAsyncUploadState===`IN_PROGRESS`)return{state:`unknown`,ingesting:!0,detail:`lastAsyncUploadState IN_PROGRESS`};if(t.lastAsyncUploadState===`FAILED`)return{state:`rejected`,detail:`lastAsyncUploadState FAILED — the store could not ingest the package`};let n=t.submittedItemRevisionStatus;if(n?.state!==void 0)return{state:classify(n.state),version:versionOf(n),detail:`submittedItemRevisionStatus.state ${n.state}`};let S=t.publishedItemRevisionStatus;return S?.state===void 0?{state:`unknown`,detail:`fetchStatus carried no revision status and no upload state in the past 24 h`}:{state:classify(S.state),version:versionOf(S),detail:`publishedItemRevisionStatus.state ${S.state}`}}}}var gY,_Y,vY,yY,versionOf,bY=__esmMin(()=>{af(),NY(),gY=`https://oauth2.googleapis.com/token`,_Y=`https://chromewebstore.googleapis.com`,vY=`Create a new OAuth client in the Google Cloud Console (APIs & Services → Credentials) and a new refresh token with the scope https://www.googleapis.com/auth/chromewebstore, e.g. in https://developers.google.com/oauthplayground ("Use your own OAuth credentials"); then update CHROME_WEB_STORE_CLIENT_ID, CHROME_WEB_STORE_CLIENT_SECRET and CHROME_WEB_STORE_REFRESH_TOKEN.`,yY=`If the visibility was changed in the Developer Dashboard, the API refuses to publish until the item has been published by hand once with the new visibility: publish once in the Developer Dashboard by hand (einmal im Dashboard von Hand veröffentlichen), then retry.`,versionOf=t=>t?.distributionChannels?.find(t=>t.crxVersion!==void 0)?.crxVersion});function operationIdFrom(t){if(t===null)return null;let n=t.trim().split(`?`)[0].split(`/`).filter(Boolean);return n.length>0?n[n.length-1]:null}function errorLines(t){return Array.isArray(t)?t.map(t=>typeof t==`string`?t:typeof t==`object`&&t&&typeof t.message==`string`?t.message:JSON.stringify(t)):[]}var xY,SY,CY,wY,TY,createEdgeBackend,EY=__esmMin(()=>{af(),NY(),xY=`edge`,SY=`https://api.addons.microsoftedge.microsoft.com`,CY=`00000000-0000-0000-0000-000000000000`,wY=400,TY=`The API key was rejected. API keys expire (Microsoft announced 72 days — unverified in the API docs); renew it in Partner Center → Microsoft Edge → Publish API → "Create API credentials", then update EDGE_ADDONS_API_KEY.`,createEdgeBackend=(t,n={})=>{let S=t.EDGE_ADDONS_PRODUCT_ID,C=t.EDGE_ADDONS_CLIENT_ID,N=t.EDGE_ADDONS_API_KEY,F=[...secretValuesOf(xY,t),C],I=`${SY}/v1/products/${encodeURIComponent(S)}`,clean=t=>redactSecrets(t,F).slice(0,wY),H=null;async function send(t,S,F={}){let I={Authorization:`ApiKey ${N}`,"X-ClientID":C};F.contentType!==void 0&&(I[`Content-Type`]=F.contentType),n.log?.(`${t} ${S} ${JSON.stringify(redactHeaders(I))}`);let H=n.fetchImpl??globalThis.fetch,W;try{W=await H(S,{method:t,headers:I,body:F.body})}catch(t){throw new StoreApiError(xY,void 0,clean(t instanceof Error?t.message:String(t)))}if(n.log?.(` → HTTP ${W.status}`),W.status>=200&&W.status<300)return W;let q=await W.text().catch(()=>``);throw new StoreApiError(xY,W.status,failureDetail(W.status,q))}function failureDetail(t,n){let S=clean(n.trim());return t===401?S===``?TY:`${TY} Store said: ${S}`:t===404?`the product id or operation id is unknown, or the product is not yours — check EDGE_ADDONS_PRODUCT_ID.`+(S===``?``:` Store said: ${S}`):t===429?`throttled — too many requests; retry later.`:S===``?`the store gave no reason.`:S}async function accepted(t,n){let S=operationIdFrom(t.headers.get(`location`));if(S===null)throw new StoreApiError(xY,t.status,`${n} was accepted but the response has no Location header.`);return S}async function upload(t){let n=new Uint8Array(readFileSync(t.zipPath)),S=await send(`POST`,`${I}/submissions/draft/package`,{contentType:`application/zip`,body:n}),C=await accepted(S,`the upload`);return{operationId:C,ingested:!1,detail:`HTTP ${S.status} accepted — upload operation ${C} is pending.`}}async function publish(t){let n=t.notes??``,S=JSON.stringify({notes:n}),C=await send(`POST`,`${I}/submissions`,{contentType:`application/json`,body:S}),N=await accepted(C,`the publish request`);return H={operationId:N,version:t.version},{state:`unknown`,operationId:N,detail:`HTTP ${C.status} accepted — publish operation ${N} is pending; the submission is not confirmed yet.`}}async function operation(t,n,S){let C=await send(`GET`,`${I}/${t===`upload`?`submissions/draft/package/operations`:`submissions/operations`}/${encodeURIComponent(n)}`),N=await C.text(),F;try{F=JSON.parse(N)}catch{throw new StoreApiError(xY,C.status,`the ${t} operation answered something that is not JSON.`)}let H=clean(F.message??``);switch(F.status){case`InProgress`:return{state:`in-progress`,detail:`${t} operation ${n} is still running.`};case`Succeeded`:return{state:`succeeded`,detail:H===``?`${t} operation succeeded.`:H};case`Failed`:throw failure(F,H,S);default:throw new StoreApiError(xY,C.status,`the ${t} operation has an unrecognised status: ${clean(String(F.status))}.`)}}function failure(t,n,S){let C=t.errorCode??``;if(C===`NoModulesUpdated`)return new StoreVersionAlreadyThereError(xY,S??`in the draft`);if(C===`InProgressSubmission`)return new StoreInReviewError(xY,n===``?`a submission is already in progress.`:n);let N=errorLines(t.errors).map(clean),F=[C===``?null:`${C}:`,n===``?null:n,...N].filter(t=>t!==null).join(` `);return new StoreApiError(xY,200,F===``?`the operation failed without a reason.`:F)}async function status(){if(H===null)return{state:`unknown`,detail:`Edge Add-ons has no endpoint that reads a product; only an operation id can be read, and this run has none.`};let t=await operation(`publish`,H.operationId,H.version);return t.state===`succeeded`?{state:`in-review`,version:H.version,detail:t.detail}:{state:`unknown`,version:H.version,detail:t.detail}}async function verifyCredentials(){try{await send(`GET`,`${I}/submissions/operations/${CY}`)}catch(t){if(t instanceof StoreApiError&&t.httpStatus===404)return;throw t}}return{store:xY,upload,publish,status,operation,verifyCredentials}}});function asStoreId(t){return DY.includes(t)?t:null}function resolveStoreCredentials(t,n){let S=OY[t],C={},N=[];for(let t of S){let S=n[t.env];S===void 0||S===``?N.push(t):C[t.env]=S}if(N.length>0)throw new StoreCredentialsMissingError(t,N);return C}function secretValuesOf(t,n){return OY[t].filter(t=>t.secret).map(t=>n[t.env]).filter(t=>t!==void 0&&t!==``)}function redactHeaders(t){let n={};for(let[S,C]of Object.entries(t)){let t=S.toLowerCase();n[t]=jY.includes(t)||/token|secret|key/.test(t)?AY:C}return n}function redactSecrets(t,n){let S=t;for(let t of[...n].filter(t=>t.length>1).sort((t,n)=>n.length-t.length))S=S.split(t).join(AY);return S}function isIdempotentSkip(t){return t instanceof StoreVersionAlreadyThereError||t instanceof StoreInReviewError}function createStoreBackend(t,n,S){let C=MY[t];if(C===void 0)throw new StoreUnsupportedError(t,`no backend is registered for it`);return C(resolveStoreCredentials(t,n),S)}var DY,OY,kY,AY,jY,StoreCredentialsMissingError,StoreUnsupportedError,StoreVersionAlreadyThereError,StoreInReviewError,StoreApiError,MY,NY=__esmMin(()=>{hY(),bY(),EY(),DY=[`chrome`,`edge`,`amo`],OY={chrome:[{env:`CHROME_WEB_STORE_PUBLISHER_ID`,secret:!1,what:`the publisher the item belongs to`},{env:`CHROME_WEB_STORE_ITEM_ID`,secret:!1,what:`the item id from the Developer Dashboard`},{env:`CHROME_WEB_STORE_CLIENT_ID`,secret:!1,what:`the OAuth client id`},{env:`CHROME_WEB_STORE_CLIENT_SECRET`,secret:!0,what:`the OAuth client secret`},{env:`CHROME_WEB_STORE_REFRESH_TOKEN`,secret:!0,what:`the refresh token the access token is minted from`}],edge:[{env:`EDGE_ADDONS_PRODUCT_ID`,secret:!1,what:`the product id from Partner Center`},{env:`EDGE_ADDONS_CLIENT_ID`,secret:!1,what:`the client id sent as X-ClientID`},{env:`EDGE_ADDONS_API_KEY`,secret:!0,what:"the API key sent as `Authorization: ApiKey …`"}],amo:[{env:`AMO_ADDON_ID`,secret:!1,what:`the add-on slug, numeric id or GUID of the existing listing`},{env:`AMO_WEB_EXT_API_KEY`,secret:!1,what:"the AMO JWT issuer (API key, `user:…`) — also in every token payload"},{env:`AMO_WEB_EXT_API_SECRET`,secret:!0,what:`the AMO JWT secret`}]},kY={chrome:{id:`chrome`,label:`Chrome Web Store`,implemented:!0,createsListings:!1},edge:{id:`edge`,label:`Edge Add-ons`,implemented:!0,createsListings:!1},amo:{id:`amo`,label:`addons.mozilla.org`,implemented:!0,createsListings:!1}},AY=`<redacted>`,jY=[`authorization`,`x-clientid`,`x-goog-api-key`,`cookie`,`set-cookie`],StoreCredentialsMissingError=class extends Error{store;missing;constructor(t,n){super(`gjsify webext submit: ${kY[t].label} needs ${n.length} environment variable(s) this run does not set:\n`+n.map(t=>` ${t.env} — ${t.what}`).join(`
|
|
1953
1953
|
`)+`
|
|
1954
|
-
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: ${OY[t].label} is not implemented — ${n}`),this.store=t,this.name=`StoreUnsupportedError`}},StoreVersionAlreadyThereError=class extends Error{store;version;constructor(t,n){super(`${OY[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(`${OY[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(`${OY[t].label}: ${n===void 0?`request failed`:`HTTP ${n}`} — ${S}`),this.store=t,this.httpStatus=n,this.name=`StoreApiError`}},jY={chrome:createChromeBackend,edge:createEdgeBackend,amo:createAmoBackend}});function pollBackoffFor(t){return stepFrom(FY,t)}function retryBackoffFor(t,n){return stepFrom(n?LY:IY,t)}function isRepeatableFailure(t){if(!(t instanceof StoreApiError))return!1;let n=t.httpStatus;return n===void 0||zY.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:NY[t],detail:clean(n),phases:q,elapsedMs:N()-W,requests:Y,retries:X,retryable:PY.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`&¬e(`${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<RY&&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 NY,PY,FY,IY,LY,RY,stepFrom,zY,BY=__esmMin(()=>{MY(),NY={uploaded:0,submitted:0,published:0,"already-there":0,"in-review":0,rejected:1,failed:1,unresolved:3,unverifiable:4},PY=[`in-review`,`failed`,`unresolved`],FY=[2e3,4e3,8e3,15e3,3e4],IY=[1e3,2e3,4e3],LY=[5e3,15e3,3e4],RY=1,stepFrom=(t,n)=>t[Math.min(Math.max(n,0),t.length-1)]??t[t.length-1]??0,zY=[408,429]});function isTagRef(t){return t!==void 0&&t.startsWith(`refs/tags/`)&&t.length>10}function defaultZipPath(t,n){let S=n===`amo`?`firefox`:n,C=t.targets.find(t=>t.browser===S);if(C===void 0)throw Error(`gjsify webext submit: gjsify.webext.targets has no ${S} target, so there is no zip to derive. Add ${S}-mv3 or pass --zip.`);return zn(t.outDir,`${t.name}-${t.version}-${C.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 findReviewerNotes(t,n){let S=zn(t,n);if(!existsSync(S))return;let C=readdirSync(S).filter(t=>statSync(zn(S,t)).isDirectory()).sort();for(let t of[`en`,...C.filter(t=>t!==`en`)]){if(!C.includes(t))continue;let n=readText(zn(S,t),`reviewer-notes.txt`);if(n!==void 0&&n!==``)return{text:n,path:zn(S,t,`reviewer-notes.txt`)}}}function secretsOf(t,n){return DY[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=OY[C];if(!F.implemented)throw new StoreUnsupportedError(C,`no backend is registered for it`);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 (AMO: validated, no version created).`);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}if(t.listingOnly){if(C!==`amo`)throw Error(`gjsify webext submit: --listing-only applies to AMO only; Chrome and Edge have no listing API.`);if(t.submit||t.zip!==void 0||t.sourceZip!==void 0)throw Error(`gjsify webext submit: --listing-only sends texts only; drop --submit, --zip and --source.`);let N=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0;return await runListingUpload({listingRoot:In(S.root,t.listingDir??`dist/listing`),dryRun:t.dryRun,notesVersion:t.notesVersion,backend:()=>(t.createBackend??createStoreBackend)(C,n,{fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:N}),out})}if(t.notesVersion!==void 0)throw Error(`gjsify webext submit: --notes-version belongs to --listing-only.`);let H=VY[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(`
|
|
1955
|
-
`)}`);q.manual.length>0&&out(` by hand in the dashboard: ${q.manual.join(`, `)}`);let Y=In(t.zip??defaultZipPath(S,C)),X=t.sourceZip===void 0?void 0:In(t.sourceZip);if(X!==void 0&&C!==`amo`)throw Error(`gjsify webext submit: --source applies to AMO only; Chrome and Edge take no source archive.`);if(X!==void 0&&!t.submit)throw Error(`gjsify webext submit: --source is attached to the version, which only --submit creates; add --submit or drop --source.`);if(X!==void 0&&!t.dryRun&&!existsSync(X))throw Error(`gjsify webext submit: the source archive ${X} does not exist.`);if(!t.dryRun&&!existsSync(Y))throw Error(`gjsify webext submit: ${Y} does not exist. Run \`gjsify webext zip\` first or pass --zip.`);let Z=C===`edge`||C===`amo`?findReviewerNotes(In(S.root,t.listingDir??`dist/listing`),H):void 0;Z===void 0&&C===`edge`&&t.submit&&err("warning: no reviewer-notes.txt under the listing dir; Edge reviewers expect certification notes. Run `gjsify webext listing --store edge` first. Continuing without notes.");let te=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0,ne={fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:te},re=(t.createBackend??createStoreBackend)(C,n,ne);if(t.dryRun)return re.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.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0):(await re.verifyCredentials(),out(`${F.label}: dry run — credentials accepted (one read). ${existsSync(Y)?`The zip exists`:`No zip at ${Y} yet`}. Nothing was uploaded.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0);let ie=await driveSubmission({backend:re,upload:{zipPath:Y,version:S.version},publish:t.submit?{version:S.version,sourceZip:X,notes:Z?.text}:void 0},{timeoutMs:I,sleep:t.sleep,now:t.now,log:te,secrets:N}),ae=ie.exitCode===0?out:err;for(let t of describeResult(ie,F.label))ae(t);return NY[ie.verdict]}catch(t){return err(t instanceof Error?t.message:String(t)),1}}var VY,HY=__esmMin(()=>{af(),Xn(),sY(),MY(),oY(),BY(),VY={chrome:`cws`,edge:`edge`,amo:`amo`}});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 UY=__esmMin(()=>{af(),Xn(),wH()});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(()=>(mR(),dR)),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}-${++WY}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++WY}`;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 WY,GY=__esmMin(()=>{af(),Xn(),cr(),P_(),__name$1(isRecord$1,`isRecord`),WY=0});function planPage(t,n,S){let C=Hn(n),N=[],F=[],local=t=>{if(QY.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return Rn(n)?n:In(C,n)},I=S.replace(KY,n=>{let S=JY.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!$Y.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:XY.test(n)?`esm`:`iife`,output:F}),n.replace(JY,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(qY,t=>{if(!ZY.test(t))return t;let n=YY.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(YY,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var KY,qY,JY,YY,XY,ZY,QY,$Y,eX=__esmMin(()=>{Xn(),KY=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,qY=/<link\b[^>]*>/gi,JY=/\bsrc\s*=\s*(["'])([^"']+)\1/i,YY=/\bhref\s*=\s*(["'])([^"']+)\1/i,XY=/\btype\s*=\s*["']module["']/i,ZY=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,QY=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,$Y=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=tX?n:tX}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(`
|
|
1956
|
-
- `)}`);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
|
|
1957
|
-
- `)}`);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??[...
|
|
1958
|
-
- `)}`);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 sX,cX,lX,uX=__esmMin(()=>{af(),Xn(),oX(),sX=[16,32,48,128],cX=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],lX=/^[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 dX,fX=__esmMin(()=>{af(),o_(),Xn(),dL(),oX(),dX="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(()=>(VX(),BX)),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 pX,mX,hX,gX,_X,vX,yX,bX,xX=__esmMin(()=>{_e(),af(),Xn(),qJ(),HY(),nX(),uX(),fX(),pX={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},mX={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},hX={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},gX={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,pX).option(`out-dir`,mX).option(`define`,hX).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)},_X={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,pX).option(`out-dir`,mX).option(`define`,hX),handler:t=>runBuild(t,!0)},vX={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`,{...pX,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,hX).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(dX);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(()=>(WJ(),UJ));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(()=>(WJ(),UJ));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})}},yX={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})}},bX={command:`submit`,description:`Upload the built zip to the Chrome Web Store, Edge Add-ons or Firefox AMO; --submit also asks for review (tags only).`,builder:t=>t.option(`store`,{description:`Which store (amo = addons.mozilla.org, an existing listed add-on).`,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(`source`,{description:`AMO only: source archive for reviewers (needed when the zip is bundled or minified); attached with --submit.`,type:`string`}).option(`listing-only`,{description:`AMO only: send description and privacy policy from --listing-dir (not the zip), then read each back. With --dry-run: lengths only, no network.`,type:`boolean`,default:!1}).option(`notes-version`,{description:`With --listing-only: also send the reviewer notes (approval_notes) to this version id or number.`,type:`string`}).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. AMO: without --submit the zip is only uploaded and validated (no version, no review); --submit creates the version, which enters review at once. 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,sourceZip:t.source?In(n,t.source):void 0,listingOnly:t.listingOnly,notesVersion:t.notesVersion,project:loadSubmitProject(n),env:process.env,out:t=>ge.log(t),err:t=>ge.error(t)});S!==0&&(process.exitCode=S)}}}),SX,CX=__esmMin(()=>{xX(),SX={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(gX.command,gX.description,gX.builder,gX.handler).command(_X.command,_X.description,_X.builder,_X.handler).command(vX.command,vX.description,vX.builder,vX.handler).command(yX.command,yX.description,yX.builder,yX.handler).command(bX.command,bX.description,bX.builder,bX.handler).demandCommand(1).strict()}});function snapRegisterArgs(t){return[`register`,t]}function snapStatusArgs(t){return[`status`,t]}function snapUploadArgs(t,n){let S=[`upload`];return n.length>0&&S.push(`--release=${n.join(`,`)}`),S.push(t),S}function parseChannels(t){let n=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t!==``);for(let t of n)if(!TX.test(t))throw Error(`gjsify snap upload: "${t}" is not a channel (e.g. stable, latest/edge).`);return n}function assertSnapNameForStore(t,n){if(n===void 0||n===``)throw Error(`gjsify snap ${t}: pass the snap name (the store name, e.g. hello-app).`);if(!isSnapName(n))throw Error(`gjsify snap ${t}: "${n}" is not a snap name (lowercase letters, digits, single hyphens).`);return n}function assertSnapCredentials(t){if(t.SNAPCRAFT_STORE_CREDENTIALS===void 0||t.SNAPCRAFT_STORE_CREDENTIALS===``)throw Error(`gjsify snap upload: ${wX} is not set. Create one with \`${TW} export-login --snaps=<name> --acls=package_access,package_push,package_release -\` and pass it through the environment (a CI secret); it is never read from a file.`)}function assertSnapFile(t){if(t===void 0||t===``)throw Error(`gjsify snap upload: pass the .snap file.`);if(!t.endsWith(`.snap`))throw Error(`gjsify snap upload: "${t}" is not a .snap file.`);if(!existsSync(t)||!statSync(t).isFile())throw Error(`gjsify snap upload: no such file: ${t}.`);return t}async function runSnapcraft(t,n){let S=await spawnToCompletion(TW,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify snap ${t}: ${TW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(S.code!==0)throw Error(`gjsify snap ${t}: ${TW} failed with ${describeExit(S)}.`)}var wX,TX,EX=__esmMin(()=>{af(),FW(),hv(),wX=`SNAPCRAFT_STORE_CREDENTIALS`,TX=/^[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*){0,2}$/}),DX,OX,kX,AX=__esmMin(()=>{Xn(),EX(),DX={command:`register <name>`,description:"Claim a snap name in the Snap Store (snapcraft register). Needs an interactive `snapcraft login`.",builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`register`,snapRegisterArgs(assertSnapNameForStore(`register`,t.name)))},OX={command:`upload <file>`,description:`Upload a .snap to the Snap Store, optionally releasing it to channels (snapcraft upload).`,builder:t=>t.positional(`file`,{description:"The .snap that `gjsify ship --format snap` wrote.",type:`string`}).option(`release`,{description:`Release to these channels after the upload, e.g. edge or stable,candidate (repeatable).`,type:`string`,array:!0,default:[]}).epilog("Credentials come from $SNAPCRAFT_STORE_CREDENTIALS only (create one with `snapcraft export-login`); this command never reads or prints them."),handler:async t=>{let n=parseChannels(t.release),S=assertSnapFile(t.file===void 0?void 0:In(process.cwd(),t.file));assertSnapCredentials(process.env),await runSnapcraft(`upload`,snapUploadArgs(S,n))}},kX={command:`status <name>`,description:`Show the revisions and channels of a snap in the Snap Store (snapcraft status).`,builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`status`,snapStatusArgs(assertSnapNameForStore(`status`,t.name)))}}),jX,MX=__esmMin(()=>{AX(),jX={command:`snap <subcommand>`,description:`Snap Store helpers: register a name, upload a .snap, show channel status.`,builder:t=>t.command(DX.command,DX.description,DX.builder,DX.handler).command(OX.command,OX.description,OX.builder,OX.handler).command(kX.command,kX.description,kX.builder,kX.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())NX.has(S)||S.startsWith(`.`)||blueprintsUnder(zn(t,S),n);return n}var NX,PX,formatFor,FX,IX=__esmMin(()=>{_e(),af(),Xn(),vA(),TA(),NX=new Set([`node_modules`,`dist`,`lib`,`.git`]),PX=new Map,formatFor=t=>{let n=PX.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return PX.set(t,S),S},FX={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.`)}}}),LX,RX=__esmMin(()=>{IX(),LX={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(FX.command,FX.description,FX.builder,FX.handler).demandCommand(1).strict()}}),zX=__esmMin(()=>{yR(),xR(),wR(),OR(),GR(),JR(),rB(),aB(),sB(),_B(),AB(),YB(),QB(),nV(),aV(),nH(),BG(),qG(),EB(),$G(),nK(),cK(),hB(),pK(),YK(),eq(),cq(),bq(),Sq(),Tq(),Dq(),Nq(),zq(),qq(),Xq(),Qq(),eJ(),lJ(),dJ(),pJ(),bJ(),TJ(),DJ(),HJ(),KJ(),YJ(),QJ(),eY(),nY(),iY(),CX(),MX(),RX()}),BX=__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=ch(t);await n.scriptName(wh).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(JB.command,JB.description,JB.builder,JB.handler).command(ZG.command,ZG.description,ZG.builder,ZG.handler).command(eK.command,eK.description,eK.builder,eK.handler).command(tK.command,tK.description,tK.builder,tK.handler).command(vR.command,vR.description,vR.builder,vR.handler).command(bR.command,bR.description,bR.builder,bR.handler).command(CR.command,CR.description,CR.builder,CR.handler).command(DR.command,DR.description,DR.builder,DR.handler).command(WR.command,WR.description,WR.builder,WR.handler).command(qR.command,qR.description,qR.builder,qR.handler).command(nB.command,nB.description,nB.builder,nB.handler).command(TB.command,TB.description,TB.builder,TB.handler).command(iB.command,iB.description,iB.builder,iB.handler).command(oB.command,oB.description,oB.builder,oB.handler).command(gB.command,gB.description,gB.builder,gB.handler).command(kB.command,kB.description,kB.builder,kB.handler).command(ZB.command,ZB.description,ZB.builder,ZB.handler).command(tV.command,tV.description,tV.builder,tV.handler).command(iV.command,iV.description,iV.builder,iV.handler).command(tH.command,tH.description,tH.builder,tH.handler).command(RG.command,RG.description,RG.builder,RG.handler).command(KG.command,KG.description,KG.builder,KG.handler).command(sK.command,sK.description,sK.builder,sK.handler).command(mB.command,mB.description,mB.builder,mB.handler).command(uK.command,uK.description,uK.builder,uK.handler).command(JK.command,JK.description,JK.builder,JK.handler).command(xq.command,xq.description,xq.builder,xq.handler).command($K.command,$K.description,$K.builder,$K.handler).command(sq.command,sq.description,sq.builder,sq.handler).command(yq.command,yq.description,yq.builder,yq.handler).command(wq.command,wq.description,wq.builder,wq.handler).command(Eq.command,Eq.description,Eq.builder,Eq.handler).command(Mq.command,Mq.description,Mq.builder,Mq.handler).command(Rq.command,Rq.description,Rq.builder,Rq.handler).command(Gq.command,Gq.description,Gq.builder,Gq.handler).command(Yq.command,Yq.description,Yq.builder,Yq.handler).command($q.command,$q.description,$q.builder,$q.handler).command(Zq.command,Zq.description,Zq.builder,Zq.handler).command(gJ.command,gJ.description,gJ.builder,gJ.handler).command(cJ.command,cJ.description,cJ.builder,cJ.handler).command(uJ.command,uJ.description,uJ.builder,uJ.handler).command(fJ.command,fJ.description,fJ.builder,fJ.handler).command(wJ.command,wJ.description,wJ.builder,wJ.handler).command(EJ.command,EJ.description,EJ.builder,EJ.handler).command(BJ.command,BJ.description,BJ.builder,BJ.handler).command(GJ.command,GJ.description,GJ.builder,GJ.handler).command(JJ.command,JJ.description,JJ.builder,JJ.handler).command(ZJ.command,ZJ.description,ZJ.builder,ZJ.handler).command($J.command,$J.description,$J.builder,$J.handler).command(tY.command,tY.description,tY.builder,tY.handler).command(rY.command,rY.description,rY.builder,rY.handler).command(SX.command,SX.description,SX.builder,SX.handler).command(jX.command,jX.description,jX.builder,jX.handler).command(LX.command,LX.description,LX.builder,LX.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var VX=__esmMin(()=>{lh(),uh(),Ch(),zX(),Th(),P_(),$z()});VX(),P_(),tB();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(),P_();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 HX=globalThis.process,UX=Number(HX?.exitCode);Number.isInteger(UX)&&UX!==0&&HX.exit(UX);
|
|
1954
|
+
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: ${kY[t].label} is not implemented — ${n}`),this.store=t,this.name=`StoreUnsupportedError`}},StoreVersionAlreadyThereError=class extends Error{store;version;constructor(t,n){super(`${kY[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(`${kY[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(`${kY[t].label}: ${n===void 0?`request failed`:`HTTP ${n}`} — ${S}`),this.store=t,this.httpStatus=n,this.name=`StoreApiError`}},MY={chrome:createChromeBackend,edge:createEdgeBackend,amo:createAmoBackend}});function pollBackoffFor(t){return stepFrom(IY,t)}function retryBackoffFor(t,n){return stepFrom(n?RY:LY,t)}function isRepeatableFailure(t){if(!(t instanceof StoreApiError))return!1;let n=t.httpStatus;return n===void 0||BY.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:PY[t],detail:clean(n),phases:q,elapsedMs:N()-W,requests:Y,retries:X,retryable:FY.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`&¬e(`${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<zY&&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 PY,FY,IY,LY,RY,zY,stepFrom,BY,VY=__esmMin(()=>{NY(),PY={uploaded:0,submitted:0,published:0,"already-there":0,"in-review":0,rejected:1,failed:1,unresolved:3,unverifiable:4},FY=[`in-review`,`failed`,`unresolved`],IY=[2e3,4e3,8e3,15e3,3e4],LY=[1e3,2e3,4e3],RY=[5e3,15e3,3e4],zY=1,stepFrom=(t,n)=>t[Math.min(Math.max(n,0),t.length-1)]??t[t.length-1]??0,BY=[408,429]});function isTagRef(t){return t!==void 0&&t.startsWith(`refs/tags/`)&&t.length>10}function defaultZipPath(t,n){let S=n===`amo`?`firefox`:n,C=t.targets.find(t=>t.browser===S);if(C===void 0)throw Error(`gjsify webext submit: gjsify.webext.targets has no ${S} target, so there is no zip to derive. Add ${S}-mv3 or pass --zip.`);return zn(t.outDir,`${t.name}-${t.version}-${C.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 findReviewerNotes(t,n){let S=zn(t,n);if(!existsSync(S))return;let C=readdirSync(S).filter(t=>statSync(zn(S,t)).isDirectory()).sort();for(let t of[`en`,...C.filter(t=>t!==`en`)]){if(!C.includes(t))continue;let n=readText(zn(S,t),`reviewer-notes.txt`);if(n!==void 0&&n!==``)return{text:n,path:zn(S,t,`reviewer-notes.txt`)}}}function secretsOf(t,n){return OY[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=kY[C];if(!F.implemented)throw new StoreUnsupportedError(C,`no backend is registered for it`);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 (AMO: validated, no version created).`);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}if(t.listingOnly){if(C!==`amo`)throw Error(`gjsify webext submit: --listing-only applies to AMO only; Chrome and Edge have no listing API.`);if(t.submit||t.zip!==void 0||t.sourceZip!==void 0)throw Error(`gjsify webext submit: --listing-only sends texts only; drop --submit, --zip and --source.`);let N=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0;return await runListingUpload({listingRoot:In(S.root,t.listingDir??`dist/listing`),dryRun:t.dryRun,notesVersion:t.notesVersion,backend:()=>(t.createBackend??createStoreBackend)(C,n,{fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:N}),out})}if(t.notesVersion!==void 0)throw Error(`gjsify webext submit: --notes-version belongs to --listing-only.`);let H=HY[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(`
|
|
1955
|
+
`)}`);q.manual.length>0&&out(` by hand in the dashboard: ${q.manual.join(`, `)}`);let Y=In(t.zip??defaultZipPath(S,C)),X=t.sourceZip===void 0?void 0:In(t.sourceZip);if(X!==void 0&&C!==`amo`)throw Error(`gjsify webext submit: --source applies to AMO only; Chrome and Edge take no source archive.`);if(X!==void 0&&!t.submit)throw Error(`gjsify webext submit: --source is attached to the version, which only --submit creates; add --submit or drop --source.`);if(X!==void 0&&!t.dryRun&&!existsSync(X))throw Error(`gjsify webext submit: the source archive ${X} does not exist.`);if(!t.dryRun&&!existsSync(Y))throw Error(`gjsify webext submit: ${Y} does not exist. Run \`gjsify webext zip\` first or pass --zip.`);let Z=C===`edge`||C===`amo`?findReviewerNotes(In(S.root,t.listingDir??`dist/listing`),H):void 0;Z===void 0&&C===`edge`&&t.submit&&err("warning: no reviewer-notes.txt under the listing dir; Edge reviewers expect certification notes. Run `gjsify webext listing --store edge` first. Continuing without notes.");let te=n.GJSIFY_WEBEXT_DEBUG?t=>err(t):void 0,ne={fetchImpl:t.fetchImpl,sleep:t.sleep,now:t.now,log:te},re=(t.createBackend??createStoreBackend)(C,n,ne);if(t.dryRun)return re.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.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0):(await re.verifyCredentials(),out(`${F.label}: dry run — credentials accepted (one read). ${existsSync(Y)?`The zip exists`:`No zip at ${Y} yet`}. Nothing was uploaded.`),t.submit&&Z!==void 0&&out(` would send reviewer notes from ${Z.path}: ${Z.text.length} chars`),0);let ie=await driveSubmission({backend:re,upload:{zipPath:Y,version:S.version},publish:t.submit?{version:S.version,sourceZip:X,notes:Z?.text}:void 0},{timeoutMs:I,sleep:t.sleep,now:t.now,log:te,secrets:N}),ae=ie.exitCode===0?out:err;for(let t of describeResult(ie,F.label))ae(t);return PY[ie.verdict]}catch(t){return err(t instanceof Error?t.message:String(t)),1}}var HY,UY=__esmMin(()=>{af(),Xn(),cY(),NY(),sY(),VY(),HY={chrome:`cws`,edge:`edge`,amo:`amo`}});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 WY=__esmMin(()=>{af(),Xn(),wH()});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(()=>(mR(),dR)),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}-${++GY}.mjs`);copyFileSync(C,N),n=pathToFileURL(N).href,cleanup=()=>rmSync(N,{force:!0})}else n=`${pathToFileURL(t).href}?t=${statSync(t).mtimeMs}-${++GY}`;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 GY,KY=__esmMin(()=>{af(),Xn(),cr(),P_(),__name$1(isRecord$1,`isRecord`),GY=0});function planPage(t,n,S){let C=Hn(n),N=[],F=[],local=t=>{if($Y.test(t)||t.startsWith(`/`))return null;let n=t.replace(/[?#].*$/,``);return Rn(n)?n:In(C,n)},I=S.replace(qY,n=>{let S=YY.exec(n);if(!S)return n;let C=local(S[2]);if(C===null||!eX.test(C))return n;let F=N.length===0?`${t}.js`:`${t}-${N.length+1}.js`;return N.push({entry:C,format:ZY.test(n)?`esm`:`iife`,output:F}),n.replace(YY,(t,n)=>`src=${n}${F}${n}`)});return I=I.replace(JY,t=>{if(!QY.test(t))return t;let n=XY.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(XY,(t,n)=>`href=${n}${C}${n}`)}),{html:I,scripts:N,stylesheets:F}}var qY,JY,YY,XY,ZY,QY,$Y,eX,tX=__esmMin(()=>{Xn(),qY=/<script\b[^>]*\bsrc\s*=\s*["'][^"']+["'][^>]*>/gi,JY=/<link\b[^>]*>/gi,YY=/\bsrc\s*=\s*(["'])([^"']+)\1/i,XY=/\bhref\s*=\s*(["'])([^"']+)\1/i,ZY=/\btype\s*=\s*["']module["']/i,QY=/\brel\s*=\s*["'][^"']*\bstylesheet\b[^"']*["']/i,$Y=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,eX=/\.(?:[cm]?[jt]sx?)$/i});function zipTimestamp(t=process.env){let n=Number(t.SOURCE_DATE_EPOCH);return Number.isFinite(n)&&n>=nX?n:nX}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(`
|
|
1956
|
+
- `)}`);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 nX,rX=__esmMin(()=>{_e(),af(),Xn(),fG(),WY(),KY(),tX(),nX=315532800});function parseWebextTarget(t){let n=/^([a-z]+)-mv([23])$/.exec(t),S=n?.[1];if(!n||S===void 0||!iX.includes(S))throw Error(`gjsify webext: unknown target "${t}". A target is <browser>-mv<2|3> with browser one of ${iX.join(`, `)} (e.g. chrome-mv3, firefox-mv2).`);let C=n[2]===`2`?2:3,N=C===2?oX.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 iX,aX,oX,sX=__esmMin(()=>{iX=[`chrome`,`edge`,`firefox`,`opera`,`safari`],aX=[`chrome-mv3`,`firefox-mv3`],oX=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??[...aX];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=lX.find(t=>S(zn(n,t),`file`));t===void 0?C.push(`no \`manifest\` declared and none of ${lX.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(!uX.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??cX;(!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(!uX.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(`
|
|
1957
|
+
- `)}`);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??[...aX],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(`
|
|
1958
|
+
- `)}`);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 cX,lX,uX,dX=__esmMin(()=>{af(),Xn(),sX(),cX=[16,32,48,128],lX=[`manifest.ts`,`manifest.mts`,`manifest.js`,`manifest.mjs`,`manifest.json`],uX=/^[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 fX,pX=__esmMin(()=>{af(),o_(),Xn(),dL(),sX(),fX="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(()=>(HX(),VX)),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 mX,hX,gX,_X,vX,yX,bX,xX,SX=__esmMin(()=>{_e(),af(),Xn(),JJ(),UY(),rX(),dX(),pX(),mX={description:`Build only these targets (default: every target in gjsify.webext.targets).`,type:`string`,array:!0},hX={description:`Output directory (default: gjsify.webext.outDir, else .output).`,type:`string`},gX={description:`Compile-time constant for every bundle, KEY=VALUE (repeatable); wins over gjsify.webext.define.`,type:`string`,array:!0,default:[]},_X={command:`build`,description:`Build one extension folder per target: bundles, pages, icons, locales and the manifest.`,builder:t=>t.option(`target`,mX).option(`out-dir`,hX).option(`define`,gX).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)},vX={command:`zip`,description:`Production build, then one store-ready <name>-<version>-<target>.zip per target.`,builder:t=>t.option(`target`,mX).option(`out-dir`,hX).option(`define`,gX),handler:t=>runBuild(t,!0)},yX={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`,{...mX,description:`The target to run (default: the first Firefox target).`}).option(`out-dir`,{description:`Output directory (default: <outDir>-dev).`,type:`string`}).option(`define`,gX).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(fX);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(()=>(GJ(),WJ));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(()=>(GJ(),WJ));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})}},bX={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})}},xX={command:`submit`,description:`Upload the built zip to the Chrome Web Store, Edge Add-ons or Firefox AMO; --submit also asks for review (tags only).`,builder:t=>t.option(`store`,{description:`Which store (amo = addons.mozilla.org, an existing listed add-on).`,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(`source`,{description:`AMO only: source archive for reviewers (needed when the zip is bundled or minified); attached with --submit.`,type:`string`}).option(`listing-only`,{description:`AMO only: send description and privacy policy from --listing-dir (not the zip), then read each back. With --dry-run: lengths only, no network.`,type:`boolean`,default:!1}).option(`notes-version`,{description:`With --listing-only: also send the reviewer notes (approval_notes) to this version id or number.`,type:`string`}).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. AMO: without --submit the zip is only uploaded and validated (no version, no review); --submit creates the version, which enters review at once. 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,sourceZip:t.source?In(n,t.source):void 0,listingOnly:t.listingOnly,notesVersion:t.notesVersion,project:loadSubmitProject(n),env:process.env,out:t=>ge.log(t),err:t=>ge.error(t)});S!==0&&(process.exitCode=S)}}}),CX,wX=__esmMin(()=>{SX(),CX={command:`webext <subcommand>`,description:`Browser extensions: build, zip and develop one WebExtension for Chrome, Edge, Firefox, Opera and Safari.`,builder:t=>t.command(_X.command,_X.description,_X.builder,_X.handler).command(vX.command,vX.description,vX.builder,vX.handler).command(yX.command,yX.description,yX.builder,yX.handler).command(bX.command,bX.description,bX.builder,bX.handler).command(xX.command,xX.description,xX.builder,xX.handler).demandCommand(1).strict()}});function snapRegisterArgs(t){return[`register`,t]}function snapStatusArgs(t){return[`status`,t]}function snapUploadArgs(t,n){let S=[`upload`];return n.length>0&&S.push(`--release=${n.join(`,`)}`),S.push(t),S}function parseChannels(t){let n=t.flatMap(t=>t.split(`,`)).map(t=>t.trim()).filter(t=>t!==``);for(let t of n)if(!EX.test(t))throw Error(`gjsify snap upload: "${t}" is not a channel (e.g. stable, latest/edge).`);return n}function assertSnapNameForStore(t,n){if(n===void 0||n===``)throw Error(`gjsify snap ${t}: pass the snap name (the store name, e.g. hello-app).`);if(!isSnapName(n))throw Error(`gjsify snap ${t}: "${n}" is not a snap name (lowercase letters, digits, single hyphens).`);return n}function assertSnapCredentials(t){if(t.SNAPCRAFT_STORE_CREDENTIALS===void 0||t.SNAPCRAFT_STORE_CREDENTIALS===``)throw Error(`gjsify snap upload: ${TX} is not set. Create one with \`${TW} export-login --snaps=<name> --acls=package_access,package_push,package_release -\` and pass it through the environment (a CI secret); it is never read from a file.`)}function assertSnapFile(t){if(t===void 0||t===``)throw Error(`gjsify snap upload: pass the .snap file.`);if(!t.endsWith(`.snap`))throw Error(`gjsify snap upload: "${t}" is not a .snap file.`);if(!existsSync(t)||!statSync(t).isFile())throw Error(`gjsify snap upload: no such file: ${t}.`);return t}async function runSnapcraft(t,n){let S=await spawnToCompletion(TW,n,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify snap ${t}: ${TW} not found. Install it with \`sudo snap install snapcraft --classic\`.`)});if(S.code!==0)throw Error(`gjsify snap ${t}: ${TW} failed with ${describeExit(S)}.`)}var TX,EX,DX=__esmMin(()=>{af(),IW(),hv(),TX=`SNAPCRAFT_STORE_CREDENTIALS`,EX=/^[a-z0-9][a-z0-9._-]*(\/[a-z0-9][a-z0-9._-]*){0,2}$/}),OX,kX,AX,jX=__esmMin(()=>{Xn(),DX(),OX={command:`register <name>`,description:"Claim a snap name in the Snap Store (snapcraft register). Needs an interactive `snapcraft login`.",builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`register`,snapRegisterArgs(assertSnapNameForStore(`register`,t.name)))},kX={command:`upload <file>`,description:`Upload a .snap to the Snap Store, optionally releasing it to channels (snapcraft upload).`,builder:t=>t.positional(`file`,{description:"The .snap that `gjsify ship --format snap` wrote.",type:`string`}).option(`release`,{description:`Release to these channels after the upload, e.g. edge or stable,candidate (repeatable).`,type:`string`,array:!0,default:[]}).epilog("Credentials come from $SNAPCRAFT_STORE_CREDENTIALS only (create one with `snapcraft export-login`); this command never reads or prints them."),handler:async t=>{let n=parseChannels(t.release),S=assertSnapFile(t.file===void 0?void 0:In(process.cwd(),t.file));assertSnapCredentials(process.env),await runSnapcraft(`upload`,snapUploadArgs(S,n))}},AX={command:`status <name>`,description:`Show the revisions and channels of a snap in the Snap Store (snapcraft status).`,builder:t=>t.positional(`name`,{description:`The store name.`,type:`string`}),handler:t=>runSnapcraft(`status`,snapStatusArgs(assertSnapNameForStore(`status`,t.name)))}}),MX,NX=__esmMin(()=>{jX(),MX={command:`snap <subcommand>`,description:`Snap Store helpers: register a name, upload a .snap, show channel status.`,builder:t=>t.command(OX.command,OX.description,OX.builder,OX.handler).command(kX.command,kX.description,kX.builder,kX.handler).command(AX.command,AX.description,AX.builder,AX.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())PX.has(S)||S.startsWith(`.`)||blueprintsUnder(zn(t,S),n);return n}var PX,FX,formatFor,IX,LX=__esmMin(()=>{_e(),af(),Xn(),vA(),TA(),PX=new Set([`node_modules`,`dist`,`lib`,`.git`]),FX=new Map,formatFor=t=>{let n=FX.get(t);if(n!==void 0)return n;let S=emitFormatForTree(t);return FX.set(t,S),S},IX={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.`)}}}),RX,zX=__esmMin(()=>{LX(),RX={command:`blueprint <subcommand>`,description:`Blueprint (.blp) tooling: generate the TypeScript type sidecars a .blp exports (ADR 0088).`,builder:t=>t.command(IX.command,IX.description,IX.builder,IX.handler).demandCommand(1).strict()}}),BX=__esmMin(()=>{yR(),xR(),wR(),OR(),GR(),JR(),rB(),aB(),sB(),_B(),AB(),YB(),QB(),nV(),aV(),nH(),VG(),JG(),EB(),eK(),rK(),lK(),hB(),mK(),XK(),tq(),lq(),xq(),Cq(),Eq(),Oq(),Pq(),Bq(),Jq(),Zq(),$q(),tJ(),uJ(),fJ(),mJ(),xJ(),EJ(),OJ(),UJ(),qJ(),XJ(),$J(),tY(),rY(),aY(),wX(),NX(),zX()}),VX=__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=ch(t);await n.scriptName(wh).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(JB.command,JB.description,JB.builder,JB.handler).command(QG.command,QG.description,QG.builder,QG.handler).command(tK.command,tK.description,tK.builder,tK.handler).command(nK.command,nK.description,nK.builder,nK.handler).command(vR.command,vR.description,vR.builder,vR.handler).command(bR.command,bR.description,bR.builder,bR.handler).command(CR.command,CR.description,CR.builder,CR.handler).command(DR.command,DR.description,DR.builder,DR.handler).command(WR.command,WR.description,WR.builder,WR.handler).command(qR.command,qR.description,qR.builder,qR.handler).command(nB.command,nB.description,nB.builder,nB.handler).command(TB.command,TB.description,TB.builder,TB.handler).command(iB.command,iB.description,iB.builder,iB.handler).command(oB.command,oB.description,oB.builder,oB.handler).command(gB.command,gB.description,gB.builder,gB.handler).command(kB.command,kB.description,kB.builder,kB.handler).command(ZB.command,ZB.description,ZB.builder,ZB.handler).command(tV.command,tV.description,tV.builder,tV.handler).command(iV.command,iV.description,iV.builder,iV.handler).command(tH.command,tH.description,tH.builder,tH.handler).command(zG.command,zG.description,zG.builder,zG.handler).command(qG.command,qG.description,qG.builder,qG.handler).command(cK.command,cK.description,cK.builder,cK.handler).command(mB.command,mB.description,mB.builder,mB.handler).command(dK.command,dK.description,dK.builder,dK.handler).command(YK.command,YK.description,YK.builder,YK.handler).command(Sq.command,Sq.description,Sq.builder,Sq.handler).command(eq.command,eq.description,eq.builder,eq.handler).command(cq.command,cq.description,cq.builder,cq.handler).command(bq.command,bq.description,bq.builder,bq.handler).command(Tq.command,Tq.description,Tq.builder,Tq.handler).command(Dq.command,Dq.description,Dq.builder,Dq.handler).command(Nq.command,Nq.description,Nq.builder,Nq.handler).command(zq.command,zq.description,zq.builder,zq.handler).command(Kq.command,Kq.description,Kq.builder,Kq.handler).command(Xq.command,Xq.description,Xq.builder,Xq.handler).command(eJ.command,eJ.description,eJ.builder,eJ.handler).command(Qq.command,Qq.description,Qq.builder,Qq.handler).command(_J.command,_J.description,_J.builder,_J.handler).command(lJ.command,lJ.description,lJ.builder,lJ.handler).command(dJ.command,dJ.description,dJ.builder,dJ.handler).command(pJ.command,pJ.description,pJ.builder,pJ.handler).command(TJ.command,TJ.description,TJ.builder,TJ.handler).command(DJ.command,DJ.description,DJ.builder,DJ.handler).command(VJ.command,VJ.description,VJ.builder,VJ.handler).command(KJ.command,KJ.description,KJ.builder,KJ.handler).command(YJ.command,YJ.description,YJ.builder,YJ.handler).command(QJ.command,QJ.description,QJ.builder,QJ.handler).command(eY.command,eY.description,eY.builder,eY.handler).command(nY.command,nY.description,nY.builder,nY.handler).command(iY.command,iY.description,iY.builder,iY.handler).command(CX.command,CX.description,CX.builder,CX.handler).command(MX.command,MX.description,MX.builder,MX.handler).command(RX.command,RX.description,RX.builder,RX.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var HX=__esmMin(()=>{lh(),uh(),Ch(),BX(),Th(),P_(),$z()});HX(),P_(),tB();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(),P_();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 UX=globalThis.process,WX=Number(UX?.exitCode);Number.isInteger(WX)&&WX!==0&&UX.exit(WX);
|