@gjsify/cli 0.9.0 → 0.10.0
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 +3 -3
- package/lib/cli-app.js +6 -0
- package/lib/commands/foreach.js +6 -0
- package/lib/commands/run.js +9 -0
- package/lib/commands/workspace.js +7 -0
- package/lib/utils/gjsify-shim.d.ts +6 -0
- package/lib/utils/gjsify-shim.js +52 -0
- package/package.json +17 -17
package/dist/cli.gjs.mjs
CHANGED
|
@@ -738,7 +738,7 @@ var S=Object.getOwnPropertySymbols,C=Object.prototype.hasOwnProperty,N=Object.pr
|
|
|
738
738
|
`),H=new Set;return{input:F,plugin:{name:`gjsify-virtual-entry`,async resolveId(n,a){return n.startsWith(N)?n:H.has(n)?{id:n,moduleSideEffects:`no-treeshake`}:null},async load(n){if(!n.startsWith(N))return null;let a=C.get(n);if(!a)return null;let F=(await this.resolve(a,void 0,{skipSelf:!0}))?.id??a;if(H.add(F),S.preserveDefaultExport){let n=`__gjsify_entry__`;return{code:`${I}\nimport * as ${n} from ${JSON.stringify(F)};\nexport * from ${JSON.stringify(F)};\nexport default ${n}.default;\n`,moduleSideEffects:`no-treeshake`}}return{code:`${I}\nimport ${JSON.stringify(F)};\nexport * from ${JSON.stringify(F)};\n`,moduleSideEffects:`no-treeshake`}}}}}function flattenAliases$4(n){let a={};for(let[S,C]of Object.entries(n))C&&(a[S]=C);return a}function createGjsExternalsPredicate(n=[]){let a=[`cairo`,`gettext`,`system`,...n];return n=>isRegisterSubpath(n)?!1:!!(n.startsWith(`gi://`)||a.includes(n))}function isRegisterSubpath(n){return!!(/\/register(?:\/[^?]*)?$/.test(n)||/[/\\]register(?:[/\\][^/\\]+)?\.(?:[mc]?js|ts)$/.test(n))}var dA,setupForGjs,fA=__esmMin(()=>{mn(),ps(),qb(),Jb(),$S(),Dk(),l_(),Nv(),Nk(),zk(),oA(),uA(),dA=as(fileURLToPath(import.meta.url)),setupForGjs=async n=>{let a=n.userExternal??[],S=[`cairo`,`gettext`,`system`,...a.filter(n=>!isRegisterSubpath(n))],C=createGjsExternalsPredicate(a),N=n.pluginOptions.format??`esm`,F=n.pluginOptions.exclude??[],I=await globToEntryPoints(n.input,F),H=resolveShim(`unicorn-magic`),W={...getAliasesForGjs({external:C}),"unicorn-magic":H,...n.pluginOptions.aliases,...n.userAliases},K=n.pluginOptions.consoleShim===!1?null:resolveShim(`console-gjs`),q=[];n.pluginOptions.autoGlobalsInject&&q.push(n.pluginOptions.autoGlobalsInject);let Y=wrapInputWithSideEffects(I,q,{preserveDefaultExport:n.pluginOptions.preserveDefaultExport===!0}),X={input:Y.input,platform:`neutral`,external:S,resolve:{mainFields:N===`esm`?[`browser`,`module`,`main`]:[`browser`,`main`,`module`],conditionNames:N===`esm`?[`browser`,`import`]:[`browser`,`require`,`import`]},transform:{target:`firefox140`,define:{global:`globalThis`,window:`globalThis`,"process.env.READABLE_STREAM":`"disable"`},...K?{inject:{console:[K,`console`]}}:{}},output:{...n.output,format:N,sourcemap:!1,codeSplitting:!1},treeshake:!0},te=getBundleDirFromOutput(n.output);return{options:X,plugins:[...Y.plugin?[Y.plugin]:[],inputShebangStripPlugin(),aliasPlugin({entries:{"random-access-file":`random-access-file/index.js`,...flattenAliases$4(W)}}),externalsPlugin(C,{name:`gjsify-gjs-externalize`}),blueprintPlugin(),deepkitPlugin({reflection:n.pluginOptions.reflection}),cssAsStringPlugin({targets:{firefox:60<<16}}),nodeModulesPathRewritePlugin({bundleDir:te,runtimeResolve:N===`esm`}),processStubPlugin({userBanner:n.userBanner,captureBundleUrl:N===`esm`}),(()=>{let a=resolveShebangLine(n.shebang);return shebangPlugin({enabled:a!==null,line:a??void 0})})()]}},__name$1(flattenAliases$4,`flattenAliases`)});function gjsImportsEmptyPlugin(){return{name:`gjsify-gjs-imports-empty`,resolveId:{order:`pre`,filter:{id:/^(@girs\/|gi:\/\/)/},handler(n){return/^(@girs\/|gi:\/\/)/.test(n)?{id:pA}:null}},load(n){return n===pA?{code:`export {}; export default {};`,moduleSideEffects:!1}:null}}}var pA,mA=__esmMin(()=>{pA=`\0gjsify-empty-gjs-import`});function flattenAliases$3(n){let a={};for(let[S,C]of Object.entries(n))C&&(a[S]=C);return a}var setupForNode,hA=__esmMin(()=>{qb(),$S(),c_(),l_(),Nv(),Nk(),oA(),mA(),setupForNode=async n=>{let a=n.userExternal??[],S=[...Qg,`node-datachannel`,...a],external=n=>!!S.includes(n),C=n.pluginOptions.format??`esm`,N=n.pluginOptions.exclude??[],F=await globToEntryPoints(n.input,N),I={...getAliasesForNode({external}),...n.pluginOptions.aliases,...n.userAliases},H=getBundleDirFromOutput(n.output);return{options:{input:F,platform:`node`,external:S,resolve:{mainFields:C===`esm`?[`module`,`main`,`browser`]:[`main`,`module`,`browser`],conditionNames:C===`esm`?[`require`,`node`,`module`]:[`require`]},transform:{target:`node24`,define:{global:`globalThis`,window:`globalThis`}},output:{...n.output,format:C,sourcemap:!1,banner:void 0,codeSplitting:!1},treeshake:!0},plugins:[gjsImportsEmptyPlugin(),aliasPlugin({entries:flattenAliases$3(I)}),deepkitPlugin({reflection:n.pluginOptions.reflection}),cssAsStringPlugin(),nodeModulesPathRewritePlugin({bundleDir:H})]}},__name$1(flattenAliases$3,`flattenAliases`)});function flattenAliases$2(n){let a={};for(let[S,C]of Object.entries(n))C&&(a[S]=C);return a}var setupForBrowser,gA=__esmMin(()=>{qb(),$S(),Dk(),c_(),Nv(),mA(),oA(),setupForBrowser=async n=>{let a=[...n.userExternal??[]],S=n.pluginOptions.exclude??[],C=await globToEntryPoints(n.input,S),N={};for(let[n,a]of Object.entries(n_))N[n]=a,N[`node:${n}`]=a;let F={},I={...getDerivedAliasesSync(`browser`),...N,...F,...n.pluginOptions.aliases,...n.userAliases};return{options:{input:C,platform:`browser`,external:a,resolve:{mainFields:[`browser`,`module`,`main`],conditionNames:[`import`,`browser`]},transform:{target:`esnext`,define:{global:`globalThis`,window:`globalThis`}},output:{...n.output,format:`esm`,sourcemap:!1,codeSplitting:!1},treeshake:!0},plugins:[gjsImportsEmptyPlugin(),aliasPlugin({entries:flattenAliases$2(I)}),blueprintPlugin(),deepkitPlugin({reflection:n.pluginOptions.reflection}),cssAsStringPlugin()]}},__name$1(flattenAliases$2,`flattenAliases`)});function isPlatform(n){return _A.includes(n)}function platformResolvePlugin(n={}){let a=n.platform,S=a?[a,`native`]:[`native`];return{name:`gjsify-nativescript-platform-resolve`,resolveId:{order:`pre`,async handler(n,a,C){if(!a||!n.startsWith(`./`)&&!n.startsWith(`../`))return null;let N=vA.exec(n),F=N?N[0]:``,I=F?n.slice(0,-F.length):n;for(let N of S){let S=F&&`${I}.${N}`!=`${I}.${N}${F}`?[`${I}.${N}`,`${I}.${N}${F}`]:[`${I}.${N}`];for(let N of S){if(N===n)continue;let S=await this.resolve(N,a,{skipSelf:!0,...C?.kind?{kind:C.kind}:{}});if(S&&!S.external)return S}}return null}}}}function detectNativescriptPlatform(n=process.env){let a=n.NATIVESCRIPT_PLATFORM??n.NS_PLATFORM;if(a&&isPlatform(a))return a;let S=n.NATIVESCRIPT_BUNDLER_ENV??n.NATIVESCRIPT_WEBPACK_ENV;if(S)try{let n=JSON.parse(S);if(n.android===!0)return`android`;if(n.ios===!0)return`ios`;if(n.visionos===!0)return`visionos`;if(typeof n.platform==`string`&&isPlatform(n.platform))return n.platform}catch{}}function nativescriptPlatformDefines(n,a={}){let S=n===`android`,C=n===`ios`,N=n===`visionos`;return{__ANDROID__:String(S),__IOS__:String(C),__VISIONOS__:String(N),__APPLE__:String(C||N),__DEV__:String(a.dev??!1)}}var _A,vA,yA=__esmMin(()=>{_A=[`android`,`ios`,`visionos`],vA=/\.(tsx?|jsx?|mts|cts|mjs|cjs)$/});function flattenAliases$1(n){let a={};for(let[S,C]of Object.entries(n))C&&(a[S]=C);return a}var setupForNativescript,bA=__esmMin(()=>{qb(),$S(),c_(),Nv(),mA(),yA(),setupForNativescript=async n=>{let a=[...n.userExternal??[]],S=n.pluginOptions.exclude??[],C=await globToEntryPoints(n.input,S),N=detectNativescriptPlatform(),F={};for(let[n,a]of Object.entries(r_))F[n]=a,F[`node:${n}`]=a;let I={},H={...getDerivedAliasesSync(`nativescript`),...F,...I,...n.pluginOptions.aliases,...n.userAliases};return{options:{input:C,platform:`browser`,external:a,resolve:{mainFields:[`nativescript`,`module`,`main`],conditionNames:[`import`,`nativescript`]},transform:{target:`esnext`,define:{global:`globalThis`,...nativescriptPlatformDefines(N,{dev:!1})}},output:{...n.output,format:`esm`,sourcemap:!1,codeSplitting:!1},treeshake:!0},plugins:[gjsImportsEmptyPlugin(),platformResolvePlugin({platform:N}),aliasPlugin({entries:flattenAliases$1(H)}),deepkitPlugin({reflection:n.pluginOptions.reflection})]}},__name$1(flattenAliases$1,`flattenAliases`)}),xA=__esmMin(()=>{fA(),hA(),gA(),bA()});function isExternalSpecifier(n){return!(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`/`)||n.startsWith(`\0`)||n.startsWith(`data:`))}function computeCommonRoot(n){let a=n===void 0?[]:typeof n==`string`?[n]:Array.isArray(n)?n:Object.values(n);if(a.length===0)return`src`;let S=a.map(n=>n.split(`/`).filter(Boolean)),C=S[0],N=0;for(;N<C.length;N++){let n=C[N];if(!S.every(a=>a[N]===n))break}if(N===0)return`src`;let F=C.slice(0,N);return S.some(n=>n.length>N)?F.join(`/`):F.slice(0,-1).join(`/`)||`src`}function flattenAliases(n){let a={};for(let[S,C]of Object.entries(n))C&&(a[S]=C);return a}var setupLib,SA=__esmMin(()=>{qb(),oA(),Jb(),Nv(),setupLib=async n=>{let a=n.pluginOptions.format??n.pluginOptions.library??`esm`,S=n.pluginOptions.exclude??[],C=await globToEntryPoints(n.input,S),N=computeCommonRoot(C),F={...n.pluginOptions.aliases,...n.userAliases};return{options:{input:C,platform:`neutral`,resolve:{mainFields:a===`esm`?[`module`,`main`]:[`main`],conditionNames:a===`esm`?[`module`,`import`]:[`require`]},transform:{target:`esnext`},output:{...n.output,format:a,preserveModules:!0,preserveModulesRoot:N,sourcemap:!1},treeshake:!1},plugins:[aliasPlugin({entries:flattenAliases(F)}),externalsPlugin(isExternalSpecifier,{name:`gjsify-lib-externalize`}),cssAsStringPlugin()]}}}),CA=__esmMin(()=>{SA()});function mimeForExtension(n){return wA[n.toLowerCase()]??`application/octet-stream`}function textLoaderPlugin(n={}){let a=n.loaders??{},S=Object.entries(a),C=S.filter(([,n])=>n===`text`).map(([n])=>n),N=S.filter(([,n])=>n===`dataurl`).map(([n])=>n),F=[...C,...N];if(F.length===0)return null;let I=F.map(n=>n.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),H=RegExp(`\\.(?:${I.join(`|`)})$`),W=new Map(S.map(([n,a])=>[n.toLowerCase(),a]));return{name:`gjsify-asset-loader`,async load(n){if(!H.test(n))return null;let a=n.lastIndexOf(`.`),S=a>=0?n.slice(a).toLowerCase():``;if((W.get(S)??`text`)===`dataurl`){let a=await readFile$1(n),C=mimeForExtension(S),N=a.toString(`base64`);return{code:`export default ${JSON.stringify(`data:${C};base64,${N}`)};`,moduleType:`js`}}let C=await readFile$1(n,`utf8`);return{code:`export default ${JSON.stringify(C)};`,moduleType:`js`}}}}var wA,TA=__esmMin(()=>{kc(),wA={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`,".svg":`image/svg+xml`,".ico":`image/x-icon`,".avif":`image/avif`,".bmp":`image/bmp`,".tiff":`image/tiff`,".tif":`image/tiff`,".wasm":`application/wasm`}}),gjsifyPlugin,EA=__esmMin(()=>{xA(),CA(),gjsifyPlugin=async(n,a={})=>{if(a.library)switch(a.library){case`esm`:case`cjs`:return await setupLib({input:n.input,output:n.output,userAliases:n.userAliases,pluginOptions:a});default:throw TypeError(`Unknown library type: `+a.library)}let S=a.app??`gjs`;switch(S){case`gjs`:return await setupForGjs({input:n.input,output:n.output,userExternal:n.userExternal,userBanner:n.userBanner,userAliases:n.userAliases,shebang:n.shebang,pluginOptions:a});case`node`:return await setupForNode({input:n.input,output:n.output,userExternal:n.userExternal,userAliases:n.userAliases,pluginOptions:a});case`browser`:return await setupForBrowser({input:n.input,output:n.output,userExternal:n.userExternal,userAliases:n.userAliases,pluginOptions:a});case`nativescript`:return await setupForNativescript({input:n.input,output:n.output,userExternal:n.userExternal,userAliases:n.userAliases,pluginOptions:a});default:throw TypeError(`Unknown app platform: `+S)}}}),DA=__esmMin(()=>{Kg(),Kb(),xA(),CA(),Nk(),zk(),oA(),TA(),uA(),mA(),Jb(),yA(),EA(),EA(),c_()});function isPluginByName(n){return typeof n==`object`&&!!n&&typeof n.name==`string`&&!(`apply`in n)&&!(`resolveId`in n)&&!(`load`in n)&&!(`transform`in n)&&!(`renderChunk`in n)&&!(`generateBundle`in n)}async function resolveUserPlugins(n,a,S={}){let C=S.loadModule??defaultLoadModule,N=createRequire(ns(a,`package.json`)),F=[];for(let S of n){if(!isPluginByName(S)){F.push(S);continue}let n;try{n=N.resolve(S.name)}catch(n){throw Error(`gjsify config: failed to resolve plugin "${S.name}" from ${a}. Add it to your project's dependencies, or pass a Plugin object directly. (${n.message})`)}let I=await C(n,S.name),H=S.export??`default`,W=I[H];if(typeof W!=`function`){let n=Object.keys(I).filter(n=>typeof I[n]==`function`);throw Error(`gjsify config: plugin "${S.name}" has no function export "${H}". Available function exports: ${n.length?n.join(`, `):`(none)`}.`)}let K=await W(S.options);if(K==null)throw Error(`gjsify config: plugin "${S.name}" factory returned ${K}. Check the plugin's signature — it should return a Rolldown/Vite plugin object.`);F.push(K)}return F}var defaultLoadModule,OA=__esmMin(()=>{Uo(),ps(),mn(),defaultLoadModule=async n=>await import(pathToFileURL(n).href)}),kA,AA=__esmMin(()=>{kA={"@gjsify/buffer/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/canvas":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/document":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/font-face":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/image":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`HTMLCanvasElement`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`document`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/location":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/match-media":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/navigator":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`navigator`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/dom-elements/register/observers":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/domparser/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/gamepad/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/buffer":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/encoding":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/microtask":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/process":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/structured-clone":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/timers":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/node-globals/register/url":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`URL`,`URLSearchParams`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/web-globals/register/formdata":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`FormData`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/web-globals/register/performance":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webaudio/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/data-channel":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`EventTarget`,`File`,`MessageEvent`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/error":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/media":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`EventTarget`,`File`,`MediaStream`,`MediaStreamTrack`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/media-devices":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`Event`,`EventTarget`,`File`,`MediaStream`,`MediaStreamTrack`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"@gjsify/webrtc/register/peer-connection":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CountQueuingStrategy.DOMException.Event.EventTarget.File.MediaStream.MediaStreamTrack.MessageEvent.RTCSessionDescription.ReadableStream.TextDecoderStream.TextEncoderStream.TransformStream.WritableStream.atob.btoa.clearTimeout.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"abort-controller/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"compression-streams/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CompressionStream`,`CountQueuingStrategy`,`DOMException`,`DecompressionStream`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/custom-events":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/event-target":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-events/register/ui-events":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"dom-exception/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"eventsource/register":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CompressionStream.CountQueuingStrategy.DOMException.DecompressionStream.Event.EventSource.EventTarget.File.Headers.MessageEvent.ReadableStream.Request.Response.TextDecoderStream.TextEncoderStream.TransformStream.URL.URLSearchParams.WritableStream.atob.btoa.clearTimeout.fetch.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"fetch/register/fetch":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CompressionStream.CountQueuingStrategy.DOMException.DecompressionStream.File.Headers.ReadableStream.Request.Response.TextDecoderStream.TextEncoderStream.TransformStream.URL.URLSearchParams.WritableStream.atob.btoa.clearTimeout.fetch.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"fetch/register/xhr":`AbortController.AbortSignal.Blob.Buffer.ByteLengthQueuingStrategy.CompressionStream.CountQueuingStrategy.DOMException.DecompressionStream.Event.EventTarget.File.Headers.ProgressEvent.ReadableStream.Request.Response.TextDecoderStream.TextEncoderStream.TransformStream.URL.URLSearchParams.WritableStream.XMLHttpRequest.XMLHttpRequestUpload.atob.btoa.clearTimeout.fetch.performance.process.queueMicrotask.setTimeout.structuredClone`.split(`.`),"message-channel/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`MessageChannel`,`MessagePort`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/queuing":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/readable":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/text-streams":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/transform":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"web-streams/register/writable":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"webassembly/register/promise":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WebAssembly`,`WritableStream`,`atob`,`btoa`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"webcrypto/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`crypto`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`],"websocket/register":[`AbortController`,`AbortSignal`,`Blob`,`Buffer`,`ByteLengthQueuingStrategy`,`CountQueuingStrategy`,`DOMException`,`File`,`ReadableStream`,`TextDecoderStream`,`TextEncoderStream`,`TransformStream`,`WritableStream`,`atob`,`btoa`,`clearTimeout`,`performance`,`process`,`queueMicrotask`,`setTimeout`,`structuredClone`]}});function expandWithClosure(n,a){let S=new Set(n),C=[...n];for(;C.length>0;){let n=jA[C.pop()];if(!n)continue;let N=MA[n];if(N)for(let n of N)a.has(n)||jA[n]&&(S.has(n)||(S.add(n),C.push(n)))}return S}function isSubset(n,a){for(let S of n)if(!a.has(S))return!1;return!0}async function applyExcludeGlobals(n,a,S,C,N){if(!C?.length)return{detected:n,injectPath:a};for(let a of C)n.delete(a);let F=detectedToRegisterPaths(n);for(let n of S)F.add(n);return N&&(F=filterResolvableRegisterPaths(F,N)),{detected:n,injectPath:F.size>0?await writeRegisterInjectFile(F,N)??void 0:void 0}}function detectedToRegisterPaths(n){let a=new Set;for(let S of n){let n=jA[S];n&&a.add(n)}return a}function isFullConfig(n){return typeof n==`object`&&!!n&&!Array.isArray(n)&&`plugins`in n&&`options`in n}async function detectAutoGlobals(n,a,S,C,N={},F=defaultBundler){let I=N.extraGlobalsList?resolveGlobalsList(N.extraGlobalsList):new Set,H=new Set(N.excludeGlobals??[]),W=N.cwd,K=new Set,q;I.size>0&&(q=await writeRegisterInjectFile(W?filterResolvableRegisterPaths(I,W):I,W)??void 0);let Y=(n.plugins??[]).filter(n=>{let a=n&&typeof n==`object`&&`name`in n?n.name:void 0;return a!==`gjsify`&&a!==`gjsify-orchestrator`});for(let X=1;X<=NA;X++){let te=await S({...a,autoGlobalsInject:q}),ne,re;isFullConfig(te)?(re=te.options,ne=te.plugins):ne=te;let ie=q?appendInjectAsEntry(n.input,q):n.input,ae=n.resolve??re?.resolve,oe=n.external??re?.external,Z=n.transform??re?.transform,se=re?.treeshake,ce=Array.isArray(ne)?ne:[ne],le=await F({rolldownInput:{input:ie,external:oe,resolve:ae,transform:Z,plugins:[...Y,...ce],logLevel:`silent`,...se===void 0?{}:{treeshake:se}},format:n.format??`esm`});if(le.length===0)return{detected:new Set,injectPath:q};let ue=new Set;for(let n=0;n<le.length;n++){let a=le[n]??``;try{for(let n of detectFreeGlobals(a))ue.add(n)}catch(S){if(globalThis.process?.env?.GJSIFY_DEBUG_AUTO_GLOBALS){let S=`/tmp/gjsify-auto-globals-failed-chunk-${n}.mjs`;try{(await Promise.resolve().then(()=>(Zc(),Jc))).writeFileSync(S,a),ke.error(`[gjsify-auto-globals] parse failed on chunk #${n} — wrote ${S} for inspection`)}catch{}}throw S}}if(H.size>0)for(let n of H)ue.delete(n);if(isSubset(ue,K)){if(C){let n=[...K].sort(),a=I.size>0?` (+ ${I.size} extra register module(s))`:``;ke.debug(`[gjsify] --globals auto: converged after ${X-1} iteration(s), ${K.size} global(s)${n.length?`: `+n.join(`, `):``}${a}`)}return applyExcludeGlobals(K,q,I,N.excludeGlobals,W)}let de=N.disableClosureExpansion?ue:expandWithClosure(ue,H);C&&de.size>ue.size&&ke.debug(`[gjsify] --globals auto: closure map expanded ${ue.size} → ${de.size} global(s)`),X>1&&C&&ke.debug("[gjsify] --globals auto: detection grew past the closure-map expansion — the committed register-globals-closure map looks stale. Regenerate via `node packages/infra/cli/scripts/generate-register-closure.mjs`."),K=new Set([...K,...de]);let fe=detectedToRegisterPaths(K);for(let n of I)fe.add(n);if(W&&(fe=filterResolvableRegisterPaths(fe,W)),fe.size===0)return{detected:K,injectPath:void 0};if(q=await writeRegisterInjectFile(fe,W)??void 0,C){let n=[...K].sort();ke.debug(`[gjsify] --globals auto: iteration ${X}, ${K.size} global(s)${n.length?`: `+n.join(`, `):``}`)}}return C&&ke.debug(`[gjsify] --globals auto: hit max iterations (${NA}), using last detected set`),applyExcludeGlobals(K,q,I,N.excludeGlobals,W)}function appendInjectAsEntry(n,a){return n===void 0?[a]:typeof n==`string`?[n,a]:Array.isArray(n)?[...n,a]:{...n,__gjsify_inject:a}}var defaultBundler,jA,MA,NA,PA=__esmMin(()=>{Ae(),zb(),Ub(),Pb(),AA(),defaultBundler=async({rolldownInput:n,format:a})=>{let S=await(await import(`rolldown`)).rolldown(n);try{let n=await S.generate({format:a,minify:!1,sourcemap:!1}),C=[];for(let a of n.output)a.type===`chunk`&&C.push(a.code);return C}finally{await S.close()}},jA=Nb,MA=kA,NA=5}),FA=__esmMin(()=>{Ub(),zb(),PA()});function findPnpRoot(n){let a=n;for(;;){if(existsSync(ns(a,`.pnp.cjs`)))return a;let n=as(a);if(n===a)return null;a=n}}async function loadPnpApi(){try{let n=await import(`pnpapi`);return n.default??n}catch{return null}}async function pnpPlugin(n={}){let a=n.issuerUrl??import.meta.url;if(!findPnpRoot(process.cwd()))return null;let S=await loadPnpApi();if(S===null)return null;let C=fileURLToPath(a),N=createRequire(C),F=n.relayPackages??[`@gjsify/node-polyfills`,`@gjsify/web-polyfills`],I=[];for(let n of F)try{I.push(N.resolve(`${n}/package.json`))}catch{}return{name:`gjsify-pnp`,resolveId:{order:`pre`,async handler(n,a){if(n.startsWith(`.`)||n.startsWith(`/`))return null;if(n.startsWith(`gi://`))return{id:n,external:!0};if(n.startsWith(`node:`))return await this.resolve(n,a,{skipSelf:!0});if(!a)return null;let N=a.startsWith(`file://`)?fileURLToPath(a):a;try{let a=S.resolveRequest(n,N);return a===null?null:{id:a}}catch(a){if(!isUndeclaredDependency(a))throw a;try{let a=S.resolveRequest(n,C);if(a!==null)return{id:a}}catch(n){if(!isUndeclaredDependency(n))throw n}for(let a of I)try{let C=S.resolveRequest(n,a);if(C!==null)return{id:C}}catch(n){if(!isUndeclaredDependency(n))throw n}return null}}},async load(n){if(!n.includes(`/.yarn/`)&&!n.includes(`.zip/`))return null;try{return{code:await readFile$1(n,`utf8`)}}catch(a){let S=a instanceof Error?a.message:String(a);this.error(`gjsify-pnp: failed to read ${n}: ${S}`)}}}}function isUndeclaredDependency(n){return typeof n==`object`&&!!n&&`pnpCode`in n&&n.pnpCode===`UNDECLARED_DEPENDENCY`}var IA=__esmMin(()=>{Uo(),mn(),ps(),Zc(),kc()});function normalizeBundlerOptions(n){let a=n.bundler??{},S=a;if(typeof a.define==`object`&&a.define!==null){RA||(RA=!0,ke.warn(`[gjsify] WARNING: 'bundler.define' is not a valid Rolldown option and would be silently ignored — it has been auto-mapped to 'bundler.transform.define'. Move 'define' under 'bundler.transform.define' in your config to suppress this warning and avoid a ReferenceError at GJS load time.`));let{define:n,...C}=a;S={...C,transform:{...C.transform,define:{...n,...C.transform?.define}}}}if(!n.esbuild)return S;LA||(LA=!0,ke.warn(`[gjsify] DEPRECATION: the 'esbuild' config key is deprecated and will be removed in 0.5.0. Rename it to 'bundler' (typed as RolldownOptions). See the migration notes in the gjsify CHANGELOG.`));let C=legacyEsbuildToRolldown(n.esbuild),N={...C,...S};return(C.output||S.output)&&(N.output={...C.output,...S.output}),(C.transform||S.transform)&&(N.transform={...C.transform,...S.transform},(C.transform?.define||S.transform?.define)&&(N.transform.define={...C.transform?.define,...S.transform?.define})),(C.resolve||S.resolve)&&(N.resolve={...C.resolve,...S.resolve}),N}function legacyEsbuildToRolldown(n){let a={},S={},C={},N={};return n.outfile!==void 0&&(S.file=n.outfile),n.outdir!==void 0&&(S.dir=n.outdir),n.format!==void 0&&(S.format=n.format),n.minify!==void 0&&(S.minify=n.minify),n.sourcemap!==void 0&&(S.sourcemap=n.sourcemap===`inline`?`inline`:!!n.sourcemap),n.banner?.js!==void 0&&(S.banner=n.banner.js),n.target!==void 0&&(C.target=Array.isArray(n.target)?n.target.join(`,`):n.target),n.define!==void 0&&(C.define=n.define),n.mainFields!==void 0&&(N.mainFields=n.mainFields),n.conditions!==void 0&&(N.conditionNames=n.conditions),n.external!==void 0&&(a.external=n.external),n.platform!==void 0&&(a.platform=n.platform),Object.keys(S).length>0&&(a.output=S),Object.keys(C).length>0&&(a.transform=C),Object.keys(N).length>0&&(a.resolve=N),a}function mergeBundlerOptions(n,a){let{input:S,external:C,...N}=a,F={...n,...N};return(n.output||a.output)&&(F.output={...n.output,...a.output}),(n.transform||a.transform)&&(F.transform={...n.transform,...a.transform},(n.transform?.define||a.transform?.define)&&(F.transform.define={...n.transform?.define,...a.transform?.define})),(n.resolve||a.resolve)&&(F.resolve={...n.resolve,...a.resolve}),F}var LA,RA,zA=__esmMin(()=>{Ae(),LA=!1,RA=!1});function isUnsafeDefaultOutput(n){if(/\.[cm]?tsx?$/i.test(n))return!0;let a=n.replace(/\\/g,`/`);return!!/(?:^|\/)src\//.test(a)}async function buildPnpPlugin(){return pnpPlugin({issuerUrl:import.meta.url})}function shortHash(n){let a=5381;for(let S=0;S<n.length;S++)a=(a<<5)+a+n.charCodeAt(S)>>>0;return a.toString(16).padStart(8,`0`)}function isTruthyEnv(n){return n===`1`||n===`true`||n===`yes`}async function newestLockfileMtime(n){let a=0;for(let S of VA)try{let C=await stat$1(ns(n,S));C.mtimeMs>a&&(a=C.mtimeMs)}catch{}return a}async function runOneLibraryBuild(n){let a=await gjsifyPlugin({input:n.userBundler.input,output:n.output,userAliases:n.userAliases},n.pluginOpts);return await runBundle({...mergeBundlerOptions(a.options,n.userBundler),plugins:[...n.pnpPlugins,...a.plugins]})}var BA,VA,HA,UA=__esmMin(()=>{Ae(),Hg(),DA(),zg(),OA(),FA(),IA(),ps(),mn(),kc(),zA(),BA=`#!/usr/bin/env -S gjs -m`,VA=[`gjsify-lock.json`,`package-lock.json`,`yarn.lock`,`pnpm-lock.yaml`],HA=class BuildAction{configData;constructor(n={}){this.configData=n}async buildLibrary(){let{verbose:n,library:a,typescript:S,exclude:C,aliases:N}=this.configData,F=a??{},I=normalizeBundlerOptions(this.configData),H=F.module?as(F.module):void 0,W=F.main?as(F.main):void 0,K=F.module?ss(F.module):`.js`,q=F.main?ss(F.main):`.js`,Y=H&&W&&H!==W,X=await buildPnpPlugin(),te=X?[X]:[],ne=[];if(Y){let a=H.includes(`/cjs`)||K===`.cjs`?`cjs`:`esm`;ne.push(await runOneLibraryBuild({pluginOpts:{debug:n,library:a,exclude:C,reflection:S?.reflection,jsExtension:K},userBundler:I,output:{dir:H},userAliases:N,pnpPlugins:te}));let F=W.includes(`/cjs`)||q===`.cjs`?`cjs`:`esm`;ne.push(await runOneLibraryBuild({pluginOpts:{debug:n,library:F,exclude:C,reflection:S?.reflection,jsExtension:q},userBundler:I,output:{dir:W},userAliases:N,pnpPlugins:te}))}else{let a=I.output?.file??F.module??F.main,H=a?ss(a):`.js`,W=I.output?.dir??(a?as(a):void 0),K=I.output?.format??(W?.includes(`/cjs`)||H===`.cjs`?`cjs`:`esm`);ne.push(await runOneLibraryBuild({pluginOpts:{debug:n,library:K,exclude:C,reflection:S?.reflection,jsExtension:H},userBundler:I,output:{dir:W},userAliases:N,pnpPlugins:te}))}return ne}parseGlobalsValue(n){if(n===void 0)return{autoMode:!0,extras:``};if(n===`none`||n===``)return{autoMode:!1,extras:``};let a=n.split(`,`).map(n=>n.trim()).filter(Boolean);return{autoMode:a.includes(`auto`),extras:a.filter(n=>n!==`auto`).join(`,`)}}async resolveGlobalsInject(n,a,S){if(n!==`gjs`||!a)return;let C=resolveGlobalsList(a);if(C.size===0)return;let N=await writeRegisterInjectFile(C,process.cwd());return S&&N&&ke.debug(`[gjsify] globals: injected ${C.size} register module(s) from --globals ${a}`),N??void 0}async applyShebang(n,a,S){if(!a){S&&ke.warn(`[gjsify] --shebang skipped: no single outfile (use --outfile for executables)`);return}let C=n===`node`?cA:BA,N=resolveShebangLine(this.configData.shebang,C)??C,F=await readFile$1(a,`utf-8`);F.startsWith(`#!`)?S&&ke.debug(`[gjsify] --shebang skipped: ${a} already starts with a shebang`):await writeFile$1(a,N+`
|
|
739
739
|
`+F),await chmod$1(a,493),S&&ke.debug(`[gjsify] --shebang: wrote ${N} + chmod 0o755 to ${a}`)}async loadPluginViaGjsBundle(n,a,S){let C=await this.bundlePluginForGjs(n,a,S);try{return await import(pathToFileURL(C).href)}catch(n){throw Error(`gjsify config: failed to import the GJS bundle for plugin "${a}" (bundled to ${C}). (${n.message})`)}}async bundlePluginForGjs(n,a,S){let C=process.cwd(),N=ns(C,`node_modules`,`.cache`,`gjsify`,`plugins`),F=ns(N,`${a.replace(/[^a-zA-Z0-9._-]/g,`_`)}-${shortHash(n)}.mjs`);if(!isTruthyEnv(process.env.GJSIFY_NO_PLUGIN_CACHE)&&await this.isPluginBundleFresh(F,n,C))return S&&ke.debug(`[gjsify] plugin "${a}": reusing cached GJS bundle ${F}`),F;S&&ke.debug(`[gjsify] plugin "${a}": bundling for GJS → ${F}`);try{await mkdir$1(N,{recursive:!0}),await new BuildAction({verbose:S,bundler:{input:n,output:{file:F}}}).buildApp(`gjs`,{preserveDefaultExport:!0})}catch(n){throw Error(`gjsify config: failed to bundle plugin "${a}" for GJS (needed because GJS can't import packages that use exports-map subpaths directly; cache dir ${N}). (${n.message})`)}return F}async isPluginBundleFresh(n,a,S){try{let C=await stat$1(n),N=await stat$1(a),F=await newestLockfileMtime(S);return C.mtimeMs>=Math.max(N.mtimeMs,F)}catch{return!1}}async buildApp(n=`gjs`,a={}){let{verbose:S,typescript:C,exclude:N,library:F,aliases:I,excludeGlobals:H}=this.configData,W=normalizeBundlerOptions(this.configData),K=W.output?.format??(W.output?.file?.endsWith(`.cjs`)?`cjs`:`esm`),q=K===`iife`?`esm`:K,Y=W.output?.file,X=W.output?.dir;if(!Y&&!X&&(F?.main||F?.module)){let n=q===`cjs`?F.main??F.module:F.module??F.main;if(n&&isUnsafeDefaultOutput(n))throw Error(`gjsify build: refusing to default --outfile to ${n} (would overwrite a TypeScript source file). Pass --outfile/--outdir explicitly, or set "gjsify.bundler.output.file" in package.json.`);Y=n}let{consoleShim:te,globals:ne}=this.configData,re=Array.isArray(W.external)?W.external:void 0,ie=typeof W.output?.banner==`string`?W.output.banner:void 0,ae={debug:S,app:n,format:q,exclude:N,reflection:C?.reflection,consoleShim:te,...I?{aliases:I}:{},...a.preserveDefaultExport?{preserveDefaultExport:!0}:{}},{autoMode:oe,extras:Z}=this.parseGlobalsValue(ne),se=await buildPnpPlugin(),ce=se?[se]:[],le=textLoaderPlugin({loaders:this.configData.loaders}),ue=le?[le]:[];if(W.plugins?.length){let n=await resolveUserPlugins(W.plugins,process.cwd(),isGjs()?{loadModule:(n,a)=>this.loadPluginViaGjsBundle(n,a,S)}:{});ue.push(...n)}if(n===`gjs`&&oe){let gjsifyPluginFactory=async n=>{let a=await gjsifyPlugin({input:W.input,output:{file:Y,dir:X},userExternal:re,userBanner:ie,userAliases:I,shebang:this.configData.shebang},n);return{options:a.options,plugins:a.plugins}},{injectPath:n}=await detectAutoGlobals({input:W.input,plugins:[...ce,...ue],external:W.external,transform:W.transform,format:q},ae,gjsifyPluginFactory,S,{extraGlobalsList:Z,excludeGlobals:H,cwd:process.cwd()},bundleToChunks);ae.autoGlobalsInject=n}else Z&&(ae.autoGlobalsInject=await this.resolveGlobalsInject(n,Z,S));let de=await gjsifyPlugin({input:W.input,output:{file:Y,dir:X},userExternal:re,userBanner:ie,userAliases:I,shebang:this.configData.shebang},ae),fe={...mergeBundlerOptions(de.options,W),plugins:[...ce,...ue,...de.plugins]};if(a.watch)return await this.runWatchLoop(fe,n,Y,S),[];let pe=await runBundle(fe);return(n===`gjs`||n===`node`)&&this.configData.shebang&&await this.applyShebang(n,Y,S),[pe]}async runWatchLoop(n,a,S,C){let N=await runWatch(n),F=new Promise(n=>{N.on(`close`,()=>n())}),I=!1,shutdown=async()=>{if(!I){I=!0,ke.log(`
|
|
740
740
|
[gjsify build --watch] stopping watcher…`);try{await N.close()}catch(n){ke.error(`[gjsify build --watch] watcher close error:`,n)}}};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),N.on(`event`,async n=>{switch(n.code){case`START`:C&&ke.log(`[gjsify build --watch] rebuild start`);break;case`BUNDLE_START`:ke.log(`[gjsify build --watch] building…`);break;case`BUNDLE_END`:ke.log(`[gjsify build --watch] built in ${n.duration}ms`);try{(a===`gjs`||a===`node`)&&this.configData.shebang&&await this.applyShebang(a,S,C)}finally{await n.result.close()}break;case`END`:ke.log(`[gjsify build --watch] waiting for changes…`);break;case`ERROR`:ke.error(`[gjsify build --watch] build failed:`,n.error?.message??n.error),C&&n.error?.stack&&ke.error(n.error.stack);try{await n.result.close()}catch{}break}}),C&&N.on(`change`,(n,a)=>{ke.log(`[gjsify build --watch] ${a.event}: ${n}`)}),await F}async start(n={app:`gjs`}){if(n.library){if(n.watch)throw Error(`gjsify build: --watch is not supported with --library (library mode would emit watcher rebuilds for every produced format; use --app gjs|node|browser instead).`);return await this.buildLibrary()}return await this.buildApp(n.app,{watch:n.watch})}}}),WA,GA=__esmMin(()=>{Fg(),UA(),WA={command:`build [entryPoints..]`,description:`Build and bundle your Gjs project`,builder:n=>n.option(`entry-points`,{description:`The entry points you want to bundle. Defaults to bundler.input from package.json#gjsify or .gjsifyrc.js, falling back to src/index.ts when neither is set.`,array:!0,type:`string`,normalize:!0,defaultDescription:`src/index.ts (fallback)`,coerce:n=>[...new Set(n)]}).option(`exclude`,{description:`An array of glob patterns to exclude entry-points and aliases`,array:!0,type:`string`,normalize:!0,default:[]}).option(`verbose`,{description:`Switch on the verbose mode`,type:`boolean`,normalize:!0,default:!1}).option(`app`,{description:`Use this if you want to build an application, the platform node is usually only used for tests`,type:`string`,choices:[`gjs`,`node`,`browser`,`nativescript`],normalize:!0,default:`gjs`}).option(`format`,{description:`Override the default output format`,type:`string`,choices:[`iife`,`esm`,`cjs`],normalize:!0}).option(`minify`,{description:`Minify the bundled output. Defaults to true; use --no-minify to emit pretty-printed code (e.g. for debugging or readable bundle review).`,type:`boolean`,normalize:!0,defaultDescription:`true`}).option(`library`,{description:`Use this if you want to build a library for Gjsify`,type:`boolean`,normalize:!0,default:!1}).option(`outfile`,{alias:`o`,description:`Sets the output file name for the build operation. If no outfile is specified, the outfile will be parsed from the package.json. Only used if application mode is active`,type:`string`,normalize:!0}).option(`outdir`,{alias:`d`,description:`Sets the output directory for the build operation. If no outdir is specified, the outdir will be parsed from the package.json. Only used if library mode is active`,type:`string`,normalize:!0}).option(`reflection`,{alias:`r`,description:`Enables TypeScript types on runtime using Deepkit's type compiler`,type:`boolean`,normalize:!0,default:!1}).option(`log-level`,{description:`The log level can be changed to prevent esbuild from printing warning and/or error messages to the terminal`,type:`string`,choices:[`silent`,`error`,`warning`,`info`,`debug`,`verbose`],normalize:!0,default:`warning`}).option(`console-shim`,{description:`Inject a console shim into GJS builds for clean output without the GLib prefix and with working ANSI colors. Use --no-console-shim to disable. Only applies to GJS app builds.`,type:`boolean`,normalize:!0,default:!0}).option(`globals`,{description:"Comma-separated list of global identifiers, 'auto' (default) to detect automatically from the bundled output, or 'none' to disable. The 'auto' token may be combined with explicit identifiers/groups (e.g. 'auto,dom') for cases where the detector cannot statically see a global because it's accessed via indirection. Each identifier is mapped to the corresponding `@gjsify/<pkg>/register` module and injected into the bundle. See the CLI Reference docs for the full list of known identifiers. Only applies to GJS app builds.",type:`string`,normalize:!0,default:`auto`}).option(`shebang`,{description:"Prepend a target-appropriate shebang to the output and mark it executable (chmod 755): `#!/usr/bin/env -S gjs -m` for --app gjs, `#!/usr/bin/env node` for --app node. Applies to GJS and Node app builds with a single --outfile. Default: false (use --shebang to enable, or set `shebang: true` in `.gjsifyrc.js`).",type:`boolean`,normalize:!0}).option(`external`,{description:"Module names that should NOT be bundled — EXACT package names only, matched literally on both bundler engines (no globs). Repeat the flag or pass a comma-separated list (e.g. --external typedoc,prettier). Appended to the per-app built-in externals; register subpaths (`<pkg>/register[/…]`) are always force-inlined for --app gjs regardless of this flag.",array:!0,type:`string`,default:[],coerce:n=>n.flatMap(n=>n.split(`,`).map(n=>n.trim()).filter(Boolean))}).option(`define`,{description:`Substitute compile-time constants. Each entry is KEY=VALUE where VALUE is a JS expression (string literals must be quoted: --define VERSION='"1.2.3"'). Repeat the flag or pass comma-separated. See https://esbuild.github.io/api/#define`,array:!0,type:`string`,default:[]}).option(`alias`,{description:`Map module specifiers at bundle time. Each entry is FROM=TO (e.g. --alias typedoc=@gjsify/empty). Layered on top of the built-in alias map. Useful for stubbing heavy deps the test scenario never executes.`,array:!0,type:`string`,default:[],coerce:n=>n.flatMap(n=>n.split(`,`).map(n=>n.trim()).filter(Boolean))}).option(`exclude-globals`,{description:`Comma-separated global identifiers to remove from auto-detection results. Use for false positives from dead browser-compat code whose polyfills require unavailable native libraries (e.g. --exclude-globals fetch,XMLHttpRequest).`,type:`string`,normalize:!0}).option(`watch`,{alias:`w`,description:"Watch source files and rebuild on change. Logs each rebuild with duration; clean SIGINT shutdown. Only valid with --app gjs|node|browser (rejected with --library). Requires the npm `rolldown` engine — run under Node, not the GJS-bundled CLI.",type:`boolean`,normalize:!0,default:!1}),handler:async n=>{await new HA(await new Config().forBuild(n)).start({library:n.library,app:n.app,watch:n.watch})}}});function nodeArchToLinuxArch(n){return{x64:`x86_64`,arm64:`aarch64`,arm:`armv7`,ia32:`i686`}[n]??n}function readPackageJson$3(n){try{return JSON.parse(readFileSync(n,`utf-8`))}catch{return null}}function scanNodeModules(n,a){let S=[];if(!existsSync(n))return S;let C;try{C=readdirSync(n)}catch{return S}for(let N of C)if(!N.startsWith(`.`))if(N.startsWith(`@`)){let C=ns(n,N),F;try{F=readdirSync(C)}catch{continue}for(let n of F){let F=checkPackage(ns(C,n),`${N}/${n}`,a);F&&S.push(F)}}else{let C=checkPackage(ns(n,N),N,a);C&&S.push(C)}return S}function checkPackage(n,a,S){let C=readPackageJson$3(ns(n,`package.json`));if(!C)return null;let N=C.gjsify;if(!N||typeof N!=`object`)return null;let F=N.prebuilds;if(typeof F!=`string`)return null;let I=ns(n,F,`linux-${S}`);return existsSync(I)?{name:a,prebuildsDir:I}:null}function detectNativePackages(n){let a=nodeArchToLinuxArch(process.arch),S=[],C=new Set,N=$o(n);for(;;){let n=ns(N,`node_modules`);if(existsSync(n))for(let N of scanNodeModules(n,a))C.has(N.name)||(C.add(N.name),S.push(N));let F=$o(N,`..`);if(F===N)break;N=F}return S}function buildNativeEnv(n){let a=n.map(n=>n.prebuildsDir),S=process.env.LD_LIBRARY_PATH??``,C=process.env.GI_TYPELIB_PATH??``;return{LD_LIBRARY_PATH:[...a,...S?[S]:[]].join(`:`),GI_TYPELIB_PATH:[...a,...C?[C]:[]].join(`:`)}}var KA=__esmMin(()=>{Zc(),ps(),__name$1(readPackageJson$3,`readPackageJson`)}),qA=__exportAll$3({computeNativeEnvForBundle:()=>computeNativeEnvForBundle,runGjsBundle:()=>runGjsBundle});function computeNativeEnvForBundle(n,a=process.cwd()){let S=$o(n),C=detectNativePackages(a),N=detectNativePackages(as(S)),F=new Set(C.map(n=>n.name)),I=buildNativeEnv([...C,...N.filter(n=>!F.has(n.name))]);return{env:I,envPrefix:Object.entries(I).filter(([,n])=>n!==void 0&&n!==``).map(([n,a])=>`${n}=${a}`).join(` `)}}async function runGjsBundle(n,a=[],S={}){let{env:C,envPrefix:N}=computeNativeEnvForBundle(n),F={...process.env,...C},I=[`-m`,n,...a],H=[`gjs`,...I.map(n=>n.includes(` `)?`"${n}"`:n)].join(` `);ke.error(`$ ${N?`${N} `:``}${H}`);let W=spawn(`gjs`,I,{env:F,stdio:`inherit`});await new Promise((n,a)=>{W.on(`close`,S=>{S===0?n():a(Error(`gjs exited with code ${S}`))}),W.on(`error`,a)}).catch(n=>{ke.error(n.message),process.exit(1)}),S.exitOnSuccess&&process.exit(0)}var JA=__esmMin(()=>{Ae(),oC(),ps(),KA()});async function buildTestBundle(n,a,S,C){let N=await new Config().forBuild({entryPoints:[n],outfile:a,app:S,verbose:C??!1,logLevel:`warning`,exclude:[]});N.library={...N.library},N.bundler={...N.bundler,input:[n],output:{...N.bundler?.output,file:a}},await new HA(N).start({app:S,library:!1})}async function runTestBundle(n,a){if(a===`gjs`){await runGjsBundle(n);return}await new Promise((a,S)=>{let C=spawn(`node`,[n],{stdio:`inherit`});C.on(`error`,S),C.on(`exit`,n=>{n===0?a():S(Error(`node exited with code ${n}`))})})}function isFresh(n,a){if(!existsSync(n))return!1;let S=statSync(n).mtimeMs,C=as(a);try{return S>=newestMtimeUnder(existsSync(C)?C:a)}catch{return!1}}function newestMtimeUnder(n){let a=statSync(n);if(a.isFile())return a.mtimeMs;let S=a.mtimeMs;for(let a of readdirSync(n,{withFileTypes:!0})){if(a.name===`node_modules`||a.name===`dist`||a.name===`lib`||a.name.startsWith(`.`))continue;let C=newestMtimeUnder(ns(n,a.name));C>S&&(S=C)}return S}var YA,XA=__esmMin(()=>{Ae(),Zc(),ps(),oC(),Fg(),UA(),JA(),YA={command:`test`,description:"Build + run the package’s `src/test.mts` suite on GJS and Node and aggregate the results. Replaces the per-package `build:test:{gjs,node}` + `test:{gjs,node}` script boilerplate.",builder:n=>n.option(`runtime`,{description:`Target runtime. Default: both.`,type:`string`,choices:[`gjs`,`node`,`all`],default:`all`}).option(`entry`,{description:"Path to the test entry. Default: `src/test.mts` (or `gjsify.test.entry`).",type:`string`,normalize:!0}).option(`outdir`,{description:"Output directory for the built test bundles. Default: `dist/`.",type:`string`,normalize:!0}).option(`rebuild`,{description:`Always rebuild the test bundles, even when they look up-to-date.`,type:`boolean`,default:!1}).option(`build`,{description:`Build before running. Default: true (use --no-build to skip when bundles already exist).`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print resolved entry/outdir + per-step timing.`,type:`boolean`,default:!1}),handler:async n=>{let a=process.cwd(),S=(await new Config().forBuild({}).catch(()=>({}))).test??{},C=$o(a,n.entry??S.entry??`src/test.mts`),N=$o(a,n.outdir??S.outdir??`dist`);existsSync(C)||(ke.error(`[gjsify test] no test entry at ${rs(a,C)} — add an \`src/test.mts\` that aggregates your \`@gjsify/unit\` suites, or set \`gjsify.test.entry\` in package.json.`),process.exit(1));let F=n.runtime===`gjs`?[`gjs`]:n.runtime===`node`?[`node`]:S.runtimes&&S.runtimes.length>0?S.runtimes:[`gjs`,`node`],I=[];for(let S of F){let F=ns(N,`test.${S}.mjs`);if(n.build!==!1)if(n.rebuild||!isFresh(F,C)){let N=Date.now();n.verbose&&ke.log(`[gjsify test] building → ${rs(a,F)} (—app ${S})`);try{await buildTestBundle(C,F,S,n.verbose),n.verbose&&ke.log(`[gjsify test] built ${S} in ${Date.now()-N}ms`)}catch(n){ke.error(`[gjsify test] build failed for ${S}:`,n.message),I.push({runtime:S,ok:!1,durationMs:0,error:`build failed`});continue}}else n.verbose&&ke.log(`[gjsify test] ${S}: bundle is up-to-date — skipping build (use --rebuild to force)`);else if(!existsSync(F)){ke.error(`[gjsify test] --no-build but ${rs(a,F)} doesn't exist. Build first or drop --no-build.`),I.push({runtime:S,ok:!1,durationMs:0,error:`no bundle`});continue}let H=Date.now();try{await runTestBundle(F,S),I.push({runtime:S,ok:!0,durationMs:Date.now()-H})}catch(n){I.push({runtime:S,ok:!1,durationMs:Date.now()-H,error:n.message})}}let H=I.map(n=>`${n.ok?`✅`:`❌`} ${n.runtime} (${n.durationMs}ms)${n.error?` — ${n.error}`:``}`).join(` `);ke.log(`[gjsify test] ${H}`),I.some(n=>!n.ok)&&process.exit(1),process.exit(0)}}});function readPackageJson$2(n){if(!existsSync(n))return null;let a=readFileSync(n,`utf-8`);try{return JSON.parse(a)}catch(a){throw Error(`gjsify install: ${n} is not valid JSON: ${a.message}`)}}function writePackageJson(n,a){let S=sortKnownDepFields(a);writeFileSync(n,JSON.stringify(S,null,2)+`
|
|
741
|
-
`,`utf-8`)}function parseSpec$2(n){if(n.startsWith(`@`)){let a=n.indexOf(`/`);if(a===-1)return{name:n};let S=n.indexOf(`@`,a+1);return S===-1?{name:n}:{name:n.slice(0,S),range:n.slice(S+1)}}let a=n.indexOf(`@`);return a===-1?{name:n}:{name:n.slice(0,a),range:n.slice(a+1)}}function projectSpecsFromPackageJson(n){let a=[];for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C))typeof S==`string`&&(/^(workspace|link|file|portal|git\+|https?):/.test(S)||a.push(`${n}@${S}`))}return a}function addDependencyEntry(n,a,S,C){n[C]===void 0&&(n[C]={}),n[C][a]=S}function defaultRangeFromVersion(n){return`^${n}`}function sortKnownDepFields(n){let a={...n};for(let n of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let S=a[n];S&&(a[n]=Object.fromEntries(Object.entries(S).sort(([n],[a])=>n<a?-1:+(n>a))))}return a}var ZA=__esmMin(()=>{Zc(),__name$1(readPackageJson$2,`readPackageJson`),__name$1(parseSpec$2,`parseSpec`)});function looksLikeFile(n){if(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`/`)||n.includes(`/`)||n.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(n))return!0;try{return statSync(n).isFile()}catch{return!1}}async function runScript(n,a){let S=process.cwd(),C=ns(S,`package.json`),N=readPackageJson$2(C);N||(ke.error(`gjsify run: no package.json in ${S}`),process.exit(1));let F=N.scripts??{},I=F[n];if(typeof I!=`string`){let a=Object.keys(F).join(`, `)||`<none>`;ke.error(`gjsify run: no script "${n}" in ${C} (available: ${a})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[ns(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(ns(H,`node_modules`,`.bin`));let K=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},q={...process.env,...K,PATH:[...W,process.env.PATH??``].filter(Boolean).join(ds),npm_lifecycle_event:n,npm_package_name:N.name??``,npm_package_version:N.version??``},Y=isGjs()?gjsifyInProcessArgv(I,a):null;if(Y){process.env.PATH=q.PATH,process.env.npm_lifecycle_event=q.npm_lifecycle_event,process.env.npm_package_name=q.npm_package_name,process.env.npm_package_version=q.npm_package_version,q.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=q.FORCE_COLOR);try{let{runCli:n}=await Promise.resolve().then(()=>(
|
|
741
|
+
`,`utf-8`)}function parseSpec$2(n){if(n.startsWith(`@`)){let a=n.indexOf(`/`);if(a===-1)return{name:n};let S=n.indexOf(`@`,a+1);return S===-1?{name:n}:{name:n.slice(0,S),range:n.slice(S+1)}}let a=n.indexOf(`@`);return a===-1?{name:n}:{name:n.slice(0,a),range:n.slice(a+1)}}function projectSpecsFromPackageJson(n){let a=[];for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=n[S];if(C)for(let[n,S]of Object.entries(C))typeof S==`string`&&(/^(workspace|link|file|portal|git\+|https?):/.test(S)||a.push(`${n}@${S}`))}return a}function addDependencyEntry(n,a,S,C){n[C]===void 0&&(n[C]={}),n[C][a]=S}function defaultRangeFromVersion(n){return`^${n}`}function sortKnownDepFields(n){let a={...n};for(let n of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let S=a[n];S&&(a[n]=Object.fromEntries(Object.entries(S).sort(([n],[a])=>n<a?-1:+(n>a))))}return a}var ZA=__esmMin(()=>{Zc(),__name$1(readPackageJson$2,`readPackageJson`),__name$1(parseSpec$2,`parseSpec`)});function looksLikeFile(n){if(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`/`)||n.includes(`/`)||n.includes(`\\`)||/\.(c?js|mjs|cjs|gjs)$/.test(n))return!0;try{return statSync(n).isFile()}catch{return!1}}async function runScript(n,a){let S=process.cwd(),C=ns(S,`package.json`),N=readPackageJson$2(C);N||(ke.error(`gjsify run: no package.json in ${S}`),process.exit(1));let F=N.scripts??{},I=F[n];if(typeof I!=`string`){let a=Object.keys(F).join(`, `)||`<none>`;ke.error(`gjsify run: no script "${n}" in ${C} (available: ${a})`),process.exit(1)}let H=findWorkspaceRoot(S),W=[ns(S,`node_modules`,`.bin`)];H&&H!==S&&W.push(ns(H,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&W.unshift(process.env.GJSIFY_SHIM_DIR);let K=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},q={...process.env,...K,PATH:[...W,process.env.PATH??``].filter(Boolean).join(ds),npm_lifecycle_event:n,npm_package_name:N.name??``,npm_package_version:N.version??``},Y=isGjs()?gjsifyInProcessArgv(I,a):null;if(Y){process.env.PATH=q.PATH,process.env.npm_lifecycle_event=q.npm_lifecycle_event,process.env.npm_package_name=q.npm_package_name,process.env.npm_package_version=q.npm_package_version,q.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=q.FORCE_COLOR);try{let{runCli:n}=await Promise.resolve().then(()=>(uP(),lP));await n(Y)}catch(n){ke.error(n.message),process.exit(1)}process.exit(process.exitCode==null?0:Number(process.exitCode))}let X=a.length>0?`${I} ${a.map(shellEscape).join(` `)}`:I;await new Promise((a,C)=>{let N=spawn(X,[],{cwd:S,env:q,stdio:`inherit`,shell:!0});N.on(`close`,S=>{S===0?a():C(Error(`script "${n}" exited with code ${S}`))}),N.on(`error`,C)}).catch(n=>{ke.error(n.message),process.exit(1)}),process.exit(0)}function shellEscape(n){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(n)?n:`'${n.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(n,a){let S=tokenizeSimpleCommand(n);return!S||S.length<2||S[0]!==`gjsify`?null:[...S.slice(1),...a]}function tokenizeSimpleCommand(n){let a=[],S=``,C=!1,N=null;for(let F=0;F<n.length;F++){let I=n[F];if(N===`'`){I===`'`?N=null:S+=I;continue}if(N===`"`){if(I===`"`)N=null;else if(I===`\\`&&(n[F+1]===`"`||n[F+1]===`\\`))S+=n[++F];else if(I===`$`||I==="`")return null;else S+=I;continue}if(I===`'`||I===`"`){N=I,C=!0;continue}if(I===` `||I===` `){C&&=(a.push(S),S=``,!1);continue}if(`|&;<>\`$()\\
|
|
742
742
|
\r*?{}[]~#!`.includes(I))return null;S+=I,C=!0}return N?null:(C&&a.push(S),a)}var QA,$A=__esmMin(()=>{Ae(),Zc(),ps(),oC(),JA(),ZA(),Lg(),zg(),QA={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:n=>n.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:[]}).parserConfiguration({"populate--":!0,"unknown-options-as-args":!0}),handler:async n=>{let a=n.target,S=n.args??[],C=(n[`--`]??[]).filter(n=>typeof n==`string`),N=[...S,...C],F=readPackageJson$2(ns(process.cwd(),`package.json`));if(!(F?.scripts&&typeof F.scripts[a]==`string`)&&looksLikeFile(a)){await runGjsBundle($o(a),N,{exitOnSuccess:!0});return}await runScript(a,N)}}}),ej,tj=__esmMin(()=>{Ae(),ps(),KA(),ej={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:n=>n.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 n=>{let a=process.cwd(),S=n.file?$o(n.file):null,C=detectNativePackages(a),{LD_LIBRARY_PATH:N,GI_TYPELIB_PATH:F}=buildNativeEnv(C);if(n.export){ke.log(`export LD_LIBRARY_PATH="${N}"`),ke.log(`export GI_TYPELIB_PATH="${F}"`);return}if(C.length===0){ke.log(`No native gjsify packages detected in node_modules.`),ke.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ke.log(`Native packages detected:`);for(let n of C)ke.log(` ${n.name} → ${n.prebuildsDir}`);ke.log(``),ke.log(`To run your app directly with gjs, set:`),ke.log(` export LD_LIBRARY_PATH="${N}"`),ke.log(` export GI_TYPELIB_PATH="${F}"`),S?ke.log(` gjs -m ${S}`):ke.log(` gjs -m <your-bundle.js>`),ke.log(``),ke.log(`Or use gjsify run to handle this automatically:`),S?ke.log(` gjsify run ${n.file}`):ke.log(` gjsify run <your-bundle.js>`)}}});function tryExecFile(n,a){try{return execFileSync(n,a,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`]}).trim()}catch{return null}}function checkBinary(n,a,S,C,N,F,I){let H=tryExecFile(S,C);return H===null?{id:n,name:a,found:!1,severity:N,requiredBy:I}:{id:n,name:a,found:!0,version:F?F(H):H.split(`
|
|
743
743
|
`)[0]??H,severity:N,requiredBy:I}}function checkPkgConfig(n,a,S,C,N){let F=tryExecFile(`pkg-config`,[`--modversion`,S]);return F===null?{id:n,name:a,found:!1,severity:C,requiredBy:N}:{id:n,name:a,found:!0,version:F.split(`
|
|
744
744
|
`)[0],severity:C,requiredBy:N}}function checkNpmPackage(n,a,S,C,N,F){try{return createRequire(pathToFileURL(ns(C,`_check_.js`)).href).resolve(S),{id:n,name:a,found:!0,severity:N,requiredBy:F}}catch{}try{return createRequire(import.meta.url).resolve(S),{id:n,name:a,found:!0,severity:N,requiredBy:F}}catch{return{id:n,name:a,found:!1,severity:N,requiredBy:F}}}function detectPackageManager$2(){for(let n of[`apt`,`dnf`,`pacman`,`zypper`,`apk`])if(tryExecFile(`which`,[n])!==null)return n;return`unknown`}function findProjectRoot(n){let a=$o(n);for(;;){if(existsSync(ns(a,`package.json`)))return a;let n=$o(a,`..`);if(n===a)return null;a=n}}function discoverGjsifyPackages(n){let a=findProjectRoot(n);if(!a)return null;let S=ns(a,`node_modules`,`@gjsify`);if(!existsSync(S))return new Set;let C=ns(a,`package.json`),N={};try{N=JSON.parse(readFileSync(C,`utf-8`))}catch{}let F={...N.dependencies,...N.devDependencies},I=new Set;try{for(let n of readdirSync(S,{withFileTypes:!0}))(n.isDirectory()||n.isSymbolicLink())&&I.add(`@gjsify/${n.name}`)}catch{}for(let n of Object.keys(F))n.startsWith(`@gjsify/`)&&I.add(n);return I}function computeNeededOptionalDeps(n){let a=discoverGjsifyPackages(n);if(a===null)return null;let S=new Set;for(let n of a){let a=rj[n];if(a)for(let n of a)S.add(n)}return S}function runAllChecks(n){let a=computeNeededOptionalDeps(n);return[...runMinimalChecks(),...runRequiredChecks(n),...runOptionalChecks(a,n)]}function runMinimalChecks(){let n=[];return n.push({id:`nodejs`,name:`Node.js`,found:!0,version:process.version,severity:`required`}),n.push(checkBinary(`gjs`,`GJS`,`gjs`,[`--version`],`required`,n=>n.replace(/^GJS\s+/i,``).split(`
|
|
@@ -796,7 +796,7 @@ jobs:
|
|
|
796
796
|
`)}function parseSpec(n){if(n.startsWith(`@`)){let a=n.indexOf(`/`);if(a<0)throw Error(`Invalid spec (scoped name without slash): ${n}`);let S=n.indexOf(`@`,a);return S<0?{name:n,range:`latest`}:{name:n.slice(0,S),range:n.slice(S+1)||`latest`}}let a=n.indexOf(`@`);return a<0?{name:n,range:`latest`}:{name:n.slice(0,a),range:n.slice(a+1)||`latest`}}function pickVersion(n,a,S){if(S&&n.versions[S]&&satisfiesRange(S,a))return S;if(n[`dist-tags`][a])return n[`dist-tags`][a];let C;try{C=new bM(a)}catch{throw Error(`Invalid version range for ${n.name}: ${a}`)}return maxSatisfying(Object.keys(n.versions).filter(n=>{try{return new SemVer(n),!0}catch{return!1}}),C)}async function downloadAndExtractAll(n,a,S,C,N,F){let I=[...n].sort((n,a)=>depth(n.installPath)-depth(a.installPath)||(n.installPath<a.installPath?-1:1)),H=[],W=Math.max(1,Math.min(FM,I.length));F?.beginPhase(`download`,I.length);let K=0,tickProgress=n=>{K++,F?.update({phase:`download`,current:K,total:I.length,name:`${n.name}@${n.version}`})},q=0,Y=I.findIndex(n=>depth(n.installPath)>1),X=Y<0?I.length:Y;for(;q<X;){let n=I[q++];if(!n)break;await extractOne(n,a,S,C,N),tickProgress(n)}for(let n=0;n<W;n++)H.push((async()=>{for(;;){let n=q++;if(n>=I.length)return;let F=I[n];if(!F)return;await extractOne(F,a,S,C,N),tickProgress(F)}})());await Promise.all(H),F?.endPhase(`download`)}async function extractOne(n,a,S,C,N){let F=ns(a,n.installPath);assertNodeModulesDest(F,n);let I=getCachedTarball(n.integrity);I?C(`cache-hit: %s@%s ← %s`,n.name,n.version,n.integrity):(I=getForeignCachedTarball(n.integrity))?(C(`npm-cache-hit: %s@%s ← %s`,n.name,n.version,n.integrity),putCachedTarball(n.integrity,I)):(C(`fetch: %s@%s ← %s (→ %s)`,n.name,n.version,n.tarballUrl,n.installPath),I=await fetchTarball(n.tarballUrl,{npmrc:S,signal:N,integrity:n.integrity,onRetry:({attempt:a,error:S,delayMs:N})=>{C(`tarball %s@%s: retry %d after %dms (%s)`,n.name,n.version,a,N,errMsg(S))}}),putCachedTarball(n.integrity,I)),rmSync(F,{recursive:!0,force:!0}),mkdirSync(F,{recursive:!0}),await extractTarball(I,F)}function assertNodeModulesDest(n,a){if(!n.split(us).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${a.name}@${a.version} into ${n} — target is not inside a node_modules/ directory. This would overwrite working-tree files. A workspace package likely leaked into the fetch queue (it must be symlinked, not fetched).`);let S;try{S=realpathSync(n)}catch{return}if(!S.split(us).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${a.name}@${a.version} — ${n} resolves to ${S}, which is outside any node_modules/ directory (likely a symlink to a workspace source tree). Extracting here would delete working-tree source files.`)}function depth(n){return n.split(`/node_modules/`).length}async function linkBins(n,a,S){let C=ns(a,`node_modules`,`.bin`),N=0;for(let S of n){if(!S.bin||depth(S.installPath)!==1)continue;let n=normalizeBin$1(S.name,S.bin);if(n.size!==0){mkdirSync(C,{recursive:!0});for(let[F,I]of n){let n=ns(a,S.installPath,I);if(!existsSync(n))continue;try{chmodSync(n,493)}catch{}let H=ns(C,F);rmSync(H,{force:!0});let W=rs(C,n);try{symlinkSync(W,H),N++}catch{copyFileSync(n,H),chmodSync(H,493),N++}}}}N>0&&S(`bin: linked %d entry(ies) under .bin/`,N)}function normalizeBin$1(n,a){let S=new Map;if(typeof a==`string`){let C=n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n;return S.set(C,a),S}for(let[n,C]of Object.entries(a))S.set(n,C);return S}async function loadNpmrc$1(n){let a=homedir(),S={registry:n.registry??SM,scopes:{},authTokens:{},basicAuth:{}};for(let C of[ns(a,`.npmrc`),ns(n.prefix,`.npmrc`)])if(existsSync(C))try{let n=parseNpmrc(readFileSync(C,`utf-8`));S={...S,...n,scopes:{...S.scopes,...n.scopes}}}catch(n){ke.warn(`gjsify install: ignoring malformed ${C}: ${n.message}`)}let C=process.env.npm_config_registry;return C&&(S.registry=C),n.registry&&(S.registry=n.registry),S}function makeLogger(n){return n?(n,...a)=>{let S=n.replace(/%s|%d/g,()=>String(a.shift()));process.stderr.write(`gjsify install: ${S}\n`)}:()=>{}}var FM,IM,LM,RM=__esmMin(()=>{Ae(),Zc(),ps(),Wp(),xM(),CM(),OM(),jM(),NM(),FM=Number(process.env.GJSIFY_INSTALL_CONCURRENCY??`16`)||16,IM=`gjsify-lock.json`,LM=2,__name$1(normalizeBin$1,`normalizeBin`),__name$1(loadNpmrc$1,`loadNpmrc`)});async function installPackages(n){if(zM===`npm`)return await installViaNpm(n),{installed:[]};let{installPackagesNative:a}=await Promise.resolve().then(()=>(RM(),PM));return{installed:await a(n)}}async function installViaNpm({prefix:n,specs:a,verbose:S,registry:C}){if(a.length===0)throw Error(`installPackages: empty specs list`);writeFileSync(ns(n,`package.json`),JSON.stringify({name:`gjsify-dlx-cache`,version:`0.0.0`,private:!0},null,2)),C&&writeFileSync(ns(n,`.npmrc`),`registry=${C}\n`);let N=[`install`,`--no-package-lock`,`--no-audit`,`--no-fund`,`--prefix`,n,...S?[`--loglevel`,`verbose`]:[`--loglevel`,`warn`],...a];await new Promise((n,a)=>{let S=spawn(`npm`,N,{stdio:`inherit`});S.on(`close`,S=>{S===0?n():a(Error(`npm install exited with code ${S}`))}),S.on(`error`,n=>{let S=n.code===`ENOENT`?`npm not found on PATH — install Node.js or set GJSIFY_INSTALL_BACKEND=native (not yet supported)`:`npm install failed: ${n.message}`;a(Error(S))})})}var zM,BM=__esmMin(()=>{oC(),Zc(),ps(),_M(),zM=process.env.GJSIFY_INSTALL_BACKEND??`native`});async function ensurePkgDir(n,a){if(n.kind===`local`)return{pkgDir:n.path,cachedPkgName:null};let S=cacheDirFor(createCacheKey({packages:[n.spec]})),C=a.cacheMaxAge>0?getValidCachedPkg(S,a.cacheMaxAge):void 0;if(C)return{pkgDir:resolveInstalledPkgDir(C,n.name),cachedPkgName:n.name};let N=makePrepareDir(S),F=makeProgressReporter({enabled:!a.verbose});return await installPackages({prefix:N,specs:[n.spec],verbose:a.verbose,registry:a.registry,lockfile:!0,frozen:a.frozen,progress:F}),{pkgDir:resolveInstalledPkgDir(symlinkSwap(S,N),n.name),cachedPkgName:n.name}}function splitBinAndArgs(n,a,S){if(!a)return{binName:null,extraArgs:S};let C=ns(n,`package.json`);if(existsSync(C))try{let n=JSON.parse(readFileSync(C,`utf-8`)).gjsify?.bin;if(n&&Object.prototype.hasOwnProperty.call(n,a))return{binName:a,extraArgs:S}}catch{}return{binName:null,extraArgs:[a,...S]}}var VM,HM=__esmMin(()=>{Ae(),JA(),uM(),dM(),mM(),BM(),Zc(),ps(),VM={command:`dlx <spec> [binOrArg] [extraArgs..]`,description:`Run the GJS bundle of an npm-published package without installing it locally.`,builder:n=>n.parserConfiguration({"populate--":!0}).positional(`spec`,{description:"Package spec (`name`, `name@version`, `@scope/name@spec`, or local path).",type:`string`,demandOption:!0}).positional(`binOrArg`,{description:"Optional bin name when the package defines `gjsify.bin` with multiple entries; otherwise treated as the first argument forwarded to the bundle. To pass a flag here (e.g. `--help`) use the `--` separator: `gjsify dlx <pkg> -- --help`.",type:`string`}).positional(`extraArgs`,{description:"Extra args forwarded to `gjs -m <bundle>`. Use `--` before flags to bypass gjsify-level parsing (`gjsify dlx <pkg> -- --help --verbose`).",type:`string`,array:!0}).option(`cache-max-age`,{description:`Cache TTL in minutes. Defaults to 7 days. Use 0 to bypass cache.`,type:`number`,default:1440*7}).option(`reinstall`,{description:`Bypass the cache for this run (alias for --cache-max-age=0).`,type:`boolean`,default:!1}).option(`frozen`,{description:`Use the project-local gjsify-lock.json verbatim — fail if missing or stale (no resolver pass).`,type:`boolean`,default:!1}).option(`verbose`,{description:`Verbose logging (passes --loglevel verbose to npm).`,type:`boolean`,default:!1}).option(`registry`,{description:`Registry URL override.`,type:`string`}),handler:async n=>{let a=parseSpec$1(n.spec),S=n.reinstall?0:n[`cache-max-age`],{pkgDir:C,cachedPkgName:N}=await ensurePkgDir(a,{verbose:n.verbose,registry:n.registry,cacheMaxAge:S,frozen:n.frozen}),F=(n[`--`]??[]).map(n=>String(n)),I=[...n.extraArgs??[],...F],{binName:H,extraArgs:W}=splitBinAndArgs(C,n.binOrArg,I),K=resolveGjsEntry(C,H);K.fromFallback&&ke.warn(`[gjsify dlx] package "${N??a.kind}" has no \`gjsify\` field — falling back to package.json#main. Add \`gjsify.main\` to silence.`),await runGjsBundle(K.bundlePath,W,{exitOnSuccess:!0})}}});function defaultGlobalLayout(){let n=process.env.GJSIFY_GLOBAL_PREFIX,a=process.env.GJSIFY_GLOBAL_BIN_DIR,S=homedir(),C=process.env.XDG_DATA_HOME??ns(S,`.local`,`share`);return{prefix:n??ns(C,`gjsify`,`global`),binDir:a??ns(S,`.local`,`bin`)}}function linkGlobalBins(n,a){mkdirSync(a.binDir,{recursive:!0});let S=[],C=buildLauncherEnvPreamble(detectNativePackages(a.prefix).map(n=>n.prebuildsDir));for(let N of n){let n=ns(a.prefix,`node_modules`,N),F=ns(n,`package.json`);if(!existsSync(F))continue;let I=pickBinMap(N,readJson(F));if(!(!I||I.size===0))for(let[N,F]of I){let I=ns(n,F);if(!existsSync(I))continue;try{chmodSync(I,493)}catch{}let H=ns(a.binDir,N);rmSync(H,{force:!0}),writeFileSync(H,I.endsWith(`.gjs.mjs`)||I.endsWith(`.mjs`)?`#!/bin/sh\n${C}exec gjs -m ${shQuote(I)} "$@"\n`:`#!/bin/sh\nexec ${shQuote(I)} "$@"\n`),chmodSync(H,493),S.push({name:N,target:I,link:H})}}return S}function shQuote(n){return`'${n.replace(/'/g,`'\\''`)}'`}function buildLauncherEnvPreamble(n){if(n.length===0)return``;let a=shQuote(n.join(`:`));return`GI_TYPELIB_PATH=${a}\${GI_TYPELIB_PATH:+":$GI_TYPELIB_PATH"}\nLD_LIBRARY_PATH=${a}\${LD_LIBRARY_PATH:+":$LD_LIBRARY_PATH"}\nexport GI_TYPELIB_PATH LD_LIBRARY_PATH\n`}function pickBinMap(n,a){let S=a.gjsify;if(S?.bin!==void 0)return normalizeBin(n,S.bin);let C=a.bin;return C===void 0?null:normalizeBin(n,C)}function normalizeBin(n,a){let S=new Map;if(typeof a==`string`){let C=n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n;return S.set(C,a),S}for(let[n,C]of Object.entries(a))S.set(n,C);return S}function readJson(n){return JSON.parse(readFileSync(n,`utf-8`))}function binDirOnPath(n){let a=process.env.PATH??``,S=process.platform===`win32`?`;`:`:`,C=$o(n);return a.split(S).some(n=>n&&$o(n)===C)}function specToPackageName(n){if(n.startsWith(`@`)){let a=n.indexOf(`/`);if(a<0)return n;let S=n.indexOf(`@`,a);return S<0?n:n.slice(0,S)}let a=n.indexOf(`@`);return a<0?n:n.slice(0,a)}var UM=__esmMin(()=>{Zc(),Wp(),ps(),KA()});function isAbortedFromOverallTimeout(n){if(!n||typeof n!=`object`)return!1;let a=n.name;if(a===`AbortError`)return!0;let S=n.message;return!!(typeof S==`string`&&S.includes(`install-overall-timeout`)||a===`RegistryTimeoutError`)}function isWorkspaceRoot(n){let a=readPackageJson$2(ns(n,`package.json`));return a?a.workspaces!==void 0:!1}function depKindFromArgs(n){return n[`save-dev`]?`devDependencies`:n[`save-peer`]?`peerDependencies`:n[`save-optional`]?`optionalDependencies`:`dependencies`}async function projectInstallNative(n,a){let S=process.cwd(),C=ns(S,`package.json`),N=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(n=>existsSync(ns(S,n)));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((!n.packages||n.packages.length===0)&&isWorkspaceRoot(S)){await workspaceInstall(S,n,a);return}let F,I=readPackageJson$2(C),H=I?projectSpecsFromPackageJson(I):[];if(n.packages&&n.packages.length>0){let a=new Set(n.packages.map(n=>parseSpec$2(n).name));F=[...H.filter(n=>!a.has(parseSpec$2(n).name)),...n.packages]}else{if(!I)throw Error(`gjsify install: no package.json in ${S}`);if(F=H,F.length===0){ke.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(S,{recursive:!0});let W=makeProgressReporter({enabled:!n.verbose&&!n.quiet&&n.progress!==!1}),K=await installPackages({prefix:S,specs:F,verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,refreshLockfile:n[`refresh-lockfile`],signal:a,progress:W});if(n.packages&&n.packages.length>0&&I){let a=depKindFromArgs(n);for(let S of n.packages){let{name:n,range:C}=parseSpec$2(S),N=K.installed.find(a=>a.name===n);addDependencyEntry(I,n,C??(N?defaultRangeFromVersion(N.version):`latest`),a)}writePackageJson(C,I),n.immutable||syncLockfileRequested(S,projectSpecsFromPackageJson(I))}}function syncLockfileRequested(n,a){let S=ns(n,`gjsify-lock.json`);if(existsSync(S))try{let n=JSON.parse(readFileSync(S,`utf-8`)),C=[...a].sort(),N=[...n.requested??[]].sort();if(C.length===N.length&&C.every((n,a)=>n===N[a]))return;n.requested=a,writeFileSync(S,JSON.stringify(n,null,2)+`
|
|
797
797
|
`)}catch{}}async function workspaceInstall(n,a,S){let C=discoverWorkspaces(n,{includeRoot:!0});if(C.length===0)throw Error(`gjsify install: ${n} has a "workspaces" field but no workspaces were discovered`);let N=new Map(C.map(n=>[n.name,n])),F=new Set,I=[];for(let n of C){let a=n.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=a[S];if(C)for(let[a,S]of Object.entries(C)){if(typeof S!=`string`)continue;let C=N.get(a);if(C&&!/^(link|file|portal|git\+|https?):/.test(S)){I.push({fromWorkspaceName:n.name,depName:a,targetLocation:C.location});continue}if(S.startsWith(`workspace:`))throw Error(`gjsify install: ${n.name} declares "${a}: ${S}" but no workspace with that name exists`);/^(link|file|portal|git\+|https?):/.test(S)||F.add(`${a}@${S}`)}}}ke.log(`gjsify install: ${C.length} workspace(s), ${F.size} external dep spec(s), ${I.length} workspace symlink(s)`),writeWorkspaceBinShims(n,C);let wireWorkspaceSymlinks=async()=>{if(I.length>0){let n=await Promise.resolve().then(()=>(kc(),Ec)),a=new Set,S=[];for(let n of I){let C=N.get(n.fromWorkspaceName);if(!C)continue;let F=ns(C.location,`node_modules`,n.depName);a.add(as(F));let I=rs(as(F),n.targetLocation);S.push({linkPath:F,relTarget:I})}await Promise.all([...a].map(a=>n.mkdir(a,{recursive:!0})));let C=0,F=[],wireOne=async(a,S)=>{try{await n.rm(a,{recursive:!0,force:!0})}catch{}await n.symlink(S,a)};for(let n=0;n<Math.min(32,S.length);n++)F.push((async()=>{for(;;){let n=C++;if(n>=S.length)return;let a=S[n];if(!a)return;await wireOne(a.linkPath,a.relTarget)}})());await Promise.all(F),ke.log(`gjsify install: wired ${I.length} workspace symlink(s)`)}let a=ns(n,`node_modules`),S=0;for(let N of C){if(N.location===n||!N.name)continue;let C=ns(a,N.name),F=!1;try{lstatSync(C),F=!0}catch{}F||(mkdirSync(as(C),{recursive:!0}),symlinkSync(rs(as(C),N.location),C),S++)}S>0&&ke.log(`gjsify install: hoisted ${S} workspace(s) to root node_modules/`)};await wireWorkspaceSymlinks();let H=C.find(a=>a.location===n)?.manifest,W=extractOverrides(H),K=W?.global,q=new Map,Y=new Set;if(W&&W.scoped.size>0){for(let n of C){let a=n.manifest;for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=a[S];if(C)for(let[a,S]of Object.entries(C)){let C=scopedOverrideFor(n,a,W);if(!C)continue;let N=C,F=n.location,I=q.get(F);I||(I=new Set,q.set(F,I)),I.add(`${a}@${N}`),Y.add(`${a}@${S}`)}}}let n=new Set;for(let a of C)for(let S of[`dependencies`,`devDependencies`,`optionalDependencies`]){let C=a.manifest[S];if(C)for(let[S,N]of Object.entries(C))scopedOverrideFor(a,S,W)||n.add(`${S}@${N}`)}for(let a of Y)n.has(a)||F.delete(a);q.size>0&&ke.log(`gjsify install: ${q.size} workspace(s) have scoped overrides — they will install their overridden deps locally after the root install`)}if(F.size>0){let C=makeProgressReporter({enabled:!a.verbose&&!a.quiet&&a.progress!==!1});await installPackages({prefix:n,specs:[...F],verbose:a.verbose,lockfile:!a.immutable,frozen:a.immutable,refreshLockfile:a[`refresh-lockfile`],overrides:K,signal:S,progress:C})}else a.verbose&&ke.log(`gjsify install: no external deps to fetch`);for(let[n,N]of q){if(N.size===0)continue;let F=C.find(a=>a.location===n)?.name??n;a.verbose&&ke.log(`gjsify install: ${F} — installing ${N.size} scoped-override spec(s) into ${n}/node_modules/`),await installPackages({prefix:n,specs:[...N],verbose:a.verbose,lockfile:!a.immutable,frozen:a.immutable,signal:S})}await wireWorkspaceSymlinks();let X=writeWorkspaceBinShims(n,C);X>0&&ke.log(`gjsify install: linked ${X} workspace bin(s) into node_modules/.bin/`)}function writeWorkspaceBinShims(n,a){let S=ns(n,`node_modules`,`.bin`),C=detectNativePackages(n).map(n=>n.prebuildsDir),N=0;for(let n of a){let a=n.manifest,F=a.gjsify?.bin,I=a.bin,H=mergeWorkspaceBins(n.name,F,I);if(H.size!==0){mkdirSync(S,{recursive:!0});for(let[a,{nodeTarget:F,gjsTarget:I}]of H){let H=ns(S,a);try{rmSync(H,{force:!0})}catch{}writeFileSync(H,buildBinShim(n.location,F,I,C),{mode:493}),chmodSync(H,493),N++}}}return N}function extractOverrides(n){if(!n)return;let a={},S=new Map,merge=(n,C)=>{if(n){for(let[N,F]of Object.entries(n))if(!N.startsWith(`_`)){if(typeof F==`string`){let n=N,S=N.startsWith(`@`)?N.indexOf(`@`,1):N.indexOf(`@`);S>0&&(n=N.slice(0,S)),a[n]=F;continue}if(F&&typeof F==`object`&&!Array.isArray(F)){let n={};for(let[a,S]of Object.entries(F)){if(a.startsWith(`_`))continue;if(typeof S!=`string`){ke.warn(`gjsify install: ${C}["${N}"]["${a}"] is not a string — only one level of nesting is supported, skipping`);continue}let F=a,I=a.startsWith(`@`)?a.indexOf(`@`,1):a.indexOf(`@`);I>0&&(F=a.slice(0,I)),n[F]=S}if(Object.keys(n).length>0){let a=S.get(N)??{};S.set(N,{...a,...n})}continue}ke.warn(`gjsify install: ${C}["${N}"] is not a string or object — skipping`)}}};if(merge(n.overrides,`overrides`),merge(n.resolutions,`resolutions`),!(Object.keys(a).length===0&&S.size===0))return{global:a,scoped:S}}function scopedOverrideFor(n,a,S){if(!S||S.scoped.size===0)return;let C=[n.name,n.relativeLocation];for(let n of C){let C=S.scoped.get(n);if(C?.[a])return C[a]}}function buildBinShim(n,a,S,C=[]){let N=a?ns(n,a):null,F=S?ns(n,S):null,I=C.length===0?``:(()=>{let n=`'${C.join(`:`).replace(/'/g,`'\\''`)}'`;return`GI_TYPELIB_PATH=${n}\${GI_TYPELIB_PATH:+":$GI_TYPELIB_PATH"}\nLD_LIBRARY_PATH=${n}\${LD_LIBRARY_PATH:+":$LD_LIBRARY_PATH"}\nexport GI_TYPELIB_PATH LD_LIBRARY_PATH\n`})();if(N&&F)return`#!/bin/sh\nif command -v gjs >/dev/null 2>&1 && [ -f "${F}" ]; then\n${I}exec gjs -m "${F}" "$@"\nfi\nexec node "${N}" "$@"\n`;if(N)return`#!/bin/sh\nexec node "${N}" "$@"\n`;if(F)return`#!/bin/sh\n${I}exec gjs -m "${F}" "$@"\n`;throw Error(`buildBinShim: either nodeTarget or gjsTarget must be provided`)}function mergeWorkspaceBins(n,a,S){let C=new Map,N=n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n,get=n=>{let a=C.get(n);return a||(a={},C.set(n,a)),a};if(typeof S==`string`)get(N).nodeTarget=S;else if(S&&typeof S==`object`)for(let[n,a]of Object.entries(S))typeof a==`string`&&a.length>0&&(get(n).nodeTarget=a);if(typeof a==`string`)get(N).gjsTarget=a;else if(a&&typeof a==`object`)for(let[n,S]of Object.entries(a))typeof S==`string`&&S.length>0&&(get(n).gjsTarget=S);return C}async function projectInstallViaNpm(n){let a=[`install`];n[`save-dev`]&&a.push(`--save-dev`),n[`save-peer`]&&a.push(`--save-peer`),n[`save-optional`]&&a.push(`--save-optional`),n.verbose&&a.push(`--loglevel`,`verbose`),n.packages&&n.packages.length>0&&a.push(...n.packages),await spawnNpm(a)}async function spawnNpm(n){return new Promise((a,S)=>{let C=spawn(`npm`,n,{stdio:`inherit`});C.on(`close`,n=>{n===0?a():S(Error(`npm install exited with code ${n}`))}),C.on(`error`,n=>{let a=n.code===`ENOENT`?`npm not found on PATH — install Node.js first.`:`npm install failed: ${n.message}`;S(Error(a))})}).catch(n=>{ke.error(n.message),process.exit(1)})}async function installGlobalAndLink(n,a){let S=defaultGlobalLayout();mkdirSync(S.prefix,{recursive:!0}),ke.log(`gjsify install --global → ${S.prefix}`),ke.log(` bins → ${S.binDir}`),await installPackages({prefix:S.prefix,specs:n,verbose:a.verbose});let C=linkGlobalBins(n.map(specToPackageName),S);if(C.length===0)ke.warn("\nNo bins declared (neither `gjsify.bin` nor `bin` in package.json) — nothing was symlinked.");else{ke.log(`\nLinked ${C.length} bin(s):`);for(let n of C)ke.log(` • ${n.link} → ${n.target}`)}C.length>0&&!binDirOnPath(S.binDir)&&ke.warn(`\nNote: ${S.binDir} is not on your PATH.\nAdd it to your shell rc file:\n export PATH="${S.binDir}:$PATH"`)}async function runPostInstallChecks(){ke.log(`
|
|
798
798
|
--- gjsify post-install checks ---`);let n=runMinimalChecks().filter(n=>!n.found&&n.severity===`required`);if(n.length>0){ke.warn(`Missing required system dependencies:
|
|
799
|
-
`);for(let a of n)ke.warn(` ✗ ${a.name}`);let a=buildInstallCommand(detectPackageManager$2(),n);a&&ke.warn(`\nInstall with:\n ${a}`)}else ke.log(`System dependencies OK.`);let a=detectNativePackages(process.cwd());if(a.length>0){ke.log(`\nDetected ${a.length} @gjsify/* package(s) with native prebuilds:`);for(let n of a)ke.log(` • ${n.name}`);ke.log("\nUse `gjsify run <bundle>` to launch with LD_LIBRARY_PATH/GI_TYPELIB_PATH set.")}maybeInstallGitHooks()}function maybeInstallGitHooks(){let n=process.cwd(),a=ns(n,`scripts`,`install-git-hooks.mjs`);if(existsSync(a)&&existsSync(ns(n,`.git`)))try{let S=spawnSync(process.execPath,[a,`--quiet`],{cwd:n,stdio:`inherit`,env:process.env});S.status!==0&&ke.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(n){ke.warn(`[gjsify install] git hook installation skipped: ${n instanceof Error?n.message:String(n)}`)}}var WM,GM,KM=__esmMin(()=>{Ae(),Zc(),ps(),oC(),Ig(),oj(),KA(),BM(),UM(),ZA(),WM=18e5,GM={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:n=>n.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(`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:WM}),handler:async n=>{if(n.immutable&&(n.packages&&n.packages.length>0&&(ke.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1)),n.global&&(ke.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1)),n[`refresh-lockfile`]&&(ke.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1))),n.global){(!n.packages||n.packages.length===0)&&(ke.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1));for(let a of[`save-dev`,`save-peer`,`save-optional`])n[a]&&ke.warn(`gjsify install --global ignores --${a}: global installs do not modify a project package.json.`);await installGlobalAndLink(n.packages,{verbose:n.verbose});return}if((n.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(n),await runPostInstallChecks();return}let a=n.timeout>0?n.timeout:0,S=a>0?new AbortController:null,C=S===null?null:setTimeout(()=>S.abort(Error(`install-overall-timeout`)),a);try{await projectInstallNative(n,S?.signal),await runPostInstallChecks()}catch(n){if(S!==null&&S.signal.aborted&&isAbortedFromOverallTimeout(n)){let n=Math.round(a/100)/10;ke.error(`gjsify install: timed out after ${n}s — likely a registry slowdown.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw n}finally{C!==null&&clearTimeout(C)}}}});function readDirectChildren(n){let a;try{a=readdirSync(`/proc/${n}/task`)}catch{return null}let S=[],C=!1;for(let N of a)try{let a=readFileSync(`/proc/${n}/task/${N}/children`,`utf-8`);C=!0;for(let n of a.trim().split(/\s+/)){let a=Number(n);Number.isInteger(a)&&a>0&&S.push(a)}}catch{}return C?S:null}function buildPpidMap(){let n=new Map,a=[];try{a=readdirSync(`/proc`)}catch{return n}for(let S of a){let a=Number(S);if(!(!Number.isInteger(a)||a<=0))try{let S=readFileSync(`/proc/${a}/stat`,`utf-8`),C=S.slice(S.lastIndexOf(`)`)+2).split(` `),N=Number(C[1]);if(!Number.isInteger(N)||N<=0)continue;let F=n.get(N);F?F.push(a):n.set(N,[a])}catch{}}return n}function collectDescendants(n){let a=[],S=new Set([n]),C=[n],N=null;for(;C.length>0;){let n=C.shift(),F=readDirectChildren(n);F===null&&(N??=buildPpidMap(),F=N.get(n)??[]);for(let n of F)S.has(n)||(S.add(n),a.push(n),C.push(n))}return a}function signalTree(n,a,S){for(let n=a.length-1;n>=0;n--)try{process.kill(a[n],S)}catch{}try{n.kill(S)}catch{}}function killActiveChildren(){let n=new Map;for(let a of qM){let S=a.pid?collectDescendants(a.pid):[];n.set(a,S),signalTree(a,S,`SIGTERM`)}setTimeout(()=>{for(let a of qM){let S=new Set(a.pid?collectDescendants(a.pid):[]);for(let C of n.get(a)??[])S.add(C);signalTree(a,[...S],`SIGKILL`)}},JM).unref?.()}async function runSequential(n,a,S,C,N){for(let F of n)await runOne$1(F,a,S,!1,C,N)}async function runParallel(n,a,S,C,N,F){let I=0,H=[];for(let W=0;W<C;W++)H.push((async()=>{for(;I<n.length;)await runOne$1(n[I++],a,S,!0,N,F)})());await Promise.all(H)}async function runTopologicalParallel(n,a,S,C,N,F,I){let H=new Set(n.map(n=>n.name)),W=new Map;for(let a of n){let n=new Set,S=a.manifest;for(let a of[S.dependencies,F?S.devDependencies:void 0,S.optionalDependencies])if(a)for(let[S,C]of Object.entries(a))typeof C==`string`&&C.startsWith(`workspace:`)&&H.has(S)&&n.add(S);W.set(a.name,n)}let K=new Map(n.map(n=>[n.name,n])),q=n.length,Y=new Set,X=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((n,F)=>{let H=null,re=Date.now(),describeInflight=()=>[...ne.entries()].map(([n,a])=>`${n} (${Math.round((Date.now()-a)/1e3)}s)`).join(`, `),failFast=n=>{H||(H=n,killActiveChildren(),setTimeout(()=>settle(),YM).unref?.())},ae=setInterval(()=>{let n=Date.now()-re;n<3e5||ne.size===0||(ke.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(n/6e4)}min — in-flight: ${describeInflight()}`),n>=ie&&failFast(Error(`gjsify foreach: stalled — no workspace completed for ${Math.round(n/6e4)}min (override via GJSIFY_FOREACH_STALL_MINUTES); killed in-flight: ${describeInflight()}`)))},6e4);ae.unref?.();let settle=()=>{clearInterval(ae),H?F(H):n()},pump=()=>{if(!H){for(;X<C;){let n=[...W.entries()].filter(([,n])=>[...n].every(n=>Y.has(n))).map(([n])=>n);if(n.length===0)break;let C=n.sort()[0];W.delete(C),X++,ne.set(C,Date.now()),te&&ke.error(`[gjsify foreach] start ${C} (${Y.size}/${q} done, ${X} in flight)`),runOne$1(K.get(C),a,S,!0,N,I).then(()=>{Y.add(C)}).catch(n=>{failFast(n instanceof Error?n:Error(String(n)))}).finally(()=>{X--,ne.delete(C),re=Date.now(),H?X===0&&settle():W.size===0&&X===0?settle():pump()})}W.size>0&&X===0&&!H&&(clearInterval(ae),F(Error(`gjsify foreach --topological: stuck — workspaces ${[...W.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne$1(n,a,S,C,N,F){if(F){N&&ke.error(`[${n.name}] $ ${a} ${S.join(` `)}`),await spawnPrefixed(a,S,n.location,C?`[${n.name}] `:null);return}let I=detectPackageManager$1(),H=I===`gjsify`?[`run`,a,...S]:[`run`,a,...S.length>0?[`--`,...S]:[]];N&&ke.error(`[${n.name}] $ ${I} ${H.join(` `)}`),await spawnPrefixed(I,H,n.location,C?`[${n.name}] `:null)}function detectPackageManager$1(){let n=process.env.npm_config_user_agent??``;return n.startsWith(`yarn/`)?`yarn`:n.startsWith(`gjsify/`)?`gjsify`:`npm`}function spawnPrefixed(n,a,S,C){let N=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`};return new Promise((F,I)=>{let H=spawn(n,a,{cwd:S,stdio:C?[`ignore`,`pipe`,`pipe`]:`inherit`,env:{...process.env,...N}});qM.add(H);let W=!process.stdout.isTTY,K=[];C&&H.stdout&&H.stderr&&(K.push(prefixLines(H.stdout,process.stdout,C,W)),K.push(prefixLines(H.stderr,process.stderr,C,W))),H.on(`close`,S=>{qM.delete(H);for(let n of K)n();S===0?F():I(Error(`${n} ${a.join(` `)} exited with code ${S}`))}),H.on(`error`,n=>{qM.delete(H),I(n)})})}var qM,JM,YM,XM,ZM=__esmMin(()=>{Ae(),oC(),Zc(),Wp(),Ig(),Lg(),lj(),qM=new Set,JM=5e3,YM=15e3,XM={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:n=>n.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).`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).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}).parserConfiguration({"populate--":!0}),handler:async n=>{let a=discoverWorkspaces(findWorkspaceRoot(process.cwd())??process.cwd()),S=n.exec===!0,C=n.script,N=n.args??[];if(!S){let a=(n[`--`]??[]).filter(n=>typeof n==`string`);a.length>0&&(N=[...N,...a])}if(S){let a=(n[`--`]??[]).filter(n=>typeof n==`string`);a.length>0&&(C?N=[...N,...a]:(C=a[0],N=[...N,...a.slice(1)])),C||(ke.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1))}let F=filterWorkspaces(a,{include:n.include,exclude:n.exclude,noPrivate:n.private===!1});if(!S){C||(ke.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1));let n=C;F=F.filter(a=>typeof(a.manifest.scripts??{})[n]==`string`)}if(F.length===0){ke.log(`gjsify foreach: no workspaces match (${S?`exec`:`script`}="${C}", include=${JSON.stringify(n.include??[])}, exclude=${JSON.stringify(n.exclude??[])})`);return}(n.topological||n[`topological-dev`])&&(F=topologicalSort(buildDependencyGraph(F,{includeDev:n[`topological-dev`]===!0})));let I=n.verbose===!0,H=C;try{if(n.parallel&&!n.topological&&!n[`topological-dev`]){let a=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runParallel(F,H,N,a,I,S)}else if(n.parallel){let a=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runTopologicalParallel(F,H,N,a,I,n[`topological-dev`]===!0,S)}else await runSequential(F,H,N,I,S)}catch(n){killActiveChildren(),ke.error(n.message),process.exit(1)}process.exit(0)}},__name$1(runOne$1,`runOne`),__name$1(detectPackageManager$1,`detectPackageManager`)});function collectTransitiveClosure(n,a,S){let C=new Map;for(let n of a)C.set(n.name,n);let N=new Set,F=[],I=[n];for(;I.length>0;){let n=I.pop();if(N.has(n.name))continue;N.add(n.name),F.push(n);let a=n.manifest,H=[a.dependencies,S?a.devDependencies:void 0,a.optionalDependencies];for(let n of H)if(n)for(let[a,S]of Object.entries(n)){if(typeof S!=`string`||!S.startsWith(`workspace:`))continue;let n=C.get(a);n&&(N.has(n.name)||I.push(n))}}return F}async function runOne(n,a,S,C,N){let F=C===`gjsify`?[`run`,a,...S]:[`run`,a,...S.length>0?[`--`,...S]:[]];N&&ke.error(`[${n.name}] $ ${C} ${F.join(` `)}`);let I=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`};await new Promise((a,S)=>{let N=spawn(C,F,{cwd:n.location,stdio:`inherit`,env:{...process.env,...I}});N.on(`close`,n=>{n===0?a():S(Error(`${C} ${F.join(` `)} exited with code ${n}`))}),N.on(`error`,S)})}function detectPackageManager(){let n=process.env.npm_config_user_agent??``;return n.startsWith(`yarn/`)?`yarn`:n.startsWith(`gjsify/`)?`gjsify`:`npm`}var QM,$M=__esmMin(()=>{Ae(),oC(),Ig(),Lg(),QM={command:`workspace <name> <script> [args..]`,description:"Run a workspace script (`yarn workspace <name> run <script>` equivalent).",builder:n=>n.positional(`name`,{description:"Workspace name (matches package.json `name` field).",type:`string`,demandOption:!0}).positional(`script`,{description:`Script name to run inside that workspace.`,type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments forwarded to the script.`,type:`string`,array:!0}).option(`with-dependencies`,{description:"Pre-build the target workspace's transitive workspace dependencies in topological order before running the script in the target. Deps that don't declare the script are skipped (--if-present behaviour). Replaces manual `gjsify workspace A build && gjsify workspace B build && …` chains.",type:`boolean`,alias:[`d`,`t`,`topological`],default:!1}).option(`include-dev`,{description:"When --with-dependencies is set, also walk devDependencies (production deps only by default — matches `gjsify foreach -t`).",type:`boolean`,default:!1}).option(`continue-on-error`,{description:`When --with-dependencies is set, keep running remaining deps after one fails (default: stop on first failure).`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}),handler:async n=>{let a=discoverWorkspaces(findWorkspaceRoot(process.cwd())??process.cwd()),S=a.find(a=>a.name===n.name);S||(ke.error(`gjsify workspace: no workspace named "${n.name}" — discovered ${a.length} workspace(s)`),process.exit(1));let C=detectPackageManager(),N=n.verbose===!0,F=n[`with-dependencies`]===!0,I=n[`continue-on-error`]===!0;typeof(S.manifest.scripts??{})[n.script]!=`string`&&(ke.error(`gjsify workspace: workspace "${n.name}" has no script "${n.script}"`),process.exit(1));let H;H=F?topologicalSort(buildDependencyGraph(collectTransitiveClosure(S,a,n[`include-dev`]===!0),{includeDev:n[`include-dev`]===!0})):[S];let W=[];for(let a of H){if(typeof(a.manifest.scripts??{})[n.script]!=`string`){N&&ke.error(`[${a.name}] (no "${n.script}" script — skipping)`);continue}try{await runOne(a,n.script,n.args??[],C,N)}catch(n){let S=n instanceof Error?n:Error(String(n));ke.error(`[${a.name}] ${S.message}`),I||process.exit(1),W.push({workspace:a.name,error:S})}}W.length>0&&(ke.error(`gjsify workspace: ${W.length} workspace(s) failed: ${W.map(n=>n.workspace).join(`, `)}`),process.exit(1)),process.exit(0)}}});async function runLifecycleScript(n,a,S,C={}){let N=(a.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${n}/package.json`)}let F=findWorkspaceRoot(n),I=[ns(n,`node_modules`,`.bin`)];F&&F!==n&&I.push(ns(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(ds),npm_lifecycle_event:S,npm_package_name:a.name??``,npm_package_version:a.version??``,...C.env},K=C.stdio===`inherit-stderr`?[`inherit`,2,2]:C.stdio??`inherit`;return await new Promise((a,C)=>{let F=spawn(N,[],{cwd:n,env:W,stdio:K,shell:!0});F.on(`close`,N=>{N===0?a():C(Error(`gjsify lifecycle-script: "${S}" in ${n} exited with code ${N}`))}),F.on(`error`,C)}),!0}var eN=__esmMin(()=>{oC(),ps(),Lg()});async function packWorkspace(n,a={}){let S=ns(n,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${n}`);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 ${n} has no "name"`);let H=a.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(n,N,S,{optional:!0,stdio:a.lifecycleStdio});let W=readFileSync(S,`utf-8`),K=W===C?N:JSON.parse(W),q=a.skipWorkspaceRewrite?K:rewriteWorkspaceDeps(K,n),Y=JSON.stringify(q,null,indentOf(W))+`
|
|
799
|
+
`);for(let a of n)ke.warn(` ✗ ${a.name}`);let a=buildInstallCommand(detectPackageManager$2(),n);a&&ke.warn(`\nInstall with:\n ${a}`)}else ke.log(`System dependencies OK.`);let a=detectNativePackages(process.cwd());if(a.length>0){ke.log(`\nDetected ${a.length} @gjsify/* package(s) with native prebuilds:`);for(let n of a)ke.log(` • ${n.name}`);ke.log("\nUse `gjsify run <bundle>` to launch with LD_LIBRARY_PATH/GI_TYPELIB_PATH set.")}maybeInstallGitHooks()}function maybeInstallGitHooks(){let n=process.cwd(),a=ns(n,`scripts`,`install-git-hooks.mjs`);if(existsSync(a)&&existsSync(ns(n,`.git`)))try{let S=spawnSync(process.execPath,[a,`--quiet`],{cwd:n,stdio:`inherit`,env:process.env});S.status!==0&&ke.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${S.status} — git hooks may not be active.`)}catch(n){ke.warn(`[gjsify install] git hook installation skipped: ${n instanceof Error?n.message:String(n)}`)}}var WM,GM,KM=__esmMin(()=>{Ae(),Zc(),ps(),oC(),Ig(),oj(),KA(),BM(),UM(),ZA(),WM=18e5,GM={command:`install [packages..]`,description:`Install npm dependencies in the current project (or globally with -g), then run gjsify-aware post-checks.`,builder:n=>n.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(`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:WM}),handler:async n=>{if(n.immutable&&(n.packages&&n.packages.length>0&&(ke.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1)),n.global&&(ke.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1)),n[`refresh-lockfile`]&&(ke.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1))),n.global){(!n.packages||n.packages.length===0)&&(ke.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1));for(let a of[`save-dev`,`save-peer`,`save-optional`])n[a]&&ke.warn(`gjsify install --global ignores --${a}: global installs do not modify a project package.json.`);await installGlobalAndLink(n.packages,{verbose:n.verbose});return}if((n.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(n),await runPostInstallChecks();return}let a=n.timeout>0?n.timeout:0,S=a>0?new AbortController:null,C=S===null?null:setTimeout(()=>S.abort(Error(`install-overall-timeout`)),a);try{await projectInstallNative(n,S?.signal),await runPostInstallChecks()}catch(n){if(S!==null&&S.signal.aborted&&isAbortedFromOverallTimeout(n)){let n=Math.round(a/100)/10;ke.error(`gjsify install: timed out after ${n}s — likely a registry slowdown.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw n}finally{C!==null&&clearTimeout(C)}}}});function readDirectChildren(n){let a;try{a=readdirSync(`/proc/${n}/task`)}catch{return null}let S=[],C=!1;for(let N of a)try{let a=readFileSync(`/proc/${n}/task/${N}/children`,`utf-8`);C=!0;for(let n of a.trim().split(/\s+/)){let a=Number(n);Number.isInteger(a)&&a>0&&S.push(a)}}catch{}return C?S:null}function buildPpidMap(){let n=new Map,a=[];try{a=readdirSync(`/proc`)}catch{return n}for(let S of a){let a=Number(S);if(!(!Number.isInteger(a)||a<=0))try{let S=readFileSync(`/proc/${a}/stat`,`utf-8`),C=S.slice(S.lastIndexOf(`)`)+2).split(` `),N=Number(C[1]);if(!Number.isInteger(N)||N<=0)continue;let F=n.get(N);F?F.push(a):n.set(N,[a])}catch{}}return n}function collectDescendants(n){let a=[],S=new Set([n]),C=[n],N=null;for(;C.length>0;){let n=C.shift(),F=readDirectChildren(n);F===null&&(N??=buildPpidMap(),F=N.get(n)??[]);for(let n of F)S.has(n)||(S.add(n),a.push(n),C.push(n))}return a}function signalTree(n,a,S){for(let n=a.length-1;n>=0;n--)try{process.kill(a[n],S)}catch{}try{n.kill(S)}catch{}}function killActiveChildren(){let n=new Map;for(let a of qM){let S=a.pid?collectDescendants(a.pid):[];n.set(a,S),signalTree(a,S,`SIGTERM`)}setTimeout(()=>{for(let a of qM){let S=new Set(a.pid?collectDescendants(a.pid):[]);for(let C of n.get(a)??[])S.add(C);signalTree(a,[...S],`SIGKILL`)}},JM).unref?.()}async function runSequential(n,a,S,C,N){for(let F of n)await runOne$1(F,a,S,!1,C,N)}async function runParallel(n,a,S,C,N,F){let I=0,H=[];for(let W=0;W<C;W++)H.push((async()=>{for(;I<n.length;)await runOne$1(n[I++],a,S,!0,N,F)})());await Promise.all(H)}async function runTopologicalParallel(n,a,S,C,N,F,I){let H=new Set(n.map(n=>n.name)),W=new Map;for(let a of n){let n=new Set,S=a.manifest;for(let a of[S.dependencies,F?S.devDependencies:void 0,S.optionalDependencies])if(a)for(let[S,C]of Object.entries(a))typeof C==`string`&&C.startsWith(`workspace:`)&&H.has(S)&&n.add(S);W.set(a.name,n)}let K=new Map(n.map(n=>[n.name,n])),q=n.length,Y=new Set,X=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((n,F)=>{let H=null,re=Date.now(),describeInflight=()=>[...ne.entries()].map(([n,a])=>`${n} (${Math.round((Date.now()-a)/1e3)}s)`).join(`, `),failFast=n=>{H||(H=n,killActiveChildren(),setTimeout(()=>settle(),YM).unref?.())},ae=setInterval(()=>{let n=Date.now()-re;n<3e5||ne.size===0||(ke.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(n/6e4)}min — in-flight: ${describeInflight()}`),n>=ie&&failFast(Error(`gjsify foreach: stalled — no workspace completed for ${Math.round(n/6e4)}min (override via GJSIFY_FOREACH_STALL_MINUTES); killed in-flight: ${describeInflight()}`)))},6e4);ae.unref?.();let settle=()=>{clearInterval(ae),H?F(H):n()},pump=()=>{if(!H){for(;X<C;){let n=[...W.entries()].filter(([,n])=>[...n].every(n=>Y.has(n))).map(([n])=>n);if(n.length===0)break;let C=n.sort()[0];W.delete(C),X++,ne.set(C,Date.now()),te&&ke.error(`[gjsify foreach] start ${C} (${Y.size}/${q} done, ${X} in flight)`),runOne$1(K.get(C),a,S,!0,N,I).then(()=>{Y.add(C)}).catch(n=>{failFast(n instanceof Error?n:Error(String(n)))}).finally(()=>{X--,ne.delete(C),re=Date.now(),H?X===0&&settle():W.size===0&&X===0?settle():pump()})}W.size>0&&X===0&&!H&&(clearInterval(ae),F(Error(`gjsify foreach --topological: stuck — workspaces ${[...W.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne$1(n,a,S,C,N,F){if(F){N&&ke.error(`[${n.name}] $ ${a} ${S.join(` `)}`),await spawnPrefixed(a,S,n.location,C?`[${n.name}] `:null);return}let I=detectPackageManager$1(),H=I===`gjsify`?[`run`,a,...S]:[`run`,a,...S.length>0?[`--`,...S]:[]];N&&ke.error(`[${n.name}] $ ${I} ${H.join(` `)}`),await spawnPrefixed(I,H,n.location,C?`[${n.name}] `:null)}function detectPackageManager$1(){if(isGjs())return`gjsify`;let n=process.env.npm_config_user_agent??``;return n.startsWith(`yarn/`)?`yarn`:n.startsWith(`gjsify/`)?`gjsify`:`npm`}function spawnPrefixed(n,a,S,C){let N=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`};return new Promise((F,I)=>{let H=spawn(n,a,{cwd:S,stdio:C?[`ignore`,`pipe`,`pipe`]:`inherit`,env:{...process.env,...N}});qM.add(H);let W=!process.stdout.isTTY,K=[];C&&H.stdout&&H.stderr&&(K.push(prefixLines(H.stdout,process.stdout,C,W)),K.push(prefixLines(H.stderr,process.stderr,C,W))),H.on(`close`,S=>{qM.delete(H);for(let n of K)n();S===0?F():I(Error(`${n} ${a.join(` `)} exited with code ${S}`))}),H.on(`error`,n=>{qM.delete(H),I(n)})})}var qM,JM,YM,XM,ZM=__esmMin(()=>{Ae(),oC(),Zc(),Wp(),Ig(),Lg(),lj(),zg(),qM=new Set,JM=5e3,YM=15e3,XM={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:n=>n.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).`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).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}).parserConfiguration({"populate--":!0}),handler:async n=>{let a=discoverWorkspaces(findWorkspaceRoot(process.cwd())??process.cwd()),S=n.exec===!0,C=n.script,N=n.args??[];if(!S){let a=(n[`--`]??[]).filter(n=>typeof n==`string`);a.length>0&&(N=[...N,...a])}if(S){let a=(n[`--`]??[]).filter(n=>typeof n==`string`);a.length>0&&(C?N=[...N,...a]:(C=a[0],N=[...N,...a.slice(1)])),C||(ke.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1))}let F=filterWorkspaces(a,{include:n.include,exclude:n.exclude,noPrivate:n.private===!1});if(!S){C||(ke.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1));let n=C;F=F.filter(a=>typeof(a.manifest.scripts??{})[n]==`string`)}if(F.length===0){ke.log(`gjsify foreach: no workspaces match (${S?`exec`:`script`}="${C}", include=${JSON.stringify(n.include??[])}, exclude=${JSON.stringify(n.exclude??[])})`);return}(n.topological||n[`topological-dev`])&&(F=topologicalSort(buildDependencyGraph(F,{includeDev:n[`topological-dev`]===!0})));let I=n.verbose===!0,H=C;try{if(n.parallel&&!n.topological&&!n[`topological-dev`]){let a=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runParallel(F,H,N,a,I,S)}else if(n.parallel){let a=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runTopologicalParallel(F,H,N,a,I,n[`topological-dev`]===!0,S)}else await runSequential(F,H,N,I,S)}catch(n){killActiveChildren(),ke.error(n.message),process.exit(1)}process.exit(0)}},__name$1(runOne$1,`runOne`),__name$1(detectPackageManager$1,`detectPackageManager`)});function collectTransitiveClosure(n,a,S){let C=new Map;for(let n of a)C.set(n.name,n);let N=new Set,F=[],I=[n];for(;I.length>0;){let n=I.pop();if(N.has(n.name))continue;N.add(n.name),F.push(n);let a=n.manifest,H=[a.dependencies,S?a.devDependencies:void 0,a.optionalDependencies];for(let n of H)if(n)for(let[a,S]of Object.entries(n)){if(typeof S!=`string`||!S.startsWith(`workspace:`))continue;let n=C.get(a);n&&(N.has(n.name)||I.push(n))}}return F}async function runOne(n,a,S,C,N){let F=C===`gjsify`?[`run`,a,...S]:[`run`,a,...S.length>0?[`--`,...S]:[]];N&&ke.error(`[${n.name}] $ ${C} ${F.join(` `)}`);let I=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`};await new Promise((a,S)=>{let N=spawn(C,F,{cwd:n.location,stdio:`inherit`,env:{...process.env,...I}});N.on(`close`,n=>{n===0?a():S(Error(`${C} ${F.join(` `)} exited with code ${n}`))}),N.on(`error`,S)})}function detectPackageManager(){if(isGjs())return`gjsify`;let n=process.env.npm_config_user_agent??``;return n.startsWith(`yarn/`)?`yarn`:n.startsWith(`gjsify/`)?`gjsify`:`npm`}var QM,$M=__esmMin(()=>{Ae(),oC(),Ig(),Lg(),zg(),QM={command:`workspace <name> <script> [args..]`,description:"Run a workspace script (`yarn workspace <name> run <script>` equivalent).",builder:n=>n.positional(`name`,{description:"Workspace name (matches package.json `name` field).",type:`string`,demandOption:!0}).positional(`script`,{description:`Script name to run inside that workspace.`,type:`string`,demandOption:!0}).positional(`args`,{description:`Extra arguments forwarded to the script.`,type:`string`,array:!0}).option(`with-dependencies`,{description:"Pre-build the target workspace's transitive workspace dependencies in topological order before running the script in the target. Deps that don't declare the script are skipped (--if-present behaviour). Replaces manual `gjsify workspace A build && gjsify workspace B build && …` chains.",type:`boolean`,alias:[`d`,`t`,`topological`],default:!1}).option(`include-dev`,{description:"When --with-dependencies is set, also walk devDependencies (production deps only by default — matches `gjsify foreach -t`).",type:`boolean`,default:!1}).option(`continue-on-error`,{description:`When --with-dependencies is set, keep running remaining deps after one fails (default: stop on first failure).`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}),handler:async n=>{let a=discoverWorkspaces(findWorkspaceRoot(process.cwd())??process.cwd()),S=a.find(a=>a.name===n.name);S||(ke.error(`gjsify workspace: no workspace named "${n.name}" — discovered ${a.length} workspace(s)`),process.exit(1));let C=detectPackageManager(),N=n.verbose===!0,F=n[`with-dependencies`]===!0,I=n[`continue-on-error`]===!0;typeof(S.manifest.scripts??{})[n.script]!=`string`&&(ke.error(`gjsify workspace: workspace "${n.name}" has no script "${n.script}"`),process.exit(1));let H;H=F?topologicalSort(buildDependencyGraph(collectTransitiveClosure(S,a,n[`include-dev`]===!0),{includeDev:n[`include-dev`]===!0})):[S];let W=[];for(let a of H){if(typeof(a.manifest.scripts??{})[n.script]!=`string`){N&&ke.error(`[${a.name}] (no "${n.script}" script — skipping)`);continue}try{await runOne(a,n.script,n.args??[],C,N)}catch(n){let S=n instanceof Error?n:Error(String(n));ke.error(`[${a.name}] ${S.message}`),I||process.exit(1),W.push({workspace:a.name,error:S})}}W.length>0&&(ke.error(`gjsify workspace: ${W.length} workspace(s) failed: ${W.map(n=>n.workspace).join(`, `)}`),process.exit(1)),process.exit(0)}}});async function runLifecycleScript(n,a,S,C={}){let N=(a.scripts??{})[S];if(typeof N!=`string`){if(C.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${S}" in ${n}/package.json`)}let F=findWorkspaceRoot(n),I=[ns(n,`node_modules`,`.bin`)];F&&F!==n&&I.push(ns(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(ds),npm_lifecycle_event:S,npm_package_name:a.name??``,npm_package_version:a.version??``,...C.env},K=C.stdio===`inherit-stderr`?[`inherit`,2,2]:C.stdio??`inherit`;return await new Promise((a,C)=>{let F=spawn(N,[],{cwd:n,env:W,stdio:K,shell:!0});F.on(`close`,N=>{N===0?a():C(Error(`gjsify lifecycle-script: "${S}" in ${n} exited with code ${N}`))}),F.on(`error`,C)}),!0}var eN=__esmMin(()=>{oC(),ps(),Lg()});async function packWorkspace(n,a={}){let S=ns(n,`package.json`);if(!existsSync(S))throw Error(`gjsify pack: no package.json at ${n}`);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 ${n} has no "name"`);let H=a.lifecycleScripts??[`prepack`];for(let S of H)await runLifecycleScript(n,N,S,{optional:!0,stdio:a.lifecycleStdio});let W=readFileSync(S,`utf-8`),K=W===C?N:JSON.parse(W),q=a.skipWorkspaceRewrite?K:rewriteWorkspaceDeps(K,n),Y=JSON.stringify(q,null,indentOf(W))+`
|
|
800
800
|
`,X=collectFiles(n,K),te=[{name:`package/`,directory:!0,mode:493}],ne=[],re=0;for(let a of X){let S;S=a===`package.json`?new TextEncoder().encode(Y):new Uint8Array(readFileSync(ns(n,a)));let C=statSync(ns(n,a)).mode&511;te.push({name:`package/${a}`,body:S,mode:C,mtime:0}),ne.push({path:a,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`),Z=`sha512-${createHash(`sha512`).update(ie).digest(`base64`)}`,se=a.destination?$o(a.destination):n,ce=ns(se,ae);return a.dryRun||(mkdirSync(se,{recursive:!0}),writeFileSync(ce,ie)),{filename:ae,name:F,version:I,size:ie.byteLength,unpackedSize:re,shasum:oe,integrity:Z,entryCount:ne.length,files:ne,absolutePath:a.dryRun?null:ce}}function collectFiles(n,a){let S=forceIncluded(a),C=Array.isArray(a.files)?a.files.filter(n=>typeof n==`string`):null,N;N=C?expandFilesPatterns(n,C):walkAll(n);let F=loadIgnore(n),I=new Set;for(let n of N)F(n)||I.add(n);for(let a of S)existsSync(ns(n,a))&&I.add(a);return[...I].sort()}function forceIncluded(n){let a=new Set;a.add(`package.json`);for(let n of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])a.add(n);let S=typeof n.main==`string`?n.main:null;S&&a.add(S.replace(/^\.\//,``));let C=n.bin;if(typeof C==`string`)a.add(C.replace(/^\.\//,``));else if(C&&typeof C==`object`)for(let n of Object.values(C))typeof n==`string`&&a.add(n.replace(/^\.\//,``));return[...a]}function walkAll(n,a=``){let S=[],C=a?ns(n,a):n,N;try{N=readdirSync(C,{withFileTypes:!0})}catch{return S}for(let C of N){if(nN.has(C.name)||C.name.startsWith(`.tsbuildinfo`))continue;let N=a?`${a}/${C.name}`:C.name;C.isDirectory()?S.push(...walkAll(n,N)):C.isFile()&&S.push(N)}return S}function expandFilesPatterns(n,a){let S=new Set,C=null;for(let N of a){let a=N.replace(/^\.\//,``).replace(/\/$/,``);if(!a)continue;if(!/[*?[\]]/.test(a)){let C=ns(n,a);if(!existsSync(C))continue;let N=statSync(C);if(N.isDirectory())for(let C of walkAll(n,a))S.add(C);else N.isFile()&&S.add(a);continue}C??=walkAll(n);let F=filesGlobToRegExp(a),I=filesGlobToRegExp(`${a}/**`);for(let n of C)(F.test(n)||I.test(n))&&S.add(n)}return[...S]}function filesGlobToRegExp(n){let a=`^`;for(let S=0;S<n.length;S++){let C=n[S];if(C===`*`)n[S+1]===`*`?(a+=`.*`,S++,n[S+1]===`/`&&S++):a+=`[^/]*`;else if(C===`?`)a+=`[^/]`;else if(C===`[`){let C=S+1,N=`[`;for(n[C]===`!`&&(N+=`^`,C++);C<n.length&&n[C]!==`]`;C++)N+=n[C];C<n.length?(a+=`${N}]`,S=C):a+=`\\[`}else ".+^${}()|\\]".includes(C)?a+=`\\${C}`:a+=C}return RegExp(`${a}$`)}function loadIgnore(n){let a=ns(n,`.npmignore`),S=ns(n,`.gitignore`),C=[],N=existsSync(a)?a:existsSync(S)?S:null;if(N){let n=readFileSync(N,`utf-8`).split(`
|
|
801
801
|
`);for(let a of n){let n=a.trim();!n||n.startsWith(`#`)||n.startsWith(`!`)||C.push(globToRegex(n))}}return n=>{for(let a of C)if(a.test(n))return!0;return!1}}function globToRegex(n){let a=n.replace(/^\//,``);return a=a.replace(/[.+^${}()|[\]\\]/g,`\\$&`),a=a.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),a=a.replace(/\?/g,`[^/]`),RegExp(`^${a}($|/)`)}function rewriteWorkspaceDeps(n,a){let S=findWorkspaceRoot(a);if(!S)return n;let C=new Map;for(let n of discoverWorkspaces(S))n.name&&n.version&&C.set(n.name,n.version);let N=JSON.parse(JSON.stringify(n));for(let n of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let a=N[n];if(a)for(let[n,F]of Object.entries(a)){if(typeof F!=`string`||!F.startsWith(`workspace:`))continue;let I=C.get(n);if(!I)throw Error(`gjsify pack: ${N.name} declares workspace:^ on ${n} but no sibling workspace with that name exists in the monorepo at ${S}`);let H=F.slice(10);H===`*`||H===``?a[n]=I:H===`^`||H===`~`?a[n]=`${H}${I}`:a[n]=H}}return N}function indentOf(n){let a=n.match(/\n([ \t]+)"/);return a?a[1]:` `}var tN,nN,rN=__esmMin(()=>{Zc(),ao(),ps(),OM(),Ig(),Lg(),eN(),tN={command:`pack [path]`,description:`Produce an npm-compatible .tgz tarball for the workspace at <path> (default: cwd). Rewrites workspace:^/~/* deps to resolved versions.`,builder:n=>n.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 n=>{let a=await packWorkspace($o(n.path??process.cwd()),{destination:n[`pack-destination`],dryRun:n[`dry-run`]===!0,lifecycleScripts:n[`ignore-scripts`]?[]:[`prepack`],lifecycleStdio:n.json?`inherit-stderr`:`inherit`});n.json?process.stdout.write(`${JSON.stringify([a],null,2)}\n`):process.stdout.write(`${a.filename}\n`)}},nN=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`])});function escapePackageName(n){return n.replace(`/`,`%2f`)}function buildPublishHeaders(n,a){let S=buildHeaders(n,{npmrc:a.npmrc});return S[`content-type`]=`application/json`,S[`npm-command`]=`publish`,S[`npm-auth-type`]=a.otp?`legacy`:`web`,S[`user-agent`]=a.userAgent??defaultUserAgent(),a.otp&&(S[`npm-otp`]=a.otp),a.authorization&&(S.authorization=a.authorization),S}function defaultUserAgent(){let n=globalThis.process,a=n?.arch??`x64`;return`gjsify-publish/0.5.0 (${n?.platform??`linux`} ${a})`}var iN=__esmMin(()=>{CM()});function decodeJwtPayload(n){let a=n.split(`.`);if(a.length!==3)return null;try{let n=a[1].replace(/-/g,`+`).replace(/_/g,`/`),S=typeof atob==`function`?atob(n):Buffer.from(n,`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(n,a){let S=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,C=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!S||!C)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 N=`${S}${S.includes(`?`)?`&`:`?`}audience=${encodeURIComponent(n)}`;a?.(`gjsify oidc: GET ${N.replace(C,`<bearer>`)}`);let F=await fetch(N,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${C}`}});if(!F.ok){let n=await F.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${F.status} ${F.statusText} — ${n.slice(0,200)}`,`fetch-id-token`)}let I=await F.json().catch(()=>({}));if(!I.value)throw new OidcUnavailableError("GitHub OIDC response missing `value` field",`no-id-token`);return I.value}async function exchangeOidcForNpmToken(n){let{packageName:a,registry:S,idToken:C,log:N}=n,F=`${S.endsWith(`/`)?S.slice(0,-1):S}/-/npm/v1/oidc/token/exchange/package/${a.startsWith(`@`)?(()=>{let n=a.indexOf(`/`),S=a.slice(1,n),C=a.slice(n+1);return`@${encodeURIComponent(S)}%2f${encodeURIComponent(C)}`})():encodeURIComponent(a)}`;N?.(`gjsify oidc: POST ${F}`);let I=n.maxRetries??3,H=n.retryBaseMs??1e3;for(let n=0;;n++){let S;try{S=await fetch(F,{method:`POST`,headers:{Authorization:`Bearer ${C}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`})}catch(S){if(n<I){let S=Math.min(H*2**n,8e3);N?.(`gjsify oidc: network error for ${a} (attempt ${n+1}/${I+1}), retrying in ${S}ms`),await sleep(S);continue}throw new OidcExchangeError(`npm OIDC token exchange network error for ${a} after ${n+1} attempt(s): ${S instanceof Error?S.message:String(S)}`,0,``,a,decodeJwtPayload(C)??void 0)}let W=await S.text().catch(()=>``);if(!S.ok){if(aN.has(S.status)&&n<I){let C=Math.min(H*2**n,8e3);N?.(`gjsify oidc: transient ${S.status} ${S.statusText} for ${a} (attempt ${n+1}/${I+1}), retrying in ${C}ms`),await sleep(C);continue}throw new OidcExchangeError(`npm OIDC token exchange failed for ${a}: ${S.status} ${S.statusText} — ${W.slice(0,300)}`,S.status,W,a,decodeJwtPayload(C)??void 0)}let K;try{K=JSON.parse(W)}catch{throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${a}: ${W.slice(0,200)}`,S.status,W,a)}if(!K.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${a}`,S.status,W,a);return K.token}}async function getNpmTrustedToken(n){let a=`npm:${new URL(n.registry).hostname}`,S=await fetchGithubOidcToken(a,n.log);return{token:await exchangeOidcForNpmToken({...n,idToken:S}),audience:a}}var aN,sleep,OidcUnavailableError,OidcExchangeError,oN=__esmMin(()=>{aN=new Set([408,425,429,500,502,503,504]),sleep=n=>new Promise(a=>setTimeout(a,n)),OidcUnavailableError=class extends Error{reason;constructor(n,a){super(n),this.reason=a,this.name=`OidcUnavailableError`}},OidcExchangeError=class extends Error{status;body;packageName;claims;constructor(n,a,S,C,N){super(n),this.status=a,this.body=S,this.packageName=C,this.claims=N,this.name=`OidcExchangeError`}}});async function diagnose404(n){let{packageName:a,version:S,registry:C,npmrc:N}=n,F={};try{F=await whoami(C,N)}catch{return{reason:`unknown`,message:formatUnknown(a,S)}}return F.username&&F.username.length>0?{reason:`live-token-404`,username:F.username,message:formatLiveToken404(a,S,F.username)}:{reason:`dead-token`,message:formatDeadToken(a,S)}}function formatDeadToken(n,a){return[`gjsify publish: ${n}@${a} — 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(`
|
|
802
802
|
`)}function formatLiveToken404(n,a,S){return[`gjsify publish: ${n}@${a} — 404 Not Found`,``,`Authenticated as: ${S}`,``,`Your token authenticates, so this is NOT a dead-token problem. The package`,`${n} 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(`
|
|
@@ -840,4 +840,4 @@ await runStorybook({
|
|
|
840
840
|
applicationId: ${JSON.stringify(a)},${F}
|
|
841
841
|
stories: collectStoryModules([${N}]),
|
|
842
842
|
});
|
|
843
|
-
`}var iP,aP=__esmMin(()=>{Ae(),oC(),Zc(),ps(),iP={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:n=>n.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(`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 n=>{let a=process.cwd(),S=readPackage(a),C=S.gjsify?.storybook??{},N=$o(a,n.stories??C.stories??`src`),F=n.appId??C.applicationId??deriveAppId(S.name),I=n.title??C.title,H=n.globals??C.globals??`auto`,W=ns(a,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(W,{recursive:!0});let K=ns(W,`entry.ts`),q=n.out?$o(a,n.out):ns(W,`storybook.gjs.mjs`),writeEntry=()=>{let n=findStoryFiles(N).sort();return writeFileSync(K,generateEntry(n,F,I)),n.length},Y=writeEntry();Y===0&&(ke.error(`No *.story.ts files found under ${rs(a,N)||N}`),process.exit(1)),ke.log(`Found ${Y} story file(s) under ${rs(a,N)||`.`}`);let{runCli:X}=await Promise.resolve().then(()=>(
|
|
843
|
+
`}var iP,aP=__esmMin(()=>{Ae(),oC(),Zc(),ps(),iP={command:`storybook`,description:`Discover *.story.ts in this project and launch the GTK storybook browser.`,builder:n=>n.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(`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 n=>{let a=process.cwd(),S=readPackage(a),C=S.gjsify?.storybook??{},N=$o(a,n.stories??C.stories??`src`),F=n.appId??C.applicationId??deriveAppId(S.name),I=n.title??C.title,H=n.globals??C.globals??`auto`,W=ns(a,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(W,{recursive:!0});let K=ns(W,`entry.ts`),q=n.out?$o(a,n.out):ns(W,`storybook.gjs.mjs`),writeEntry=()=>{let n=findStoryFiles(N).sort();return writeFileSync(K,generateEntry(n,F,I)),n.length},Y=writeEntry();Y===0&&(ke.error(`No *.story.ts files found under ${rs(a,N)||N}`),process.exit(1)),ke.log(`Found ${Y} story file(s) under ${rs(a,N)||`.`}`);let{runCli:X}=await Promise.resolve().then(()=>(uP(),lP)),buildBundle=()=>X([`build`,K,`--app`,`gjs`,`--globals`,H,`--outfile`,q]);if(!n.watch){if(await buildBundle(),n.buildOnly)return;let{runGjsBundle:a}=await Promise.resolve().then(()=>(JA(),qA));await a(q,[],{exitOnSuccess:!0});return}let{watch:te}=await Promise.resolve().then(()=>(Zc(),Jc)),ne=null,re=!1,ie=!1,rebuild=async()=>{if(re){ie=!0;return}re=!0;try{writeEntry(),ne&&=(ne.kill(),null),await buildBundle(),n.buildOnly||(ne=spawn(`gjs`,[`-m`,q],{stdio:`inherit`}))}catch(n){ke.error(`[storybook] rebuild failed: ${n.message}`)}finally{re=!1,ie&&(ie=!1,rebuild())}};await rebuild();let ae=null;te(N,{recursive:!0},()=>{ae&&clearTimeout(ae),ae=setTimeout(()=>void rebuild(),200)}),ke.log(`[storybook] watching ${rs(a,N)||`.`} — press Ctrl+C to stop`)}}}),oP=__esmMin(()=>{GA(),XA(),$A(),tj(),cj(),dj(),mj(),Cj(),Ej(),kj(),Mj(),cM(),HM(),KM(),ZM(),$M(),rN(),uN(),fN(),yN(),xN(),TN(),ON(),jN(),NN(),FN(),LN(),zN(),GN(),XN(),QN(),rP(),aP()});function ensureGjsifyShimOnPath(){if(sP||!isGjs())return;sP=!0;let n=process.env.GJSIFY_SHIM_DIR;if(n&&existsSync(ns(n,`gjsify`))){(process.env.PATH??``).split(ds).includes(n)||(process.env.PATH=n+ds+(process.env.PATH??``));return}let a=fileURLToPath(import.meta.url),S=process.env.GJS_CONSOLE||`gjs`,C=mkdtempSync(ns(tmpdir(),`gjsify-shim-`)),N=ns(C,`gjsify`);writeFileSync(N,`#!/bin/sh\nexec "${S}" -m "${a}" "$@"\n`,{mode:493}),chmodSync(N,493),process.env.GJSIFY_SHIM_DIR=C,process.env.PATH=C+ds+(process.env.PATH??``)}var sP,cP=__esmMin(()=>{Zc(),Wp(),ps(),mn(),zg(),sP=!1}),lP=__exportAll$3({runCli:()=>runCli});function runtimeLabel(){try{let n=globalThis.imports?.system;if(n?.version!==void 0){let a=Number(n.version);return`GJS ${Math.floor(a/1e4)}.${Math.floor(a%1e4/100)}.${a%100} (SpiderMonkey)`}}catch{}return isNode()?`Node.js ${process.version}`:`unknown runtime`}function readBundleVersion(){try{let n=as(fileURLToPath(import.meta.url)),a=JSON.parse(readFileSync(ns(n,`..`,`package.json`),`utf8`));return typeof a.version==`string`?a.version:`unknown`}catch{return`unknown`}}async function runCli(n){ensureGjsifyShimOnPath();let a=Zd(n);await a.scriptName($d).version(readBundleVersion()).strict().wrap(a.terminalWidth()).command(Sj.command,Sj.description,Sj.builder,Sj.handler).command(GM.command,GM.description,GM.builder,GM.handler).command(WA.command,WA.description,WA.builder,WA.handler).command(YA.command,YA.description,YA.builder,YA.handler).command(QA.command,QA.description,QA.builder,QA.handler).command(VM.command,VM.description,VM.builder,VM.handler).command(ej.command,ej.description,ej.builder,ej.handler).command(sj.command,sj.description,sj.builder,sj.handler).command(uj.command,uj.description,uj.builder,uj.handler).command(pj.command,pj.description,pj.builder,pj.handler).command(Tj.command,Tj.description,Tj.builder,Tj.handler).command(Oj.command,Oj.description,Oj.builder,Oj.handler).command(jj.command,jj.description,jj.builder,jj.handler).command(sM.command,sM.description,sM.builder,sM.handler).command(XM.command,XM.description,XM.builder,XM.handler).command(QM.command,QM.description,QM.builder,QM.handler).command(tN.command,tN.description,tN.builder,tN.handler).command(lN.command,lN.description,lN.builder,lN.handler).command(dN.command,dN.description,dN.builder,dN.handler).command(vN.command,vN.description,vN.builder,vN.handler).command(bN.command,bN.description,bN.builder,bN.handler).command(wN.command,wN.description,wN.builder,wN.handler).command(DN.command,DN.description,DN.builder,DN.handler).command(AN.command,AN.description,AN.builder,AN.handler).command(MN.command,MN.description,MN.builder,MN.handler).command(HN.command,HN.description,HN.builder,HN.handler).command(PN.command,PN.description,PN.builder,PN.handler).command(IN.command,IN.description,IN.builder,IN.handler).command(RN.command,RN.description,RN.builder,RN.handler).command(YN.command,YN.description,YN.builder,YN.handler).command(ZN.command,ZN.description,ZN.builder,ZN.handler).command($N.command,$N.description,$N.builder,$N.handler).command(iP.command,iP.description,iP.builder,iP.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var uP=__esmMin(()=>{Zc(),ps(),mn(),Qd(),oP(),ef(),zg(),cP()});uP(),await runCli(hideBin(process.argv));
|
package/lib/cli-app.js
CHANGED
|
@@ -22,6 +22,7 @@ import yargs from 'yargs';
|
|
|
22
22
|
import { buildCommand as build, testCommand as test, runCommand as run, infoCommand as info, systemCheckCommand as systemCheck, checkCommand as check, showcaseCommand as showcase, createCommand as create, gresourceCommand as gresource, gettextCommand as gettext, gsettingsCommand as gsettings, flatpakCommand as flatpak, dlxCommand as dlx, installCommand as install, foreachCommand as foreach, workspaceCommand as workspace, packCommand as pack, publishCommand as publish, whoamiCommand as whoami, loginCommand as login, logoutCommand as logout, trustCommand as trust, selfUpdateCommand as selfUpdate, generateInstallerCommand as generateInstaller, uninstallCommand as uninstall, formatCommand as format, lintCommand as lint, fixCommand as fix, upgradeCommand as upgrade, barrelsCommand as barrels, tscCommand as tsc, affectedCommand as affected, storybookCommand as storybook, } from './commands/index.js';
|
|
23
23
|
import { APP_NAME } from './constants.js';
|
|
24
24
|
import { isNode } from '@gjsify/rolldown-plugin-gjsify/runtime';
|
|
25
|
+
import { ensureGjsifyShimOnPath } from './utils/gjsify-shim.js';
|
|
25
26
|
// Detect which runtime is executing the CLI (GJS or Node.js).
|
|
26
27
|
// GJS MUST be checked first because @gjsify/process sets
|
|
27
28
|
// `process.versions.node = '20.0.0'` for compatibility — a plain
|
|
@@ -68,6 +69,11 @@ function readBundleVersion() {
|
|
|
68
69
|
* exit before any async work runs.
|
|
69
70
|
*/
|
|
70
71
|
export async function runCli(argv) {
|
|
72
|
+
// Under GJS, make a GJS-runnable `gjsify` available on PATH for child
|
|
73
|
+
// processes (workspace/foreach orchestration + compound `gjsify run`
|
|
74
|
+
// scripts) so node-free builds don't fall back to the Node bin. No-op on
|
|
75
|
+
// Node.
|
|
76
|
+
ensureGjsifyShimOnPath();
|
|
71
77
|
const cli = yargs(argv);
|
|
72
78
|
await cli
|
|
73
79
|
.scriptName(APP_NAME)
|
package/lib/commands/foreach.js
CHANGED
|
@@ -14,6 +14,7 @@ import { cpus } from 'node:os';
|
|
|
14
14
|
import { buildDependencyGraph, discoverWorkspaces, filterWorkspaces, topologicalSort, } from '@gjsify/workspace';
|
|
15
15
|
import { findWorkspaceRoot } from '../utils/workspace-root.js';
|
|
16
16
|
import { prefixLines } from '../utils/prefixed-output.js';
|
|
17
|
+
import { isGjs } from '@gjsify/rolldown-plugin-gjsify/runtime';
|
|
17
18
|
// Every child spawned by spawnPrefixed registers here so fail-fast can
|
|
18
19
|
// terminate the whole in-flight set instead of waiting on it. On CI a
|
|
19
20
|
// single failed package used to leave foreach awaiting its still-running
|
|
@@ -520,6 +521,11 @@ async function runOne(ws, script, args, prefixOutput, verbose, exec) {
|
|
|
520
521
|
await spawnPrefixed(runner, argv, ws.location, prefixOutput ? `[${ws.name}] ` : null);
|
|
521
522
|
}
|
|
522
523
|
function detectPackageManager() {
|
|
524
|
+
// Under GJS there is no Node — neither `npm` nor `yarn` can run scripts, so
|
|
525
|
+
// the runner is `gjsify` itself via the GJS shim on PATH
|
|
526
|
+
// (`ensureGjsifyShimOnPath`). Makes node-free `gjsify foreach` work.
|
|
527
|
+
if (isGjs())
|
|
528
|
+
return 'gjsify';
|
|
523
529
|
// `npm_config_user_agent` is set by npm/yarn/pnpm — first token is
|
|
524
530
|
// `<name>/<version>`. Reuse it so `gjsify foreach build` invoked
|
|
525
531
|
// through `yarn run` keeps using yarn, etc.
|
package/lib/commands/run.js
CHANGED
|
@@ -127,6 +127,15 @@ async function runScript(script, extraArgs) {
|
|
|
127
127
|
if (monorepoRoot && monorepoRoot !== cwd) {
|
|
128
128
|
binDirs.push(join(monorepoRoot, 'node_modules', '.bin'));
|
|
129
129
|
}
|
|
130
|
+
// Under GJS, the GJS-runnable `gjsify` shim (see `ensureGjsifyShimOnPath`)
|
|
131
|
+
// MUST shadow the workspace `node_modules/.bin/gjsify`, which is the Node
|
|
132
|
+
// entry and unusable in a node-free sandbox. So put the shim dir ahead of
|
|
133
|
+
// the `.bin` dirs in the child's PATH — otherwise a compound script like
|
|
134
|
+
// `gjsify run a && gjsify run b` resolves `gjsify` to the Node bin and
|
|
135
|
+
// fails. `GJSIFY_SHIM_DIR` is only set under GJS, so this is a no-op on Node.
|
|
136
|
+
if (process.env.GJSIFY_SHIM_DIR) {
|
|
137
|
+
binDirs.unshift(process.env.GJSIFY_SHIM_DIR);
|
|
138
|
+
}
|
|
130
139
|
// Default FORCE_COLOR=1 when not already set, matching yarn / npm
|
|
131
140
|
// script-runner behaviour. Without this, tools that check
|
|
132
141
|
// `process.stdout.isTTY` (chalk, picocolors, biome, …) disable colors
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
import { spawn } from 'node:child_process';
|
|
18
18
|
import { buildDependencyGraph, discoverWorkspaces, topologicalSort, } from '@gjsify/workspace';
|
|
19
19
|
import { findWorkspaceRoot } from '../utils/workspace-root.js';
|
|
20
|
+
import { isGjs } from '@gjsify/rolldown-plugin-gjsify/runtime';
|
|
20
21
|
export const workspaceCommand = {
|
|
21
22
|
command: 'workspace <name> <script> [args..]',
|
|
22
23
|
description: 'Run a workspace script (`yarn workspace <name> run <script>` equivalent).',
|
|
@@ -203,6 +204,12 @@ async function runOne(ws, script, extraArgs, runner, verbose) {
|
|
|
203
204
|
});
|
|
204
205
|
}
|
|
205
206
|
function detectPackageManager() {
|
|
207
|
+
// Under GJS there is no Node, so neither `npm` nor `yarn` can run scripts —
|
|
208
|
+
// the only option is `gjsify` itself, resolved via the GJS shim on PATH
|
|
209
|
+
// (see `ensureGjsifyShimOnPath`). This is what makes node-free multi-package
|
|
210
|
+
// orchestration work in the Flatpak sandbox.
|
|
211
|
+
if (isGjs())
|
|
212
|
+
return 'gjsify';
|
|
206
213
|
const ua = process.env.npm_config_user_agent ?? '';
|
|
207
214
|
if (ua.startsWith('yarn/'))
|
|
208
215
|
return 'yarn';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ensure a GJS-runnable `gjsify` is on `process.env.PATH` for child processes.
|
|
3
|
+
* Idempotent per process; children inherit the shim via `GJSIFY_SHIM_DIR` and
|
|
4
|
+
* reuse it instead of creating their own. No-op when not running under GJS.
|
|
5
|
+
*/
|
|
6
|
+
export declare function ensureGjsifyShimOnPath(): void;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Node-free orchestration: a GJS-runnable `gjsify` on PATH.
|
|
2
|
+
//
|
|
3
|
+
// The CLI's npm `bin` (`node_modules/.bin/gjsify`) is the NODE entry — useless
|
|
4
|
+
// in a node-free environment (the Flatpak sandbox has no Node). But multi-
|
|
5
|
+
// package orchestration and compound package scripts resolve `gjsify` from
|
|
6
|
+
// PATH and would hit that Node bin:
|
|
7
|
+
// - `gjsify workspace`/`foreach` spawn `<pm> run <script>` per package; under
|
|
8
|
+
// GJS the package manager is `gjsify` itself, and `spawn('gjsify', …)`
|
|
9
|
+
// searches PATH.
|
|
10
|
+
// - a compound script like `gjsify run a && gjsify run b` is executed via
|
|
11
|
+
// `/bin/sh -c …`, and the shell resolves each `gjsify` from PATH.
|
|
12
|
+
// Both fail without Node (`spawn npm ENOENT`, `gjsify: not found`).
|
|
13
|
+
//
|
|
14
|
+
// Fix: under GJS, write a tiny wrapper that re-invokes the running GJS bundle
|
|
15
|
+
// under `gjs -m`, and prepend its directory to `process.env.PATH` so every
|
|
16
|
+
// child process (and grandchild, via the inherited `GJSIFY_SHIM_DIR` marker)
|
|
17
|
+
// resolves `gjsify` to a GJS-runnable executable. No-op on Node.
|
|
18
|
+
import { mkdtempSync, writeFileSync, chmodSync, existsSync } from 'node:fs';
|
|
19
|
+
import { tmpdir } from 'node:os';
|
|
20
|
+
import { join, delimiter } from 'node:path';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
import { isGjs } from '@gjsify/rolldown-plugin-gjsify/runtime';
|
|
23
|
+
let _ensured = false;
|
|
24
|
+
/**
|
|
25
|
+
* Ensure a GJS-runnable `gjsify` is on `process.env.PATH` for child processes.
|
|
26
|
+
* Idempotent per process; children inherit the shim via `GJSIFY_SHIM_DIR` and
|
|
27
|
+
* reuse it instead of creating their own. No-op when not running under GJS.
|
|
28
|
+
*/
|
|
29
|
+
export function ensureGjsifyShimOnPath() {
|
|
30
|
+
if (_ensured || !isGjs())
|
|
31
|
+
return;
|
|
32
|
+
_ensured = true;
|
|
33
|
+
// A parent gjsify (also under GJS) already created the shim — reuse it so
|
|
34
|
+
// nested orchestration doesn't pile up temp dirs / PATH entries.
|
|
35
|
+
const inherited = process.env.GJSIFY_SHIM_DIR;
|
|
36
|
+
if (inherited && existsSync(join(inherited, 'gjsify'))) {
|
|
37
|
+
if (!(process.env.PATH ?? '').split(delimiter).includes(inherited)) {
|
|
38
|
+
process.env.PATH = inherited + delimiter + (process.env.PATH ?? '');
|
|
39
|
+
}
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
// `import.meta.url` resolves to the running GJS bundle (cli.gjs.mjs) — the
|
|
43
|
+
// whole CLI collapses into that single file, so this module's URL is it.
|
|
44
|
+
const selfBundle = fileURLToPath(import.meta.url);
|
|
45
|
+
const gjs = process.env.GJS_CONSOLE || 'gjs';
|
|
46
|
+
const dir = mkdtempSync(join(tmpdir(), 'gjsify-shim-'));
|
|
47
|
+
const shim = join(dir, 'gjsify');
|
|
48
|
+
writeFileSync(shim, `#!/bin/sh\nexec "${gjs}" -m "${selfBundle}" "$@"\n`, { mode: 0o755 });
|
|
49
|
+
chmodSync(shim, 0o755);
|
|
50
|
+
process.env.GJSIFY_SHIM_DIR = dir;
|
|
51
|
+
process.env.PATH = dir + delimiter + (process.env.PATH ?? '');
|
|
52
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gjsify/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "CLI for Gjsify",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -120,19 +120,19 @@
|
|
|
120
120
|
"cli"
|
|
121
121
|
],
|
|
122
122
|
"dependencies": {
|
|
123
|
-
"@gjsify/buffer": "^0.
|
|
124
|
-
"@gjsify/create-app": "^0.
|
|
125
|
-
"@gjsify/node-globals": "^0.
|
|
126
|
-
"@gjsify/node-polyfills": "^0.
|
|
127
|
-
"@gjsify/npm-registry": "^0.
|
|
128
|
-
"@gjsify/resolve-npm": "^0.
|
|
129
|
-
"@gjsify/rolldown-plugin-gjsify": "^0.
|
|
130
|
-
"@gjsify/rolldown-plugin-pnp": "^0.
|
|
131
|
-
"@gjsify/semver": "^0.
|
|
132
|
-
"@gjsify/tar": "^0.
|
|
133
|
-
"@gjsify/tsc": "^0.
|
|
134
|
-
"@gjsify/web-polyfills": "^0.
|
|
135
|
-
"@gjsify/workspace": "^0.
|
|
123
|
+
"@gjsify/buffer": "^0.10.0",
|
|
124
|
+
"@gjsify/create-app": "^0.10.0",
|
|
125
|
+
"@gjsify/node-globals": "^0.10.0",
|
|
126
|
+
"@gjsify/node-polyfills": "^0.10.0",
|
|
127
|
+
"@gjsify/npm-registry": "^0.10.0",
|
|
128
|
+
"@gjsify/resolve-npm": "^0.10.0",
|
|
129
|
+
"@gjsify/rolldown-plugin-gjsify": "^0.10.0",
|
|
130
|
+
"@gjsify/rolldown-plugin-pnp": "^0.10.0",
|
|
131
|
+
"@gjsify/semver": "^0.10.0",
|
|
132
|
+
"@gjsify/tar": "^0.10.0",
|
|
133
|
+
"@gjsify/tsc": "^0.10.0",
|
|
134
|
+
"@gjsify/web-polyfills": "^0.10.0",
|
|
135
|
+
"@gjsify/workspace": "^0.10.0",
|
|
136
136
|
"cosmiconfig": "^9.0.2",
|
|
137
137
|
"get-tsconfig": "^4.14.0",
|
|
138
138
|
"pkg-types": "^2.3.1",
|
|
@@ -140,13 +140,13 @@
|
|
|
140
140
|
"yargs": "^18.0.0"
|
|
141
141
|
},
|
|
142
142
|
"devDependencies": {
|
|
143
|
-
"@gjsify/unit": "^0.
|
|
143
|
+
"@gjsify/unit": "^0.10.0",
|
|
144
144
|
"@types/yargs": "^17.0.35",
|
|
145
145
|
"typescript": "^6.0.3"
|
|
146
146
|
},
|
|
147
147
|
"peerDependencies": {
|
|
148
|
-
"@gjsify/oxfmt-native": "^0.
|
|
149
|
-
"@gjsify/rolldown-native": "^0.
|
|
148
|
+
"@gjsify/oxfmt-native": "^0.10.0",
|
|
149
|
+
"@gjsify/rolldown-native": "^0.10.0"
|
|
150
150
|
},
|
|
151
151
|
"peerDependenciesMeta": {
|
|
152
152
|
"@gjsify/oxfmt-native": {
|