@gjsify/cli 0.46.0 → 0.48.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 +87 -83
- package/lib/commands/affected-classify.js +30 -1
- package/lib/commands/dlx.js +7 -3
- package/lib/commands/foreach.js +9 -2
- package/lib/commands/onboard.js +11 -0
- package/lib/commands/publish.d.ts +41 -0
- package/lib/commands/publish.js +223 -10
- package/lib/commands/run.js +7 -2
- package/lib/commands/ship.js +32 -4
- package/lib/types/config-data.d.ts +37 -1
- package/lib/utils/base64.d.ts +34 -0
- package/lib/utils/base64.js +47 -0
- package/lib/utils/cli-runtime-closure.d.ts +61 -0
- package/lib/utils/cli-runtime-closure.js +54 -17
- package/lib/utils/double-dash-args.d.ts +8 -0
- package/lib/utils/double-dash-args.js +64 -0
- package/lib/utils/publish-readback.d.ts +132 -0
- package/lib/utils/publish-readback.js +273 -0
- package/lib/utils/ship/changelog.d.ts +56 -0
- package/lib/utils/ship/changelog.js +166 -0
- package/lib/utils/ship/discover.d.ts +10 -1
- package/lib/utils/ship/discover.js +76 -2
- package/lib/utils/ship/entry-interpreter.d.ts +44 -0
- package/lib/utils/ship/entry-interpreter.js +109 -0
- package/lib/utils/ship/formats.js +5 -0
- package/lib/utils/ship/gi-namespaces.js +175 -12
- package/lib/utils/ship/layout.js +8 -4
- package/lib/utils/ship/plan.d.ts +5 -1
- package/lib/utils/ship/plan.js +21 -2
- package/lib/utils/ship/settings.d.ts +48 -2
- package/lib/utils/ship/settings.js +63 -3
- package/lib/utils/ship/stage-manifest.d.ts +22 -3
- package/lib/utils/ship/stage-manifest.js +40 -13
- package/lib/utils/ship/types.d.ts +13 -0
- package/package.json +19 -19
package/dist/cli.gjs.mjs
CHANGED
|
@@ -7,7 +7,7 @@ if(globalThis.__gjsifyBundleUrl??=import.meta.url,Symbol.dispose||(Symbol.dispos
|
|
|
7
7
|
`).slice(1).join(`
|
|
8
8
|
`)||``;this._write(`stderr`,`Trace:`,...n,`
|
|
9
9
|
`+S)}profile(n){}profileEnd(n){}timeStamp(n){}},me=new Console,log=(...n)=>me.log(...n),info=(...n)=>me.info(...n),he=__name$1((...n)=>me.debug(...n),`debug`),warn=(...n)=>me.warn(...n),error=(...n)=>me.error(...n),dir=(n,S)=>me.dir(n,S),dirxml=(...n)=>me.dirxml(...n),table=(n,S)=>me.table(n,S),clear=()=>me.clear(),assert=(n,...S)=>me.assert(n,...S),trace=(...n)=>me.trace(...n),time=n=>me.time(n),timeEnd=n=>me.timeEnd(n),timeLog=(n,...S)=>me.timeLog(n,...S),ge=__name$1(n=>me.count(n),`count`),countReset=n=>me.countReset(n),group=(...n)=>me.group(...n),groupCollapsed=(...n)=>me.groupCollapsed(...n),groupEnd=()=>me.groupEnd(),profile=n=>{},profileEnd=n=>{},timeStamp=n=>{}}),ve,ye=__esmMin(()=>{_e(),ve={log,info,debug:he,warn,error,dir,dirxml,table,time,timeEnd,timeLog,trace,assert,clear,count:ge,countReset,group,groupCollapsed,groupEnd,profile,profileEnd,timeStamp}}),be,xe=__esmMin(()=>{be=__name$1(n=>{Promise.resolve().then(n)},`queueMicrotask`)});function isWindowsPath(n){return/^[A-Za-z]:[\\/]/.test(n)||n.startsWith(`\\\\`)}function lastPathSeparatorIndex(n){let S=n.lastIndexOf(`/`);return isWindowsPath(n)?Math.max(S,n.lastIndexOf(`\\`)):S}function splitPathComponents(n){return isWindowsPath(n)?n.split(/[\\/]/):n.split(`/`)}function pathToFileUrlHref(n,S){let C=S?.windows??isWindowsPath(n),N=C?n.replace(/\\/g,`/`):n;if(C&&N.startsWith(`//`)){let n=N.indexOf(`/`,2);return`file://${n===-1?N.slice(2):N.slice(2,n)}${encodePathForFileUrl(n===-1?``:N.slice(n))}`}return`${N.startsWith(`/`)?`file://`:`file:///`}${encodePathForFileUrl(N)}`}function encodePathForFileUrl(n){let S=``;for(let C of n)S+=Se.test(C)?C:percentEncode(C);return S}function percentEncode(n){let S=``;for(let C of new TextEncoder().encode(n))S+=`%${C.toString(16).toUpperCase().padStart(2,`0`)}`;return S}var Se,Ce=__esmMin(()=>{Se=/^[A-Za-z0-9!$&'()*+,\-./:;=@_]$/});function mapSysname(n){let S=n.trim();switch(S){case`Linux`:return`linux`;case`Darwin`:return`darwin`;case`FreeBSD`:return`freebsd`;case`OpenBSD`:return`openbsd`;case`NetBSD`:return`netbsd`;case`SunOS`:return`sunos`;case`AIX`:return`aix`;case`Haiku`:return`haiku`;default:return/^CYGWIN/i.test(S)?`cygwin`:/^(MINGW|MSYS|Windows)/i.test(S)?`win32`:void 0}}function mapMachine(n){let S=n.trim().toLowerCase();switch(S){case`x86_64`:case`amd64`:return`x64`;case`aarch64`:case`arm64`:return`arm64`;case`i386`:case`i486`:case`i586`:case`i686`:return`ia32`;case`ppc64le`:case`ppc64`:return`ppc64`;case`s390x`:return`s390x`;case`riscv64`:return`riscv64`;case`loongarch64`:return`loong64`;case`mipsel`:return`mipsel`;case`mips`:return`mips`;default:return S.startsWith(`arm`)?`arm`:void 0}}var we=__esmMin(()=>{});function classOf(n){return Te.call(n).slice(8,-1)}function throwDataCloneError(n){let S=globalThis.DOMException;if(typeof S==`function`)throw new S(n,`DataCloneError`);let C=Error(n);throw C.name=`DataCloneError`,C}function internalClone(n,S,C){if(n==null)return n;let N=typeof n;if(N===`boolean`||N===`number`||N===`string`||N===`bigint`)return n;N===`symbol`&&throwDataCloneError(`Symbol cannot be cloned`),N===`function`&&throwDataCloneError(`Function cannot be cloned`);let F=n;if(S.has(F))return S.get(F);let I=classOf(F);if(I===`Date`)return new Date(F.getTime());if(I===`RegExp`)return new RegExp(F.source,F.flags);if(I===`Boolean`||I===`Number`||I===`String`)return Object(F.valueOf());if(I===`BigInt`)return Object(BigInt.prototype.valueOf.call(F));if(F instanceof Error){let n=F,N=n.constructor?.name,I=new(N&&Ee[N]||Ee[n.name]||Error)(n.message);return I.name=n.name,`cause`in n&&Object.defineProperty(I,"cause",{value:internalClone(n.cause,S,C),writable:!0,enumerable:!1,configurable:!0}),I}if(I===`DOMException`){let n=globalThis.DOMException;if(typeof n==`function`){let S=F;return new n(S.message,S.name)}}if(I===`ArrayBuffer`){let n=F;if(C&&C.transferred.has(n)){let N=C.transferred.get(n);return S.set(F,N),N}(n.detached===!0||n.byteLength===0&&n.detached)&&throwDataCloneError(`ArrayBuffer is detached and cannot be cloned`);let N=n.slice(0);return S.set(F,N),N}if(I===`SharedArrayBuffer`||F&&typeof F==`object`&&F.constructor?.name===`SharedBuffer`)return F;if(I===`DataView`){let n=F,N=C?.viewSnapshots.get(F),I=internalClone(n.buffer,S,C),H=N?N.byteOffset:n.byteOffset,W=N?N.byteLength:n.byteLength,q=new DataView(I,H,W);return S.set(F,q),q}if(De.has(I)){let n=F,N=C?.viewSnapshots.get(F),I=internalClone(n.buffer,S,C),H=n.constructor,W=new H(I,N?N.byteOffset:n.byteOffset,N?N.length:n.length);return S.set(F,W),W}if(I===`Map`){let n=new Map;S.set(F,n);for(let[N,I]of F)n.set(internalClone(N,S,C),internalClone(I,S,C));return n}if(I===`Set`){let n=new Set;S.set(F,n);for(let N of F)n.add(internalClone(N,S,C));return n}{let n=globalThis,S=n.Blob,C=n.File;if(typeof C==`function`&&F instanceof C){let n=F;return new C([F],n.name,{type:n.type,lastModified:n.lastModified})}if(typeof S==`function`&&F instanceof S)return new S([F],{type:F.type})}if(F instanceof WeakMap&&throwDataCloneError(`WeakMap cannot be cloned`),F instanceof WeakSet&&throwDataCloneError(`WeakSet cannot be cloned`),F instanceof WeakRef&&throwDataCloneError(`WeakRef cannot be cloned`),typeof globalThis.Promise==`function`&&F instanceof Promise&&throwDataCloneError(`Promise cannot be cloned`),I===`Array`){let n=F,N=[];S.set(F,N);for(let F=0;F<n.length;F++)F in n&&(N[F]=internalClone(n[F],S,C));return N}if(I===`Object`||typeof F==`object`){let n={};S.set(F,n);for(let N of Object.keys(F))n[N]=internalClone(F[N],S,C);return n}throwDataCloneError(`${I} cannot be cloned`)}function structuredClone$1(n,S){let C=S?.transfer;if(!C||C.length===0)return internalClone(n,new Map);let N=new Set;for(let n of C)if(classOf(n)===`ArrayBuffer`){let S=n;S.detached===!0&&throwDataCloneError(`ArrayBuffer in transfer list is detached`),N.add(S)}let F=new Map;N.size>0&&snapshotViewsBackedByTransferredBuffers(n,N,F,new Set);let I=new Map;for(let n of N){let S=n;typeof S.transfer!=`function`&&throwDataCloneError(`ArrayBuffer.prototype.transfer() not available — runtime is not SM140+`),I.set(n,S.transfer())}return internalClone(n,new Map,{transferred:I,viewSnapshots:F})}function snapshotViewsBackedByTransferredBuffers(n,S,C,N){if(typeof n!=`object`||!n)return;let F=n;if(N.has(F))return;N.add(F);let I=classOf(F);if(I===`DataView`){let n=F;S.has(n.buffer)&&C.set(F,{byteOffset:n.byteOffset,length:0,byteLength:n.byteLength});return}if(De.has(I)){let n=F;S.has(n.buffer)&&C.set(F,{byteOffset:n.byteOffset,length:n.length,byteLength:n.byteLength});return}if(Array.isArray(F)){for(let n=0;n<F.length;n++)n in F&&snapshotViewsBackedByTransferredBuffers(F[n],S,C,N);return}if(I===`Map`){for(let[n,I]of F)snapshotViewsBackedByTransferredBuffers(n,S,C,N),snapshotViewsBackedByTransferredBuffers(I,S,C,N);return}if(I===`Set`){for(let n of F)snapshotViewsBackedByTransferredBuffers(n,S,C,N);return}if(I===`Object`)for(let n of Object.keys(F))snapshotViewsBackedByTransferredBuffers(F[n],S,C,N)}var Te,Ee,De,Oe=__esmMin(()=>{({toString:Te}=Object.prototype),Ee={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},De=new Set([`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`,`BigInt64Array`,`BigUint64Array`]),__name$1(structuredClone$1,`structuredClone`)});function hostGlib(){try{return globalThis.imports?.gi?.GLib}catch{return}}function readText(n,S){try{let[C,N]=n.file_get_contents(S);return!C||!N?null:new TextDecoder().decode(N)}catch{return null}}function shellOut(n,S){try{let[C,N]=n.spawn_command_line_sync(S);if(!C||!N)return null;let F=new TextDecoder().decode(N).trim();return F.length>0?F:null}catch{return null}}function hasProcfs(){let n=hostGlib();if(!n)return!1;try{return n.file_test(`/proc/self/status`,16)}catch{return!1}}function hostPid(){if(ke!==null)return ke>0?ke:void 0;let n=hostGlib();if(!n)return;let S=0,C=hasProcfs()?readText(n,`/proc/self/stat`):null;if(C)S=parseInt(C,10);else{let C=shellOut(n,`sh -c 'echo $PPID'`);C&&(S=parseInt(C,10))}return ke=Number.isInteger(S)&&S>0?S:0,ke>0?ke:void 0}function hostPpid(){let n=hostGlib();if(!n)return;let S=hasProcfs()?readText(n,`/proc/self/status`):null;if(S){let n=/PPid:\s+(\d+)/.exec(S);if(n){let S=parseInt(n[1],10);return Number.isInteger(S)?S:void 0}}let C=hostPid();if(C===void 0)return;let N=shellOut(n,`ps -o ppid= -p ${C}`);if(!N)return;let F=parseInt(N,10);return Number.isInteger(F)?F:void 0}function hostExecPath(){let n=hostGlib();if(n){if(hasProcfs())try{let S=n.file_read_link(`/proc/self/exe`);if(S)return S}catch{}try{let S=n.get_prgname();if(S){let C=n.find_program_in_path(S);if(C)return C}}catch{return}}}function readProcessMemory$4(){let n=hostGlib();if(!n)return null;let S=hasProcfs()?readText(n,`/proc/self/status`):null;if(S){let n=new Map;for(let C of S.split(`
|
|
10
|
-
`)){let S=/^(\w+):\s+(\d+)(\s+kB)?/.exec(C);S&&n.set(S[1],parseInt(S[2],10)*(S[3]?1024:1))}if(n.size>0)return{virtual:n.get(`VmSize`)??0,resident:n.get(`VmRSS`)??0,data:n.get(`VmData`)??0,peak:n.get(`VmPeak`)??0}}let C=shellOut(n,`sh -c 'ps -o rss=,vsz= -p $PPID'`);if(!C)return null;let N=/^(\d+)\s+(\d+)$/.exec(C);return N?{virtual:parseInt(N[2],10)*1024,resident:parseInt(N[1],10)*1024,data:0,peak:0}:null}var ke,Ae=__esmMin(()=>{ke=null,__name$1(readProcessMemory$4,`readProcessMemory`)});function glib(){return globalThis.imports?.gi?.GLib}function arm(n){Fe||(Fe=!0,n.runAsync().catch(()=>{}))}function ensureMainLoop(){let n=glib();if(n)return Me?je:(je=new n.MainLoop(null,!1),Me=!0,n.main_depth()===0&&arm(je),je)}function holdMainLoop(){let n=ensureMainLoop();return n&&arm(n),n}function quitMainLoop(){je&&=(je.quit(),Me=!1,Fe=!1,null)}var je,Me,Fe,Ie=__esmMin(()=>{je=null,Me=!1,Fe=!1});function drainOnce(n){let S=Math.min(64,Le.length);for(let C=0;C<S;C++){let S=Le.shift();try{S()}catch(S){try{n.log_default_handler(`gjsify-nextTick`,n.LogLevelFlags.LEVEL_WARNING,String(S?.stack||S),null)}catch{}}}Le.length>0?n.timeout_add(n.PRIORITY_DEFAULT,1,()=>(drainOnce(n),!1)):Re=!1}function tryGLibTimeout(n){let S=globalThis.imports?.gi?.GLib;return S?.timeout_add?(Le.push(n),Re||(Re=!0,S.timeout_add(S.PRIORITY_DEFAULT,0,()=>(drainOnce(S),!1))),!0):!1}var Le,Re,nextTick,ze=__esmMin(()=>{Le=[],Re=!1,nextTick=(n,...S)=>{let C=S.length>0?()=>n(...S):n;if(!tryGLibTimeout(C)){if(typeof globalThis.process?.nextTick==`function`){globalThis.process.nextTick(n,...S);return}if(typeof queueMicrotask==`function`){queueMicrotask(C);return}Promise.resolve().then(C)}}}),Be=__esmMin(()=>{ae(),se(),ce(),le(),de(),xe(),Ce(),we(),Oe(),Ae(),Ie(),ze()});ie(),Be(),registerGlobal(`Blob`,ne),registerGlobal(`File`,re);function atobPolyfill(n){if(typeof globalThis.atob==`function`)return globalThis.atob(n);let S=n.replace(/[=\s]/g,``),C=``,N=0,F=0;for(let n=0;n<S.length;n++)N=N<<6|He[S.charCodeAt(n)],F+=6,F>=8&&(F-=8,C+=String.fromCharCode(N>>F&255));return C}function btoaPolyfill(n){if(typeof globalThis.btoa==`function`)return globalThis.btoa(n);let S=``,C=0;for(;C+2<n.length;C+=3){let N=n.charCodeAt(C)<<16|n.charCodeAt(C+1)<<8|n.charCodeAt(C+2);S+=Ve[N>>18&63]+Ve[N>>12&63]+Ve[N>>6&63]+Ve[N&63]}if(C+1===n.length){let N=n.charCodeAt(C)<<16;S+=Ve[N>>18&63]+Ve[N>>12&63]+`==`}else if(C+2===n.length){let N=n.charCodeAt(C)<<16|n.charCodeAt(C+1)<<8;S+=Ve[N>>18&63]+Ve[N>>12&63]+Ve[N>>6&63]+`=`}return S}function base64Decode$1(n){let S=n.replace(/[=\s]/g,``),C=new Uint8Array(S.length*3>>2),N=0,F=0,I=0;for(let n=0;n<S.length;n++)N=N<<6|He[S.charCodeAt(n)],F+=6,F>=8&&(F-=8,C[I++]=N>>F&255);return C.subarray(0,I)}function base64Encode$1(n){let S=``,C=n.length;for(let N=0;N<C;N+=3){let F=n[N],I=N+1<C?n[N+1]:0,H=N+2<C?n[N+2]:0;S+=Ve[F>>2],S+=Ve[(F&3)<<4|I>>4],S+=N+1<C?Ve[(I&15)<<2|H>>6]:`=`,S+=N+2<C?Ve[H&63]:`=`}return S}var Ve,He,Ue=__esmMin(()=>{Ve=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,He=new Uint8Array(256);for(let n=0;n<64;n++)He[Ve.charCodeAt(n)]=n;__name$1(base64Decode$1,`base64Decode`),__name$1(base64Encode$1,`base64Encode`)});function normalizeEncoding(n){if(!n||n===`utf8`||n===`utf-8`)return`utf8`;switch((``+n).toLowerCase().replace(/-/g,``)){case`utf8`:return`utf8`;case`ascii`:return`ascii`;case`latin1`:case`binary`:return`latin1`;case`base64`:return`base64`;case`base64url`:return`base64url`;case`hex`:return`hex`;case`ucs2`:case`utf16le`:return`utf16le`;default:return`utf8`}}function checkEncoding(n){let S=(``+n).toLowerCase().replace(/-/g,``);if(!Ge.includes(S))throw TypeError(`Unknown encoding: ${n}`)}var Ge,Ke=__esmMin(()=>{Ge=[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`]});function encodeString(n,S){switch(S){case`utf8`:return Ye().encode(n);case`ascii`:{let S=new Uint8Array(n.length);for(let C=0;C<n.length;C++)S[C]=n.charCodeAt(C)&127;return S}case`latin1`:{let S=new Uint8Array(n.length);for(let C=0;C<n.length;C++)S[C]=n.charCodeAt(C)&255;return S}case`base64`:return base64Decode$1(n.replace(/-/g,`+`).replace(/_/g,`/`));case`base64url`:return encodeString(n.replace(/-/g,`+`).replace(/_/g,`/`),`base64`);case`hex`:{let S=n.length>>>1,C=new Uint8Array(S);for(let N=0;N<S;N++){let S=parseInt(n[N*2],16),F=parseInt(n[N*2+1],16);if(Number.isNaN(S)||Number.isNaN(F))break;C[N]=S<<4|F}return C}case`utf16le`:{let S=new Uint8Array(n.length*2);for(let C=0;C<n.length;C++){let N=n.charCodeAt(C);S[C*2]=N&255,S[C*2+1]=N>>8&255}return S}default:return Ye().encode(n)}}function decodeString(n,S,C,N){let F=C!==void 0||N!==void 0?n.subarray(C??0,N??n.length):n;switch(S){case`utf8`:return Xe().decode(F);case`ascii`:{let n=``;for(let S=0;S<F.length;S++)n+=String.fromCharCode(F[S]&127);return n}case`latin1`:{let n=``;for(let S=0;S<F.length;S++)n+=String.fromCharCode(F[S]);return n}case`base64`:{let n=``;for(let S=0;S<F.length;S++)n+=String.fromCharCode(F[S]);return btoaPolyfill(n)}case`base64url`:return decodeString(F,`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);case`hex`:{let n=``;for(let S=0;S<F.length;S++)n+=F[S].toString(16).padStart(2,`0`);return n}case`utf16le`:{let n=``;for(let S=0;S+1<F.length;S+=2)n+=String.fromCharCode(F[S]|F[S+1]<<8);return n}default:return Xe().decode(F)}}function checkOffset(n,S,C){if(n+S>C)throw RangeError(`Attempt to access memory outside buffer bounds`)}var qe,Je,Ye,Xe,Ze=__esmMin(()=>{Ue(),Ye=__name$1(()=>qe??=new TextEncoder,`textEncoder`),Xe=__name$1(()=>Je??=new TextDecoder,`textDecoder`)}),Qe,$e,et,tt,nt,SlowBuffer,rt=__esmMin(()=>{Ze(),Ke(),Qe=typeof SharedArrayBuffer<`u`,$e=class Buffer extends Uint8Array{static _isBuffer=!0;static alloc(n,S,C){if(typeof n!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof n}`);if(n<0)throw RangeError(`The value "${n}" is invalid for option "size"`);let N=new Buffer(n);return S!==void 0&&S!==0&&N.fill(S,0,n,C),N}static allocUnsafe(n){if(typeof n!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof n}`);return new Buffer(n)}static allocUnsafeSlow(n){return Buffer.allocUnsafe(n)}static from(n,S,C){if(typeof n==`string`){let C=normalizeEncoding(S);if(S&&typeof S==`string`){let n=(``+S).toLowerCase().replace(/-/g,``);[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`,``].includes(n)||checkEncoding(S)}let N=encodeString(n,C);return new Buffer(N.buffer,N.byteOffset,N.byteLength)}if(ArrayBuffer.isView(n)){let S=new Buffer(n.buffer,n.byteOffset,n.byteLength),C=new Buffer(S.length);return C.set(S),C}if(n instanceof ArrayBuffer){let N=S||0,F=C===void 0?n.byteLength-N:C;return new Buffer(n,N,F)}if(Qe&&n instanceof SharedArrayBuffer){let N=S||0,F=C===void 0?n.byteLength-N:C;return new Buffer(new Uint8Array(n,N,F))}if(typeof n==`object`&&n&&typeof n.viewBytes==`function`&&typeof n.byteLength==`number`&&n.constructor?.name===`SharedBuffer`){let N=n,F=S||0,I=C===void 0?N.byteLength-F:C,H=N.viewBytes(F,I);return new Buffer(H.buffer,H.byteOffset,H.byteLength)}if(Array.isArray(n)){let S=new Buffer(n.length);for(let C=0;C<n.length;C++)S[C]=n[C]&255;return S}throw TypeError(`The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array`)}static isBuffer(n){return n instanceof Buffer}static isEncoding(n){if(typeof n!=`string`)return!1;let S=n.toLowerCase().replace(/-/g,``);return[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`].includes(S)}static byteLength(n,S){if(typeof n!=`string`){if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer||Qe&&n instanceof SharedArrayBuffer)return n.byteLength;throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer`)}switch(normalizeEncoding(S)){case`utf8`:return new TextEncoder().encode(n).byteLength;case`ascii`:case`latin1`:return n.length;case`base64`:case`base64url`:{let S=n.length;for(;S>0&&(n[S-1]===`=`||n[S-1]===` `);)S--;return S*3>>>2}case`hex`:return n.length>>>1;case`utf16le`:return n.length*2;default:return new TextEncoder().encode(n).byteLength}}static compare(n,S){if(!(n instanceof Uint8Array)||!(S instanceof Uint8Array))throw TypeError(`Arguments must be Buffers or Uint8Arrays`);let C=Math.min(n.length,S.length);for(let N=0;N<C;N++){if(n[N]<S[N])return-1;if(n[N]>S[N])return 1}return n.length<S.length?-1:+(n.length>S.length)}static concat(n,S){if(n.length===0)return Buffer.alloc(0);if(S===void 0){S=0;for(let C=0;C<n.length;C++)S+=n[C].length}let C=Buffer.alloc(S),N=0;for(let F=0;F<n.length;F++){let I=n[F],H=Math.min(I.length,S-N);H<=0||(C.set(I.subarray(0,H),N),N+=H)}return C}static poolSize=65536;toString(n,S,C){let N=normalizeEncoding(n);return decodeString(this,N,S,C)}toJSON(){return{type:`Buffer`,data:Array.from(this)}}equals(n){if(!(n instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);if(this.length!==n.length)return!1;for(let S=0;S<this.length;S++)if(this[S]!==n[S])return!1;return!0}compare(n,S,C,N,F){if(!(n instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);let I=N!==void 0||F!==void 0?this.subarray(N??0,F??this.length):this,H=S!==void 0||C!==void 0?n.subarray(S??0,C??n.length):n;return Buffer.compare(I,H)}copy(n,S=0,C=0,N){let F=N??this.length,I=Math.min(F-C,n.length-S);return I<=0?0:(n.set(this.subarray(C,C+I),S),I)}slice(n,S){let C=n??0,N=S??this.length,F=super.subarray(C,N);return new Buffer(F.buffer,F.byteOffset,F.byteLength)}subarray(n,S){let C=super.subarray(n,S);return new Buffer(C.buffer,C.byteOffset,C.byteLength)}write(n,S,C,N){S??=0;let F=encodeString(n,normalizeEncoding(N||(typeof C==`string`?C:void 0))),I=C!==void 0&&typeof C==`number`?Math.min(C,this.length-S):this.length-S,H=Math.min(F.length,I);return this.set(F.subarray(0,H),S),H}fill(n,S,C,N){let F=S??0,I=C??this.length;if(typeof n==`number`)super.fill(n&255,F,I);else if(typeof n==`string`){let S=encodeString(n,normalizeEncoding(N));if(S.length===0)super.fill(0,F,I);else if(S.length===1)super.fill(S[0],F,I);else for(let n=F;n<I;n++)this[n]=S[(n-F)%S.length]}else if(n instanceof Uint8Array)if(n.length===0)super.fill(0,F,I);else for(let S=F;S<I;S++)this[S]=n[(S-F)%n.length];return this}indexOf(n,S,C){if(typeof n==`number`)return super.indexOf(n&255,S);let N=typeof n==`string`?encodeString(n,normalizeEncoding(C)):n,F=S??0;outer:for(let n=F;n<=this.length-N.length;n++){for(let S=0;S<N.length;S++)if(this[n+S]!==N[S])continue outer;return n}return-1}lastIndexOf(n,S,C){if(typeof n==`number`)return S===void 0?super.lastIndexOf(n&255):super.lastIndexOf(n&255,S);let N=typeof n==`string`?encodeString(n,normalizeEncoding(C)):n,F=S===void 0?this.length-N.length:Math.min(S,this.length-N.length);outer:for(let n=F;n>=0;n--){for(let S=0;S<N.length;S++)if(this[n+S]!==N[S])continue outer;return n}return-1}includes(n,S,C){return this.indexOf(n,S,C)!==-1}readUInt8(n=0){return checkOffset(n,1,this.length),this[n]}readUInt16BE(n=0){return checkOffset(n,2,this.length),this[n]<<8|this[n+1]}readUInt16LE(n=0){return checkOffset(n,2,this.length),this[n]|this[n+1]<<8}readUInt32BE(n=0){return checkOffset(n,4,this.length),this[n]*16777216+(this[n+1]<<16|this[n+2]<<8|this[n+3])}readUInt32LE(n=0){return checkOffset(n,4,this.length),this[n+3]*16777216+(this[n+2]<<16|this[n+1]<<8|this[n])>>>0}readInt8(n=0){return checkOffset(n,1,this.length),this[n]|(this[n]&128?4294967040:0)}readInt16BE(n=0){checkOffset(n,2,this.length);let S=this[n]<<8|this[n+1];return S&32768?S|4294901760:S}readInt16LE(n=0){checkOffset(n,2,this.length);let S=this[n]|this[n+1]<<8;return S&32768?S|4294901760:S}readInt32BE(n=0){return checkOffset(n,4,this.length),this[n]<<24|this[n+1]<<16|this[n+2]<<8|this[n+3]}readInt32LE(n=0){return checkOffset(n,4,this.length),this[n]|this[n+1]<<8|this[n+2]<<16|this[n+3]<<24}readFloatBE(n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).getFloat32(0,!1)}readFloatLE(n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).getFloat32(0,!0)}readDoubleBE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getFloat64(0,!1)}readDoubleLE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getFloat64(0,!0)}readBigInt64BE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getBigInt64(0,!1)}readBigInt64LE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getBigInt64(0,!0)}readBigUInt64BE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getBigUint64(0,!1)}readBigUInt64LE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getBigUint64(0,!0)}readUIntBE(n,S){checkOffset(n,S,this.length);let C=0;for(let N=0;N<S;N++)C=C*256+this[n+N];return C}readUIntLE(n,S){checkOffset(n,S,this.length);let C=0,N=1;for(let F=0;F<S;F++)C+=this[n+F]*N,N*=256;return C}readIntBE(n,S){checkOffset(n,S,this.length);let C=0;for(let N=0;N<S;N++)C=C*256+this[n+N];return C>=2**(8*S-1)&&(C-=2**(8*S)),C}readIntLE(n,S){checkOffset(n,S,this.length);let C=0,N=1;for(let F=0;F<S;F++)C+=this[n+F]*N,N*=256;return C>=2**(8*S-1)&&(C-=2**(8*S)),C}writeUInt8(n,S=0){return checkOffset(S,1,this.length),this[S]=n&255,S+1}writeUInt16BE(n,S=0){return checkOffset(S,2,this.length),this[S]=n>>>8&255,this[S+1]=n&255,S+2}writeUInt16LE(n,S=0){return checkOffset(S,2,this.length),this[S]=n&255,this[S+1]=n>>>8&255,S+2}writeUInt32BE(n,S=0){return checkOffset(S,4,this.length),this[S]=n>>>24&255,this[S+1]=n>>>16&255,this[S+2]=n>>>8&255,this[S+3]=n&255,S+4}writeUInt32LE(n,S=0){return checkOffset(S,4,this.length),this[S]=n&255,this[S+1]=n>>>8&255,this[S+2]=n>>>16&255,this[S+3]=n>>>24&255,S+4}writeInt8(n,S=0){return checkOffset(S,1,this.length),n<0&&(n=255+n+1),this[S]=n&255,S+1}writeInt16BE(n,S=0){return checkOffset(S,2,this.length),this[S]=n>>>8&255,this[S+1]=n&255,S+2}writeInt16LE(n,S=0){return checkOffset(S,2,this.length),this[S]=n&255,this[S+1]=n>>>8&255,S+2}writeInt32BE(n,S=0){return checkOffset(S,4,this.length),this[S]=n>>>24&255,this[S+1]=n>>>16&255,this[S+2]=n>>>8&255,this[S+3]=n&255,S+4}writeInt32LE(n,S=0){return checkOffset(S,4,this.length),this[S]=n&255,this[S+1]=n>>>8&255,this[S+2]=n>>>16&255,this[S+3]=n>>>24&255,S+4}writeFloatBE(n,S=0){return checkOffset(S,4,this.length),new DataView(this.buffer,this.byteOffset+S,4).setFloat32(0,n,!1),S+4}writeFloatLE(n,S=0){return checkOffset(S,4,this.length),new DataView(this.buffer,this.byteOffset+S,4).setFloat32(0,n,!0),S+4}writeDoubleBE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setFloat64(0,n,!1),S+8}writeDoubleLE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setFloat64(0,n,!0),S+8}writeBigInt64BE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setBigInt64(0,n,!1),S+8}writeBigInt64LE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setBigInt64(0,n,!0),S+8}writeBigUInt64BE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setBigUint64(0,n,!1),S+8}writeBigUInt64LE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setBigUint64(0,n,!0),S+8}swap16(){let n=this.length;if(n%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let S=0;S<n;S+=2){let n=this[S];this[S]=this[S+1],this[S+1]=n}return this}swap32(){let n=this.length;if(n%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let S=0;S<n;S+=4){let n=this[S],C=this[S+1];this[S]=this[S+3],this[S+1]=this[S+2],this[S+2]=C,this[S+3]=n}return this}swap64(){let n=this.length;if(n%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let S=0;S<n;S+=8){let n=this[S],C=this[S+1],N=this[S+2],F=this[S+3];this[S]=this[S+7],this[S+1]=this[S+6],this[S+2]=this[S+5],this[S+3]=this[S+4],this[S+4]=F,this[S+5]=N,this[S+6]=C,this[S+7]=n}return this}},et=2**31-1,tt=2**28-16,nt={MAX_LENGTH:et,MAX_STRING_LENGTH:tt},SlowBuffer=class extends $e{constructor(n){super(n)}}}),it=__exportAll$4({Blob:()=>ne,Buffer:()=>$e,File:()=>re,INSPECT_MAX_BYTES:()=>50,SlowBuffer:()=>SlowBuffer,atob:()=>ot,atobPolyfill:()=>atobPolyfill,base64Decode:()=>base64Decode$1,base64Encode:()=>base64Encode$1,btoa:()=>st,btoaPolyfill:()=>btoaPolyfill,checkEncoding:()=>checkEncoding,constants:()=>nt,default:()=>ct,kMaxLength:()=>et,kStringMaxLength:()=>tt,normalizeEncoding:()=>normalizeEncoding}),ot,st,ct,lt=__esmMin(()=>{Ue(),ie(),Ke(),rt(),ot=globalThis.atob,st=globalThis.btoa,ct={Buffer:$e,SlowBuffer,Blob:ne,File:re,atob:ot,btoa:st,kMaxLength:et,kStringMaxLength:tt,constants:nt,INSPECT_MAX_BYTES:50}});lt(),`Buffer`in globalThis||Object.defineProperty(globalThis,"Buffer",{value:$e,enumerable:!1,writable:!0,configurable:!0});var ut,dt=__esmMin(()=>{ut=n}),ft,pt=__esmMin(()=>{dt(),ft=ut});pt(),typeof globalThis.btoa!=`function`&&Object.defineProperty(globalThis,"btoa",{value:function btoa(n){let S=new Uint8Array(n.length);for(let C=0;C<n.length;C++)S[C]=n.charCodeAt(C)&255;return ft.base64_encode(S)},enumerable:!0,writable:!0,configurable:!0}),typeof globalThis.atob!=`function`&&Object.defineProperty(globalThis,"atob",{value:function atob(n){let S=ft.base64_decode(n),C=``;for(let n=0;n<S.length;n++)C+=String.fromCharCode(S[n]);return C},enumerable:!0,writable:!0,configurable:!0}),Be(),typeof queueMicrotask!=`function`&&Object.defineProperty(globalThis,"queueMicrotask",{value:be,enumerable:!0,writable:!0,configurable:!0});function getGjsGlobal(){return globalThis}function getGioNamespace(){let n=getGjsGlobal().imports?.gi;if(!n)return null;let S=null;try{S=n.GioUnix??null}catch{}if(!S)try{S=n.Gio??null}catch{}return S}var mt=__esmMin(()=>{});function getMonotonicTime(){try{let n=getGjsGlobal().imports?.gi?.GLib;if(n?.get_monotonic_time)return BigInt(n.get_monotonic_time())*1000n}catch{}return typeof performance?.now==`function`?BigInt(Math.round(performance.now()*1e6)):BigInt(Date.now())*1000000n}function hrtime(n){let S=getMonotonicTime()-ht,C=Number(S/1000000000n),N=Number(S%1000000000n);if(n){let S=C-n[0],F=N-n[1];return F<0&&(S--,F+=1e9),[S,F]}return[C,N]}function hrtimeBigint(){return getMonotonicTime()-ht}var ht,gt=__esmMin(()=>{mt(),ht=getMonotonicTime()});function probeUname(){if(_t!==void 0)return _t;_t=null;try{let n=getGjsGlobal().imports?.gi?.GLib;if(!n)return _t;let S=n.spawn_sync,C=n.SpawnFlags?.SEARCH_PATH;if(!S||C===void 0)return _t;let[N,F]=S(null,[`uname`,`-sm`],null,C,null);if(!N||!F)return _t;let I=new TextDecoder().decode(F).trim().split(/\s+/);if(I.length<2)return _t;let H=mapSysname(I[0]),W=mapMachine(I[I.length-1]);if(!H||!W)return _t;_t={platform:H,arch:W}}catch{}return _t}var _t,vt=__esmMin(()=>{mt(),Be()});function detectGjsVersion(){try{let n=getGjsGlobal().imports?.system;if(n?.version!==void 0){let S=Number(n.version);return`${Math.floor(S/1e4)}.${Math.floor(S%1e4/100)}.${S%100}`}}catch{}}function detectNodeVersion(){if(typeof globalThis.process?.versions?.node==`string`)return globalThis.process.versions.node}function detectVersionInfo(){if(detectNodeVersion())return{version:globalThis.process.version,versions:{...globalThis.process.versions},title:globalThis.process?.title||`node`};let n=detectGjsVersion(),S={node:`20.0.0`};return n&&(S.gjs=n),{version:`v20.0.0`,versions:S,title:`gjs`}}function detectPpid(){return!onGjs()&&typeof globalThis.process?.ppid==`number`?globalThis.process.ppid:hostPpid()??0}function onGjs(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function detectPlatform$1(){if(onGjs()){let n=probeUname();return n?n.platform:`linux`}let n=globalThis.process;return typeof n?.platform==`string`?n.platform:`linux`}function detectArch(){if(onGjs()){let n=probeUname();return n?n.arch:`x64`}let n=globalThis.process;return typeof n?.arch==`string`?n.arch:`x64`}function getPid$1(){return!onGjs()&&typeof globalThis.process?.pid==`number`?globalThis.process.pid:hostPid()??0}var yt=__esmMin(()=>{mt(),vt(),Be(),__name$1(detectPlatform$1,`detectPlatform`),__name$1(getPid$1,`getPid`)});function getEnvProxy(){if(typeof globalThis.process?.env==`object`)return globalThis.process.env;try{let n=getGjsGlobal().imports?.gi?.GLib;if(n)return new Proxy({},{get(S,C){if(typeof C==`string`)return n.getenv(C)??void 0},set(S,C,N){return typeof C==`string`?(n.setenv(C,String(N),!0),!0):!1},deleteProperty(S,C){return typeof C==`string`?(n.unsetenv(C),!0):!1},has(S,C){return typeof C==`string`?n.getenv(C)!==null:!1},ownKeys(S){return n.listenv()},getOwnPropertyDescriptor(S,C){if(typeof C!=`string`)return;let N=n.getenv(C);if(N!==null)return{configurable:!0,enumerable:!0,writable:!0,value:N}}})}catch{}return{}}function getArgv(){if(globalThis.process?.argv!==void 0)return globalThis.process.argv;try{let n=getGjsGlobal().imports?.system;if(n?.programArgs)return[`gjs`,n.programInvocationName||``,...n.programArgs]}catch{}return[`gjs`]}function getExecPath(){let n=globalThis.process;return!isGjsHost()&&typeof n?.execPath==`string`?n.execPath:hostExecPath()??`/usr/bin/gjs`}function isGjsHost(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function getCwd(){try{let n=getGjsGlobal().imports?.gi?.GLib;if(n?.get_current_dir)return n.get_current_dir()}catch{}return`/`}function chdir(n){let S=getGjsGlobal().imports?.gi?.GLib;try{if(S?.chdir){if(!S.file_test(n,16)){let S=Error(`ENOENT: no such file or directory, chdir '${n}'`);throw S.code=`ENOENT`,S.syscall=`chdir`,S.path=n,S}S.chdir(n);return}}catch(n){if(n&&typeof n==`object`&&n.code===`ENOENT`)throw n}if(!S){let S=globalThis.process;if(S&&typeof S.chdir==`function`){S.chdir(n);return}}throw Error(`process.chdir() is not supported in this environment`)}var bt=__esmMin(()=>{mt(),Be()});function exitProcess(n){let S=getGjsGlobal().imports,C=S?.gi?.GLib,N=S?.system,F=C?.idle_add,I=C?.SOURCE_REMOVE,H=C?.PRIORITY_DEFAULT,W=C?.MainContext;if(N?.exit&&F&&typeof H==`number`&&typeof I==`boolean`&&typeof W?.default==`function`){F(H,()=>(N.exit(n),I));let S=W.default();for(;;)S.iteration(!0)}try{N?.exit&&N.exit(n)}catch{}let q=globalThis.process;throw q&&typeof q.exit==`function`&&q.exit(n),Error(`process.exit(${n})`)}var xt=__esmMin(()=>{mt()});function isGjs$1(){return getGjsGlobal().imports?.gi?.GLib!==void 0}function killPid(n,S){try{let C=getGjsGlobal().imports?.gi?.GLib;if(C){let N=typeof S==`number`?String(S):S||`SIGTERM`,F=N.startsWith(`SIG`)?`-${N.slice(3)}`:`-${N}`;return C.spawn_command_line_sync(`kill ${F} ${n}`),!0}}catch{}if(!isGjs$1()){let C=globalThis.process;if(C&&typeof C.kill==`function`)return C.kill(n,S)}throw Error(`process.kill() is not supported in this environment`)}function memoryUsage(){let n=readProcessMemory$4();if(n)return{rss:n.resident,heapTotal:n.resident,heapUsed:n.resident,external:0,arrayBuffers:0};if(!isGjs$1()){let n=globalThis.process;if(n&&typeof n.memoryUsage==`function`)return n.memoryUsage()}return{rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}}function cpuUsage(n){if(!isGjs$1()){let S=globalThis.process;if(S&&typeof S.cpuUsage==`function`)return S.cpuUsage(n)}return{user:0,system:0}}function readUmask(){try{let n=getGjsGlobal().imports?.gi?.GLib;if(n){let[S,C]=n.file_get_contents(`/proc/self/status`);if(S){let n=/^Umask:\s*([0-7]+)/m.exec(new TextDecoder().decode(C));if(n)return parseInt(n[1],8)}}}catch{}return 18}var St=__esmMin(()=>{mt(),Be(),__name$1(isGjs$1,`isGjs`)});function resolveSignalAdd(){let n=getGjsGlobal().imports?.gi;if(!n)return null;for(let[S,C]of[[`GLibUnix`,`signal_add`],[`GLib`,`unix_signal_add`]])try{let N=n[S]?.[C];if(typeof N==`function`)return N}catch{}return null}function isDeliverableSignal(n){return typeof n==`string`&&n in Ct}function armSignal(n,S){if(wt.has(n))return;let C=Ct[n],N=resolveSignalAdd(),F=getGjsGlobal().imports?.gi?.GLib;if(C===void 0||N===null||!F)return;let I=F.PRIORITY_DEFAULT,H=N(I,C,()=>(S(n),!0));wt.set(n,H)}function disarmSignal(n){let S=wt.get(n);if(S===void 0)return;wt.delete(n);let C=getGjsGlobal().imports?.gi?.GLib;C&&typeof C.source_remove==`function`&&C.source_remove(S)}var Ct,wt,Tt=__esmMin(()=>{mt(),Ct={SIGHUP:1,SIGINT:2,SIGTERM:15},wt=new Map}),Et,Dt,Ot,kt=__esmMin(()=>{if(Et=null,Dt=globalThis.imports?.gi,Dt)try{Et=Dt.GjsifyTerminal}catch{}Ot=Et});function onceWrapper(){let{target:n,type:S,listener:C}=this;return this.wrapperFn&&n.removeListener(S,this.wrapperFn),C.apply(n,Array.from(arguments))}function _onceWrap(n,S,C){let N={target:n,type:S,listener:C,wrapperFn:void 0},F=onceWrapper.bind(N);return N.wrapperFn=F,F.listener=C,F}function arrayClone(n){switch(n.length){case 0:return[];case 1:return[n[0]];case 2:return[n[0],n[1]];case 3:return[n[0],n[1],n[2]];default:return n.slice()}}function checkListener(n){if(typeof n!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof n)}function validateNumber(n,S){if(typeof n!=`number`||n!==n)throw TypeError(`The "${S}" argument must be of type number. Received type ${typeof n}`)}function spliceOne(n,S){for(;S+1<n.length;S++)n[S]=n[S+1];n.pop()}function unwrapListeners(n){let S=Array.from({length:n.length});for(let C=0;C<S.length;++C)S[C]=n[C].listener??n[C];return S}function createAbortError$2(n){let S=Error(`The operation was aborted`);return S.name=`AbortError`,S.code=`ABORT_ERR`,n?.reason&&(S.cause=n.reason),S}var At,jt,Mt,Nt=__esmMin(()=>{ye(),At=Symbol(`kCapture`),jt=Symbol.for(`nodejs.rejection`),Mt=class EventEmitter{static defaultMaxListeners=10;static errorMonitor=Symbol(`events.errorMonitor`);static captureRejectionSymbol=jt;static _captureRejections=!1;static get captureRejections(){return EventEmitter._captureRejections}static set captureRejections(n){if(typeof n!=`boolean`)throw TypeError(`The "captureRejections" argument must be of type boolean.`);EventEmitter._captureRejections=n}_events;_eventsCount;_maxListeners;[At];constructor(n){this._events=Object.create(null),this._eventsCount=0,this._maxListeners=void 0,this[At]=n?.captureRejections??EventEmitter._captureRejections}setMaxListeners(n){if(validateNumber(n,`n`),n<0)throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+n);return this._maxListeners=n,this}getMaxListeners(){return this._maxListeners??EventEmitter.defaultMaxListeners}emit(n,...S){let C=this._events,N=n===`error`;if(C!==void 0)N&&C[EventEmitter.errorMonitor]!==void 0&&this.emit(EventEmitter.errorMonitor,...S),N&&=C.error===void 0;else if(!N)return!1;if(N){let n;if(n=S.length>0?S[0]:Error(`Unhandled error.`),n instanceof Error)throw n;let C=Error(`Unhandled error. (`+n+`)`);throw C.context=n,C}let F=C[n];if(F===void 0)return!1;if(typeof F==`function`){let C=F.apply(this,S);C!=null&&this[At]&&this._addCatch(C,n,S)}else{let C=arrayClone(F),N=C.length;for(let F=0;F<N;++F){let N=C[F].apply(this,S);N!=null&&this[At]&&this._addCatch(N,n,S)}}return!0}_addCatch(n,S,C){typeof n?.then==`function`&&n.then(void 0,n=>{let N=this[jt];if(typeof N==`function`)N.call(this,n,S,...C);else{let S=this[At];try{this[At]=!1,this.emit(`error`,n)}finally{this[At]=S}}})}addListener(n,S){return this._addListener(n,S,!1)}on(n,S){return this._addListener(n,S,!1)}prependListener(n,S){return this._addListener(n,S,!0)}_addListener(n,S,C){checkListener(S);let N=this._events;N===void 0?(N=this._events=Object.create(null),this._eventsCount=0):N.newListener!==void 0&&(this.emit(`newListener`,n,S.listener??S),N=this._events);let F=N[n];F===void 0?(N[n]=S,++this._eventsCount):typeof F==`function`?N[n]=C?[S,F]:[F,S]:C?F.unshift(S):F.push(S);let I=this.getMaxListeners();if(I>0){let S=typeof N[n]==`function`?1:N[n].length;if(S>I&&!N[n].warned){typeof N[n]!=`function`&&(N[n].warned=!0);let C=Error(`Possible EventEmitter memory leak detected. ${S} ${String(n)} listeners added to [${this.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);C.name=`MaxListenersExceededWarning`,ve.warn(C.message)}}return this}once(n,S){return checkListener(S),this.on(n,_onceWrap(this,n,S)),this}prependOnceListener(n,S){return checkListener(S),this.prependListener(n,_onceWrap(this,n,S)),this}removeListener(n,S){checkListener(S);let C=this._events;if(C===void 0)return this;let N=C[n];if(N===void 0)return this;if(N===S||N.listener===S)--this._eventsCount===0?this._events=Object.create(null):(delete C[n],C.removeListener&&this.emit(`removeListener`,n,N.listener??S));else if(typeof N!=`function`){let F=-1;for(let n=N.length-1;n>=0;n--)if(N[n]===S||N[n].listener===S){F=n;break}if(F<0)return this;F===0?N.shift():spliceOne(N,F),N.length===1&&(C[n]=N[0]),C.removeListener!==void 0&&this.emit(`removeListener`,n,S.listener??S)}return this}off(n,S){return this.removeListener(n,S)}removeAllListeners(n){let S=this._events;if(S===void 0)return this;if(S.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):S[n]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete S[n]),this;if(arguments.length===0){let n=Object.keys(S);for(let S=0;S<n.length;++S){let C=n[S];C!==`removeListener`&&this.removeAllListeners(C)}return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}let C=S[n];if(typeof C==`function`)this.removeListener(n,C);else if(C!==void 0)for(let S=C.length-1;S>=0;S--)this.removeListener(n,C[S]);return this}listeners(n){let S=this._events;if(S===void 0)return[];let C=S[n];return C===void 0?[]:typeof C==`function`?[C.listener??C]:unwrapListeners(C)}rawListeners(n){let S=this._events;if(S===void 0)return[];let C=S[n];return C===void 0?[]:typeof C==`function`?[C]:arrayClone(C)}listenerCount(n){let S=this._events;if(S===void 0)return 0;let C=S[n];return C===void 0?0:typeof C==`function`?1:C.length}eventNames(){return(this._eventsCount??0)>0?Reflect.ownKeys(this._events):[]}static once(n,S,C){return new Promise((N,F)=>{let I=C?.signal;if(I?.aborted){F(createAbortError$2(I));return}if(typeof n.addEventListener==`function`){let C=n,handler=(...n)=>{I&&I.removeEventListener(`abort`,abortHandler),N(n)},errorHandler=n=>{I&&I.removeEventListener(`abort`,abortHandler),C.removeEventListener(`error`,errorHandler),F(n)},abortHandler=()=>{C.removeEventListener(S,handler),C.removeEventListener(`error`,errorHandler),F(createAbortError$2(I))};C.addEventListener(S,handler,{once:!0}),S!==`error`&&C.addEventListener(`error`,errorHandler,{once:!0}),I&&I.addEventListener(`abort`,abortHandler,{once:!0});return}let H=n,eventHandler=(...n)=>{I&&I.removeEventListener(`abort`,abortHandler),errorHandler!==void 0&&H.removeListener(`error`,errorHandler),N(n)},errorHandler;S!==`error`&&(errorHandler=n=>{H.removeListener(S,eventHandler),I&&I.removeEventListener(`abort`,abortHandler),F(n)},H.once(`error`,errorHandler)),H.once(S,eventHandler);let abortHandler=()=>{H.removeListener(S,eventHandler),errorHandler&&H.removeListener(`error`,errorHandler),F(createAbortError$2(I))};I&&I.addEventListener(`abort`,abortHandler,{once:!0})})}static on(n,S,C){let N=C?.signal;if(N?.aborted)throw createAbortError$2(N);let F=C?.highWaterMark??2**53-1,I=C?.lowWaterMark??1;validateNumber(F,`highWaterMark`),validateNumber(I,`lowWaterMark`);let H=[],W=[],q=null,Y=!1,X=!1,eventHandler=(...S)=>{if(W.length>0){let{resolve:n}=W.shift();n({value:S,done:!1})}else H.push(S),H.length>=F&&!X&&(X=!0,typeof n.pause==`function`&&n.pause())},errorHandler=n=>{if(q=n,W.length>0){let{reject:S}=W.shift();S(n)}Z.return()},abortHandler=()=>{errorHandler(createAbortError$2(N))};n.on(S,eventHandler),S!==`error`&&n.on(`error`,errorHandler),N&&N.addEventListener(`abort`,abortHandler,{once:!0});let cleanup=()=>{n.removeListener(S,eventHandler),n.removeListener(`error`,errorHandler),N&&N.removeEventListener(`abort`,abortHandler),Y=!0;for(let{resolve:n}of W)n({value:void 0,done:!0});W.length=0,H.length=0},Z={next(){if(H.length>0){let S=H.shift();return X&&H.length<I&&(X=!1,typeof n.resume==`function`&&n.resume()),Promise.resolve({value:S,done:!1})}if(q){let n=Promise.reject(q);return q=null,n}return Y?Promise.resolve({value:void 0,done:!0}):new Promise((n,S)=>{W.push({resolve:n,reject:S})})},return(){return cleanup(),Promise.resolve({value:void 0,done:!0})},throw(n){return Y||(q=n,cleanup()),Promise.reject(n)},[Symbol.asyncIterator](){return this}};return Z}static listenerCount(n,S){return n.listenerCount(S)}static getEventListeners(n,S){return typeof n.listeners==`function`?n.listeners(S):[]}static setMaxListeners(n,...S){if(validateNumber(n,`n`),n<0)throw RangeError(`The value of "n" is out of range.`);if(S.length===0)EventEmitter.defaultMaxListeners=n;else for(let C of S)typeof C.setMaxListeners==`function`&&C.setMaxListeners(n)}static getMaxListeners(n){return typeof n.getMaxListeners==`function`?n.getMaxListeners():EventEmitter.defaultMaxListeners}static addAbortListener(n,S){n.aborted&&Promise.resolve().then(()=>S());let handler=()=>S();return n.addEventListener(`abort`,handler,{once:!0}),{[Symbol.dispose](){n.removeEventListener(`abort`,handler)}}}},Mt.EventEmitter=Mt;for(let n of[`setMaxListeners`,`getMaxListeners`,`emit`,`addListener`,`on`,`prependListener`,`once`,`prependOnceListener`,`removeListener`,`off`,`removeAllListeners`,`listeners`,`rawListeners`,`listenerCount`,`eventNames`]){let S=Mt.prototype[n];typeof S==`function`&&Object.defineProperty(Mt.prototype,n,{enumerable:!0,configurable:!0,writable:!0,value:S})}Object.defineProperty(Mt.prototype,"_events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(Mt.prototype,"_eventsCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(Mt.prototype,"_maxListeners",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),__name$1(createAbortError$2,`createAbortError`)}),Pt=__exportAll$4({EventEmitter:()=>Ft,addAbortListener:()=>Gt,captureRejectionSymbol:()=>It,default:()=>Ft,defaultMaxListeners:()=>Rt,errorMonitor:()=>Lt,getEventListeners:()=>Ut,getMaxListeners:()=>Bt,listenerCount:()=>Wt,"module.exports":()=>Ft,on:()=>Ht,once:()=>Vt,setMaxListeners:()=>zt}),Ft,It,Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt=__esmMin(()=>{Nt(),Be(),Ft=makeCallable(Mt),Ft.EventEmitter=Ft,It=Ft.captureRejectionSymbol,Lt=Ft.errorMonitor,Rt=Ft.defaultMaxListeners,zt=Ft.setMaxListeners,Bt=Ft.getMaxListeners,Vt=Ft.once,Ht=Ft.on,Ut=Ft.getEventListeners,Wt=Ft.listenerCount,Gt=Ft.addAbortListener});function normalizeAndValidateEncoding(n){return n&&checkEncoding(n),normalizeEncoding(n)}function utf8DecodeMaximalSubpart(n,S,C){let N=``,F=S;for(;F<C;){let S=n[F];if(S<=127){N+=String.fromCharCode(S),F++;continue}if(S>=194&&S<=223){F+1<C&&n[F+1]>=128&&n[F+1]<=191?(N+=String.fromCharCode((S&31)<<6|n[F+1]&63),F+=2):(N+=`�`,F++);continue}if(S>=224&&S<=239){let I,H;if(S===224?(I=160,H=191):S===237?(I=128,H=159):(I=128,H=191),F+1>=C){N+=`�`,F++;continue}let W=n[F+1];if(W<I||W>H){N+=`�`,F++;continue}if(F+2>=C){N+=`�`,F+=2;continue}let q=n[F+2];if(q<128||q>191){N+=`�`,F+=2;continue}let Y=(S&15)<<12|(W&63)<<6|q&63;N+=String.fromCharCode(Y),F+=3;continue}if(S>=240&&S<=244){let I,H;if(S===240?(I=144,H=191):S===244?(I=128,H=143):(I=128,H=191),F+1>=C){N+=`�`,F++;continue}let W=n[F+1];if(W<I||W>H){N+=`�`,F++;continue}if(F+2>=C){N+=`�`,F+=2;continue}let q=n[F+2];if(q<128||q>191){N+=`�`,F+=2;continue}if(F+3>=C){N+=`�`,F+=3;continue}let Y=n[F+3];if(Y<128||Y>191){N+=`�`,F+=3;continue}let X=(S&7)<<18|(W&63)<<12|(q&63)<<6|Y&63;N+=String.fromCharCode(55296+(X-65536>>10),56320+(X-65536&1023)),F+=4;continue}N+=`�`,F++}return N}function utf8CharLength(n){return n&128?n>=194&&n<=223?2:n>=224&&n<=239?3:n>=240&&n<=244?4:0:1}function isValidContinuation(n,S,C,N){if(C===1){if(S===3)return n===224?N>=160&&N<=191:n===237?N>=128&&N<=159:N>=128&&N<=191;if(S===4)return n===240?N>=144&&N<=191:n===244?N>=128&&N<=143:N>=128&&N<=191}return N>=128&&N<=191}function writeUtf8(n,S){let C=0,N=``;if(n._lastNeed>0){for(;C<S.length&&n._lastNeed>0;){let F=S[C],I=n._lastTotal-n._lastNeed;if(isValidContinuation(n._lastLeadByte,n._lastTotal,I,F))n._lastChar[I]=F,n._lastNeed--,C++;else{N+=`�`,n._lastNeed=0,n._lastTotal=0,n._lastLeadByte=0;break}}if(n._lastNeed===0&&n._lastTotal>0&&(N+=utf8DecodeMaximalSubpart(n._lastChar,0,n._lastTotal),n._lastTotal=0,n._lastLeadByte=0),n._lastNeed>0)return N}let F=S.length;for(let N=0;N<Math.min(4,S.length-C);N++){let I=S.length-1-N;if(I<C)break;let H=S[I];if((H&192)!=128){let C=utf8CharLength(H);if(C>0&&H>=128){let N=S.length-I;if(N<C){let W=!0;for(let n=1;n<N;n++)if(!isValidContinuation(H,C,n,S[I+n])){W=!1;break}if(W){F=I;for(let C=0;C<N;C++)n._lastChar[C]=S[I+C];n._lastNeed=C-N,n._lastTotal=C,n._lastLeadByte=H}}}break}}return F>C&&(N+=utf8DecodeMaximalSubpart(S,C,F)),N}function writeUtf16le(n,S){let C=``,N=0;if(n._lastNeed>0){let F=n._lastTotal-n._lastNeed,I=Math.min(n._lastNeed,S.length);for(let C=0;C<I;C++)n._lastChar[F+C]=S[C];if(n._lastNeed-=I,N=I,n._lastNeed>0)return``;let H=n._lastTotal,W=0;for(;W+1<H;){let F=n._lastChar[W]|n._lastChar[W+1]<<8;if(W+=2,F>=55296&&F<=56319){if(W+1<H){let S=n._lastChar[W]|n._lastChar[W+1]<<8;if(S>=56320&&S<=57343){C+=String.fromCharCode(F,S),W+=2;continue}}if(N+1<S.length){let n=S[N]|S[N+1]<<8;if(n>=56320&&n<=57343){C+=String.fromCharCode(F,n),N+=2;continue}}else if(N>=S.length)return n._lastChar[0]=n._lastChar[W-2],n._lastChar[1]=n._lastChar[W-1],n._lastNeed=2,n._lastTotal=4,C}C+=String.fromCharCode(F)}n._lastTotal=0}for(;N+1<S.length;){let F=S[N]|S[N+1]<<8;if(N+=2,F>=55296&&F<=56319)if(N+1<S.length){let n=S[N]|S[N+1]<<8;if(n>=56320&&n<=57343){C+=String.fromCharCode(F,n),N+=2;continue}}else if(N<S.length)return C+=String.fromCharCode(F),n._lastChar[0]=S[N],n._lastNeed=1,n._lastTotal=2,C;else return n._lastChar[0]=S[N-2],n._lastChar[1]=S[N-1],n._lastNeed=2,n._lastTotal=4,C;C+=String.fromCharCode(F)}return N<S.length&&(n._lastChar[0]=S[N],n._lastNeed=1,n._lastTotal=2),C}function writeBase64(n,S){let C=0;if(n._lastNeed>0){let N=Math.min(n._lastNeed,S.length);for(let C=0;C<N;C++)n._lastChar[n._lastTotal-n._lastNeed+C]=S[C],n._lastNeed--;if(C=N,n._lastNeed>0)return``}let N=S.length-C,F=N-N%3,I=``;n._lastTotal>0&&n._lastNeed===0&&(I+=base64Encode$1(n._lastChar.subarray(0,n._lastTotal)),n._lastTotal=0),F>0&&(I+=base64Encode$1(S.subarray(C,C+F)));let H=N-F;if(H>0){for(let N=0;N<H;N++)n._lastChar[N]=S[C+F+N];n._lastNeed=3-H,n._lastTotal=3}return I}function decodeAscii(n){let S=``;for(let C=0;C<n.length;C++)S+=String.fromCharCode(n[C]&127);return S}function decodeLatin1(n){let S=``;for(let C=0;C<n.length;C++)S+=String.fromCharCode(n[C]);return S}function decodeHex(n){let S=``;for(let C=0;C<n.length;C++)S+=n[C].toString(16).padStart(2,`0`);return S}var qt,Jt=__esmMin(()=>{lt(),qt=function StringDecoder(n){this.encoding=normalizeAndValidateEncoding(n),this._lastNeed=0,this._lastTotal=0,this._lastLeadByte=0,this.encoding===`utf8`||this.encoding===`utf16le`?this._lastChar=new Uint8Array(4):this.encoding===`base64`?this._lastChar=new Uint8Array(3):this._lastChar=new Uint8Array},qt.prototype.write=function write(n){if(n.length===0)return``;switch(this.encoding){case`utf8`:return writeUtf8(this,n);case`utf16le`:return writeUtf16le(this,n);case`base64`:return writeBase64(this,n);case`ascii`:return decodeAscii(n);case`latin1`:return decodeLatin1(n);case`hex`:return decodeHex(n);default:return decodeAscii(n)}},qt.prototype.end=function end(n){let S=``;if(n&&n.length>0&&(S=this.write(n)),this.encoding===`utf8`&&this._lastNeed>0)S+=`�`,this._lastNeed=0,this._lastTotal=0;else if(this.encoding===`utf16le`&&this._lastNeed>0){let n=this._lastTotal-this._lastNeed;for(let C=0;C+1<n;C+=2)S+=String.fromCharCode(this._lastChar[C]|this._lastChar[C+1]<<8);this._lastNeed=0,this._lastTotal=0}else if(this.encoding===`base64`&&this._lastNeed>0){let n=this._lastChar.subarray(0,this._lastTotal-this._lastNeed);S+=base64Encode$1(n),this._lastNeed=0,this._lastTotal=0}return S}}),Yt,ProcessWriteStream,ProcessReadStream,Xt=__esmMin(()=>{ye(),mt(),kt(),Kt(),Be(),Jt(),Yt=new TextEncoder,ProcessWriteStream=class extends Ft{fd;writable=!0;_outGio=null;constructor(n){super(),this.fd=n;let S=getGioNamespace();if(S){let n=S.UnixOutputStream??S.OutputStream;if(n)try{this._outGio=n.new(this.fd,!1)}catch{}}}write(n){if(this._outGio)try{let S=typeof n==`string`?Yt.encode(n):n;return this._outGio.write_all(S,null),!0}catch{}return this.fd===2?ve.error(n):ve.log(n),!0}get isTTY(){if(Ot)return Ot.Terminal.is_tty(this.fd);try{let n=getGjsGlobal().imports?.gi?.GLib;if(n)return!!n.log_writer_supports_color(this.fd)}catch{}return!1}get columns(){if(Ot){let[n,,S]=Ot.Terminal.get_size(this.fd);if(n&&S>0)return S}try{let n=getGjsGlobal().imports?.gi?.GLib;if(n){let S=parseInt(n.getenv(`COLUMNS`)??`0`,10);if(S>0)return S}}catch{}return 80}end(){}destroy(){}get rows(){if(Ot){let[n,S]=Ot.Terminal.get_size(this.fd);if(n&&S>0)return S}try{let n=getGjsGlobal().imports?.gi?.GLib;if(n){let S=parseInt(n.getenv(`LINES`)??`0`,10);if(S>0)return S}}catch{}return 24}},ProcessReadStream=class extends Ft{fd;isRaw=!1;_gio=null;_stdinGio=null;_reading=!1;_flowing=!1;_sttyCleanupRegistered=!1;_mainLoopHeld=!1;_pendingRead=!1;_decoder=null;constructor(n){super(),this.fd=n,this._gio=getGioNamespace()}get isTTY(){return Ot?Ot.Terminal.is_tty(this.fd):!1}setRawMode(n){return Ot&&Ot.Terminal.set_raw_mode(this.fd,n)?(this.isRaw=n,this):(this._setRawModeViaStty(n),this.isRaw=n,this)}_setRawModeViaStty(n){try{let S=globalThis.imports?.gi,C=S?.Gio??S?.Gio;if(!C)return;let N=C.SubprocessFlags?.STDIN_INHERIT??2,F=n?[`stty`,`-icanon`,`-echo`,`-icrnl`,`-isig`,`min`,`1`,`time`,`0`]:[`stty`,`icanon`,`echo`,`icrnl`,`isig`];if(new C.SubprocessLauncher({flags:N}).spawnv(F).wait(null),n&&!this._sttyCleanupRegistered){this._sttyCleanupRegistered=!0;let n=globalThis.process;n?.once&&typeof n.once==`function`&&n.once(`exit`,()=>this._setRawModeViaStty(!1))}}catch{}}setEncoding(n){return this._decoder=new qt(n),this}_pushData(n){if(this._decoder){let S=this._decoder.write(n);S.length>0&&this.emit(`data`,S)}else this.emit(`data`,n)}on(n,S){let C=n===`data`&&this.listenerCount(`data`)===0;return super.on(n,S),C&&n===`data`&&this.resume(),this}addListener(n,S){return this.on(n,S)}once(n,S){return super.once(n,S),this}removeListener(n,S){return super.removeListener(n,S),n===`data`&&this.listenerCount(`data`)===0&&this.pause(),this}off(n,S){return this.removeListener(n,S)}removeAllListeners(n){let S=n===void 0||n===`data`?this.listenerCount(`data`)>0:!1;return super.removeAllListeners(n),S&&this.listenerCount(`data`)===0&&this.pause(),this}resume(){return this._flowing=!0,this._gio&&this.fd===0&&!this._reading&&this._startReading(),this}pause(){if(this._flowing=!1,this._reading=!1,this._mainLoopHeld){this._mainLoopHeld=!1;let n=globalThis.imports?.gi,S=n?.GLib??n?.GLib;S?.idle_add?S.idle_add(300,()=>(this._mainLoopHeld||quitMainLoop(),!1)):quitMainLoop()}return this}read(){return null}_startReading(){if(!this._gio||this._reading)return;if(this._pendingRead){this._reading=!0,this._mainLoopHeld||(this._mainLoopHeld=!0,ensureMainLoop());return}if(this._reading=!0,this._mainLoopHeld||(this._mainLoopHeld=!0,ensureMainLoop()),!this._stdinGio){let n=this._gio.UnixInputStream??this._gio.InputStream;if(!n){this._reading=!1;return}try{this._stdinGio=n.new(this.fd,!1)}catch{this._reading=!1;return}}let loop=()=>{if(!this._reading){this._pendingRead=!1;return}this._pendingRead=!0,this._stdinGio.read_bytes_async(4096,0,null,(n,S)=>{this._pendingRead=!1;try{let C=n.read_bytes_finish(S)?.get_data?.()??null;if(C&&C.byteLength>0)this._pushData(Buffer.from(C));else if(C!==null&&C.byteLength===0){if(this._reading=!1,this._decoder){let n=this._decoder.end();n.length>0&&this.emit(`data`,n)}this.emit(`end`);return}}catch{this._reading=!1;return}this._reading&&loop()})};loop()}}});function defineLazy(n,S,C){Object.defineProperty(n,S,{configurable:!0,enumerable:!0,get(){let N=C();return Object.defineProperty(n,S,{value:N,configurable:!0,enumerable:!0,writable:!1}),N}})}var Zt,Process,Qt=__esmMin(()=>{ye(),yt(),bt(),xt(),gt(),St(),Tt(),Xt(),Kt(),Zt=Date.now(),Process=class extends Ft{platform;arch;env;argv;argv0;execPath;pid;ppid;version;versions;title;execArgv;config;exitCode;constructor(){super(),defineLazy(this,`platform`,detectPlatform$1),defineLazy(this,`arch`,detectArch),this.env=getEnvProxy(),this.argv=getArgv(),this.argv0=this.argv[0]||`gjs`,this.execPath=getExecPath(),this.execArgv=globalThis.process?.execArgv??[],this.config=globalThis.process?.config??{target_defaults:{},variables:{}},this.pid=getPid$1(),this.ppid=detectPpid();let n=detectVersionInfo();this.version=n.version,this.versions=n.versions,this.title=n.title,this.on(`newListener`,n=>{isDeliverableSignal(n)&&armSignal(n,n=>this.emit(n,n))}),this.on(`removeListener`,n=>{isDeliverableSignal(n)&&this.listenerCount(n)===0&&disarmSignal(n)})}cwd(){return getCwd()}chdir(n){chdir(n)}kill(n,S){return killPid(n,S)}exit(n){return this.exitCode=n??this.exitCode??0,this.emit(`exit`,this.exitCode),exitProcess(this.exitCode)}nextTick(n,...S){typeof queueMicrotask==`function`?queueMicrotask(()=>n(...S)):Promise.resolve().then(()=>n(...S))}hrtime(n){return hrtime(n)}uptime(){return(Date.now()-Zt)/1e3}memoryUsage(){return memoryUsage()}cpuUsage(n){return cpuUsage(n)}stdout=new ProcessWriteStream(1);stderr=new ProcessWriteStream(2);stdin=new ProcessReadStream(0);abort(){this.exit(1)}umask(n){let S=readUmask();return n!==void 0&&!this._umaskWarned&&(this._umaskWarned=!0,this.emitWarning(`process.umask(0${n.toString(8)}) cannot change the file-creation mask under GJS — there is no umask(2) binding, so the mask is UNCHANGED. Pass an explicit \`mode\` to open/mkdir/writeFile instead; the kernel applies it atomically at creation.`,`UnsupportedWarning`)),S}_umaskWarned=!1;emitWarning(n,S){ve.warn(typeof n==`string`?`(${S||`Warning`}): ${n}`:n.message)}},Process.prototype.hrtime.bigint=function(){return hrtimeBigint()}}),$t,en,tn,nn,rn,an,on,sn=__esmMin(()=>{if(gt(),Qt(),kt(),$t=new Process,Ot)try{let n=new Ot.ResizeWatcher;n.connect(`resized`,(n,S,C)=>{$t.stdout.emit(`resize`),$t.stderr.emit(`resize`)}),n.start()}catch{}en=$t.platform,$t.arch,$t.env,$t.argv,$t.argv0,tn=$t.execPath,$t.pid,$t.ppid,$t.version,$t.versions,$t.cwd.bind($t),$t.chdir.bind($t),$t.exit.bind($t),$t.nextTick.bind($t),nn=Object.assign($t.hrtime.bind($t),{bigint:hrtimeBigint}),$t.uptime.bind($t),$t.memoryUsage.bind($t),$t.cpuUsage.bind($t),$t.kill.bind($t),$t.abort.bind($t),$t.umask.bind($t),$t.emitWarning.bind($t),rn=$t.execArgv,$t.config,an=$t.stdout,$t.stderr,on=$t.stdin});Be(),sn(),typeof Promise.withResolvers!=`function`&&(Promise.withResolvers=function(){let n,S;return{promise:new Promise((C,N)=>{n=C,S=N}),resolve:n,reject:S}}),initErrorV8Methods(Error),`global`in globalThis||Object.defineProperty(globalThis,"global",{value:globalThis,writable:!1,enumerable:!1,configurable:!0}),Object.defineProperty(globalThis,"process",{value:$t,enumerable:!1,writable:!0,configurable:!0}),Be(),typeof globalThis.structuredClone!=`function`&&Object.defineProperty(globalThis,"structuredClone",{value:structuredClone$1,enumerable:!0,writable:!0,configurable:!0});function getGLib(){return globalThis.imports?.gi?.GLib}const cn=getGLib()!==void 0;var GjsifyTimeout=class{_id=null;_refed=!0;_callback;_delay;_args;_repeat;constructor(n,S,C,N){this._callback=n,this._delay=S,this._args=C,this._repeat=N,this._schedule()}_schedule(){let n=getGLib();if(!n)return;let S=n.timeout_add.bind(n);this._id=S(n.PRIORITY_DEFAULT,this._delay,()=>{try{this._callback.apply(globalThis,this._args)}catch(n){setTimeout(()=>{throw n},0)}return this._repeat?n.SOURCE_CONTINUE:(this._id=null,n.SOURCE_REMOVE)})}ref(){return this._refed=!0,this}unref(){return this._refed=!1,this}hasRef(){return this._refed}refresh(){return this._cancel(),this._schedule(),this}_cancel(){this._id!==null&&(getGLib()?.Source.remove(this._id),this._id=null)}[Symbol.toPrimitive](){return this._id}[Symbol.dispose](){this._cancel()}};function removeById(n){n instanceof GjsifyTimeout?n._cancel():typeof n==`number`&&getGLib()?.Source.remove(n)}if(cn){let setT=(n,S=0,...C)=>new GjsifyTimeout(n,Math.max(0,S|0),C,!1),setI=(n,S=0,...C)=>new GjsifyTimeout(n,Math.max(0,S|0),C,!0),n=globalThis;n.setTimeout=setT,n.clearTimeout=removeById,n.setInterval=setI,n.clearInterval=removeById}function setImmediate$2(n,...S){return setTimeout(n,0,...S)}__name$1(setImmediate$2,`setImmediate`);function clearImmediate(n){clearTimeout(n)}`setImmediate`in globalThis||Object.defineProperty(globalThis,"setImmediate",{value:setImmediate$2,enumerable:!0,writable:!0,configurable:!0}),`clearImmediate`in globalThis||Object.defineProperty(globalThis,"clearImmediate",{value:clearImmediate,enumerable:!0,writable:!0,configurable:!0});var ln=__exportAll$4({URL:()=>mn,URLSearchParams:()=>fn,default:()=>hn,domainToASCII:()=>domainToASCII,domainToUnicode:()=>domainToUnicode,fileURLToPath:()=>fileURLToPath,format:()=>format$4,parse:()=>parse$4,pathToFileURL:()=>pathToFileURL,resolve:()=>resolve$4});function platformOrShapeIsWindows(n){return hostOs()===void 0?isWindowsPath(n):isWin32()}function decodeComponent(n){try{return decodeURIComponent(n.replace(/\+/g,` `))}catch{return n}}function percentEncodeUtf8(n){let S=``;for(let C of new TextEncoder().encode(n))S+=`%${C.toString(16).toUpperCase().padStart(2,`0`)}`;return S}function encodeComponent(n){let S=``;for(let C of n)C===` `?S+=`+`:/^[A-Za-z0-9*\-._]$/.test(C)?S+=C:S+=percentEncodeUtf8(C);return S}function encodeQuery(n,S){let C=``;for(let N of n){let n=N.codePointAt(0);C+=n<=32||n>126||N===`"`||N===`#`||N===`<`||N===`>`||S&&N===`'`?percentEncodeUtf8(N):N}return C}function parse$4(n,S,C){if(typeof n!=`string`)throw TypeError(`The "url" argument must be of type string. Received type `+typeof n);let N={protocol:null,slashes:null,auth:null,host:null,port:null,hostname:null,hash:null,search:null,query:null,pathname:null,path:null,href:n},F=n.trim(),I=F.indexOf(`#`);I!==-1&&(N.hash=F.slice(I),F=F.slice(0,I));let H=F.indexOf(`?`);H!==-1&&(N.search=F.slice(H),N.query=S?Object.fromEntries(new fn(F.slice(H+1))):F.slice(H+1),F=F.slice(0,H));let W=/^([a-z][a-z0-9.+-]*:)/i.exec(F);if(W&&(N.protocol=W[1].toLowerCase(),F=F.slice(N.protocol.length)),(C||N.protocol)&&F.startsWith(`//`)&&(N.slashes=!0,F=F.slice(2)),N.slashes||N.protocol&&![`javascript:`,`data:`,`mailto:`].includes(N.protocol)){let n=-1;for(let S=0;S<F.length;S++){let C=F[S];if(C===`/`||C===`\\`){n=S;break}}let S=n===-1?F:F.slice(0,n);F=n===-1?``:F.slice(n);let C=S.lastIndexOf(`@`);C===-1?parseHostPort(S,N):(N.auth=decodeURIComponent(S.slice(0,C)),parseHostPort(S.slice(C+1),N))}return N.pathname=F||(N.slashes?`/`:null),(N.pathname!==null||N.search!==null)&&(N.path=(N.pathname||``)+(N.search||``)),N.href=format$4(N),N}function parseHostPort(n,S){if(!n)return;let C=n.indexOf(`[`);if(C!==-1){let N=n.indexOf(`]`,C);if(N!==-1){let F=n.slice(N+1);F.startsWith(`:`)&&(S.port=F.slice(1)),S.hostname=n.slice(C,N+1),S.host=S.hostname+(S.port?`:`+S.port:``);return}}let N=n.lastIndexOf(`:`);if(N!==-1){let C=n.slice(N+1);/^\d*$/.test(C)?(S.port=C||null,S.hostname=n.slice(0,N).toLowerCase()):S.hostname=n.toLowerCase()}else S.hostname=n.toLowerCase();S.host=S.hostname+(S.port?`:`+S.port:``)}function format$4(n){if(typeof n==`string`)return n;if(n instanceof mn)return n.href;let S=n,C=``;if(S.protocol&&(C+=S.protocol),(S.slashes||S.protocol&&![`javascript:`,`data:`,`mailto:`].includes(S.protocol||``))&&(C+=`//`),S.auth&&(C+=encodeURIComponent(S.auth)+`@`),S.host?C+=S.host:(S.hostname&&(C+=S.hostname),S.port&&(C+=`:`+S.port)),S.pathname&&(C+=S.pathname),S.search)C+=S.search;else if(S.query&&typeof S.query==`object`){let n=new fn(S.query).toString();n&&(C+=`?`+n)}return S.hash&&(C+=S.hash),C}function resolve$4(n,S){return new mn(S,new mn(n,`resolve://`)).href.replace(/^resolve:\/\//,``)}function fileURLToPath(n,S){if(typeof n==`string`&&(n=new mn(n)),!(n instanceof mn))throw TypeError(`The "url" argument must be of type string or URL. Received type `+typeof n);if(n.protocol!==`file:`)throw TypeError(`The URL must be of scheme file`);let C=n.pathname,N=S?.windows??platformOrShapeIsWindows(C.slice(1));for(let n=0;n<C.length;n++){if(C[n]!==`%`)continue;let S=C.codePointAt(n+2)|32,F=C[n+1]===`2`&&S===102,I=C[n+1]===`5`&&S===99;if(N&&(F||I))throw TypeError(`File URL path must not include encoded \\ or / characters`);if(F)throw TypeError(`File URL path must not include encoded / characters`)}if(n.hostname!==``&&n.hostname!==`localhost`){if(!N)throw TypeError(`File URL host must be "localhost" or empty on ${hostOs()??`this platform`}`);return`\\\\${n.hostname}${decodeURIComponent(C).replace(/\//g,`\\`)}`}if(N){let n=decodeURIComponent(C);return/^\/[A-Za-z]:/.test(n)?n.slice(1).replace(/\//g,`\\`):n.replace(/\//g,`\\`)}return decodeURIComponent(C)}function pathToFileURL(n,S){let C=S?.windows??platformOrShapeIsWindows(n),N=n;return C&&isWindowsPath(n)||n.startsWith(`/`)||(typeof globalThis.process?.cwd==`function`?N=globalThis.process.cwd()+`/`+n:ft?.get_current_dir&&(N=ft.get_current_dir()+`/`+n)),new mn(pathToFileUrlHref(N,{windows:C}))}function domainToASCII(n){try{return new mn(`http://${n}`).hostname}catch{return``}}function domainToUnicode(n){try{return new mn(`http://${n}`).hostname}catch{return``}}var un,dn,fn,pn,mn,hn,gn=__esmMin(()=>{pt(),Be(),un=ft.UriFlags.HAS_PASSWORD|ft.UriFlags.ENCODED|ft.UriFlags.SCHEME_NORMALIZE,dn=new WeakMap,fn=class URLSearchParams{_entries=[];constructor(n){if(n)if(typeof n==`string`){let S=n.startsWith(`?`)?n.slice(1):n;if(S)for(let n of S.split(`&`)){if(n===``)continue;let S=n.indexOf(`=`);S===-1?this._entries.push([decodeComponent(n),``]):this._entries.push([decodeComponent(n.slice(0,S)),decodeComponent(n.slice(S+1))])}}else if(Array.isArray(n))for(let[S,C]of n)this._entries.push([String(S),String(C)]);else if(n instanceof URLSearchParams)this._entries=n._entries.map(([n,S])=>[n,S]);else for(let S of Object.keys(n))this._entries.push([S,String(n[S])])}get(n){for(let[S,C]of this._entries)if(S===n)return C;return null}getAll(n){return this._entries.filter(([S])=>S===n).map(([,n])=>n)}set(n,S){let C=!1;if(this._entries=this._entries.filter(([S])=>S===n?C?!1:(C=!0,!0):!0),C){for(let C=0;C<this._entries.length;C++)if(this._entries[C][0]===n){this._entries[C][1]=S;break}}else this._entries.push([n,S]);dn.get(this)?.()}has(n,S){return S===void 0?this._entries.some(([S])=>S===n):this._entries.some(([C,N])=>C===n&&N===S)}delete(n,S){this._entries=S===void 0?this._entries.filter(([S])=>S!==n):this._entries.filter(([C,N])=>!(C===n&&N===S)),dn.get(this)?.()}append(n,S){this._entries.push([n,S]),dn.get(this)?.()}sort(){this._entries.sort((n,S)=>n[0]<S[0]?-1:+(n[0]>S[0])),dn.get(this)?.()}toString(){return this._entries.map(([n,S])=>encodeComponent(n)+`=`+encodeComponent(S)).join(`&`)}forEach(n){for(let[S,C]of this._entries)n(C,S,this)}*entries(){yield*this._entries}*keys(){for(let[n]of this._entries)yield n}*values(){for(let[,n]of this._entries)yield n}[Symbol.iterator](){return this.entries()}get size(){return this._entries.length}},pn=new Set([`http:`,`https:`,`ws:`,`wss:`,`ftp:`,`file:`]),mn=class URL{#e;#t;#n;constructor(n,S){let C=n instanceof URL?n.href:String(n);try{if(S!==void 0){let n=S instanceof URL?S.href:String(S),N=ft.Uri.parse(n,un);this.#e=N.parse_relative(C,un)}else this.#e=ft.Uri.parse(C,un)}catch{throw TypeError(`Invalid URL: ${C}`)}if(!this.#e)throw TypeError(`Invalid URL: ${C}`);this.#n=this.#e.get_query()??null,this.#t=new fn(this.#n||``),dn.set(this.#t,()=>{let n=this.#t.toString();this.#n=n===``?null:n})}get protocol(){return this.#e.get_scheme()+`:`}get hostname(){return(this.#e.get_host()||``).toLowerCase()}get port(){let n=this.#e.get_port();if(n===-1)return``;let S=this.#e.get_scheme();return(S===`http`||S===`ws`)&&n===80||(S===`https`||S===`wss`)&&n===443||S===`ftp`&&n===21?``:String(n)}get host(){let n=this.hostname,S=this.port;return S?`${n}:${S}`:n}get pathname(){return this.#e.get_path()||`/`}get search(){return this.#n?`?`+this.#n:``}set search(n){let S=String(n).replace(/[\t\n\r]/g,``);if(S===``){this.#n=null,this.#t._entries=[];return}let C=S.startsWith(`?`)?S.slice(1):S;this.#n=encodeQuery(C,pn.has(this.protocol)),this.#t._entries=new fn(C)._entries}get hash(){let n=this.#e.get_fragment();return n?`#`+n:``}get origin(){let n=this.protocol;return n===`http:`||n===`https:`||n===`ftp:`?`${n}//${this.host}`:`null`}get username(){return this.#e.get_user()||``}get password(){return this.#e.get_password()||``}get href(){let n=this.protocol,S=this.#e.get_scheme();(S===`http`||S===`https`||S===`ftp`||S===`file`||S===`ws`||S===`wss`||this.hostname)&&(n+=`//`);let C=this.username,N=this.password;C&&(n+=C,N&&(n+=`:`+N),n+=`@`),n+=this.hostname,this.port&&(n+=`:`+this.port);let F=this.pathname;return n+=F,n+=this.#n===null?``:`?${this.#n}`,n+=this.hash,n}get searchParams(){return this.#t}toString(){return this.href}toJSON(){return this.href}static _objectURLPaths=new Map;static _objectURLCounter=0;static createObjectURL(n){let S=n?._tmpPath;if(typeof S==`string`&&S.length>0){let n=`file://${S}`;return URL._objectURLPaths.set(n,S),n}return`file:///dev/null`}static revokeObjectURL(n){let S=URL._objectURLPaths.get(n);S&&(ft.unlink(S),URL._objectURLPaths.delete(n))}},__name$1(parse$4,`parse`),__name$1(format$4,`format`),__name$1(resolve$4,`resolve`),hn={URL:mn,URLSearchParams:fn,parse:parse$4,format:format$4,resolve:resolve$4,fileURLToPath,pathToFileURL,domainToASCII,domainToUnicode}});gn(),typeof globalThis.URL!=`function`&&Object.defineProperty(globalThis,"URL",{value:mn,enumerable:!1,writable:!0,configurable:!0}),typeof globalThis.URLSearchParams!=`function`&&Object.defineProperty(globalThis,"URLSearchParams",{value:fn,enumerable:!1,writable:!0,configurable:!0});var _n=__exportAll$4({PerformanceEntry:()=>xn,PerformanceMark:()=>Cn,PerformanceMeasure:()=>wn,PerformanceObserver:()=>bn,PerformanceObserverEntryList:()=>Sn,default:()=>Tn,eventLoopUtilization:()=>eventLoopUtilization,monitorEventLoopDelay:()=>monitorEventLoopDelay,performance:()=>vn,timerify:()=>timerify});function eventLoopUtilization(n,S){return{idle:0,active:0,utilization:0}}function timerify(n){let wrapped=function(...S){let C=vn.now(),N=n.apply(this,S);return vn.now()-C,N};return Object.defineProperty(wrapped,"name",{value:n.name}),wrapped}function monitorEventLoopDelay(n){let S=new Map;return{enable(){},disable(){},reset(){},percentile(n){return 0},get min(){return 0},get max(){return 0},get mean(){return 0},get stddev(){return 0},get percentiles(){return S}}}var vn,PerformanceObserverStub,PerformanceEntryStub,PerformanceObserverEntryListStub,yn,bn,xn,Sn,Cn,wn,Tn,En=__esmMin(()=>{if(globalThis.performance)vn=globalThis.performance;else{let n,_now;try{let S=globalThis.imports?.gi?.GLib;if(!S)throw Error(`GJS imports.gi.GLib not available`);n=S.get_monotonic_time(),_now=()=>(S.get_monotonic_time()-n)/1e3}catch{let S=Date.now();n=0,_now=()=>Date.now()-S}let S=[],C=Date.now()-_now();vn={timeOrigin:C,now:_now,mark(n){let C={name:n,entryType:`mark`,startTime:_now(),duration:0};return S.push(C),C},measure(n,C,N){let F=0,I=_now();if(C){let n=S.find(n=>n.entryType===`mark`&&n.name===C);n&&(F=n.startTime)}if(N){let n=S.find(n=>n.entryType===`mark`&&n.name===N);n&&(I=n.startTime)}let H={name:n,entryType:`measure`,startTime:F,duration:I-F};return S.push(H),H},getEntries(){return[...S]},getEntriesByName(n){return S.filter(S=>S.name===n)},getEntriesByType(n){return S.filter(S=>S.entryType===n)},clearMarks(n){for(let C=S.length-1;C>=0;C--)S[C].entryType===`mark`&&(!n||S[C].name===n)&&S.splice(C,1)},clearMeasures(n){for(let C=S.length-1;C>=0;C--)S[C].entryType===`measure`&&(!n||S[C].name===n)&&S.splice(C,1)},clearResourceTimings(){},setResourceTimingBufferSize(){},toJSON(){return{timeOrigin:C}}}}PerformanceObserverStub=class{_callback;constructor(n){this._callback=n}observe(n){}disconnect(){}takeRecords(){return[]}},PerformanceEntryStub=class{name=``;entryType=``;startTime=0;duration=0;toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration}}},PerformanceObserverEntryListStub=class{getEntries(){return[]}getEntriesByName(n){return[]}getEntriesByType(n){return[]}},yn=globalThis,bn=yn.PerformanceObserver||PerformanceObserverStub,xn=yn.PerformanceEntry||PerformanceEntryStub,Sn=yn.PerformanceObserverEntryList||PerformanceObserverEntryListStub,Cn=yn.PerformanceMark||class PerformanceMark extends PerformanceEntryStub{},wn=yn.PerformanceMeasure||class PerformanceMeasure extends PerformanceEntryStub{},Tn={performance:vn,PerformanceObserver:bn,PerformanceEntry:xn,PerformanceObserverEntryList:Sn,PerformanceMark:Cn,PerformanceMeasure:wn,eventLoopUtilization,timerify,monitorEventLoopDelay}});En();const Dn=globalThis;globalThis.performance===void 0&&(Dn.performance=vn),typeof Dn.PerformanceObserver!=`function`&&(Dn.PerformanceObserver=bn);const $={IndexSizeError:1,HierarchyRequestError:3,WrongDocumentError:4,InvalidCharacterError:5,NoModificationAllowedError:7,NotFoundError:8,NotSupportedError:9,InUseAttributeError:10,InvalidStateError:11,SyntaxError:12,InvalidModificationError:13,NamespaceError:14,InvalidAccessError:15,TypeMismatchError:17,SecurityError:18,NetworkError:19,AbortError:20,URLMismatchError:21,QuotaExceededError:22,TimeoutError:23,InvalidNodeTypeError:24,DataCloneError:25};var _DOMExceptionPolyfill=class extends Error{code;constructor(n,S){super(n),this.name=S||`Error`,this.code=Object.hasOwn($,this.name)?$[this.name]:0}};const On=globalThis.DOMException===void 0?_DOMExceptionPolyfill:globalThis.DOMException;ye();const kn=Symbol(`type`),An=Symbol(`bubbles`),jn=Symbol(`cancelable`),Mn=Symbol(`composed`),Nn=Symbol(`target`),Pn=Symbol(`currentTarget`),Fn=Symbol(`eventPhase`),In=Symbol(`defaultPrevented`),Ln=Symbol(`isTrusted`),Rn=Symbol(`timeStamp`),zn=Symbol(`stop`),Bn=Symbol(`immediateStop`),Vn=Symbol(`dispatching`),Hn=Symbol(`inPassiveListener`);var Event=class{[kn];[An];[jn];[Mn];[Nn]=null;[Pn]=null;[Fn]=0;[In]=!1;[Ln]=!1;[Rn];[zn]=!1;[Bn]=!1;[Vn]=!1;[Hn]=!1;get type(){return this[kn]}get bubbles(){return this[An]}get cancelable(){return this[jn]}get composed(){return this[Mn]}get target(){return this[Nn]}get currentTarget(){return this[Pn]}get eventPhase(){return this[Fn]}get defaultPrevented(){return this[In]}get timeStamp(){return this[Rn]}get cancelBubble(){return this[zn]}set cancelBubble(n){n&&this.stopPropagation()}get returnValue(){return!this[In]}set returnValue(n){n||this.preventDefault()}get srcElement(){return this[Nn]}static NONE=0;static CAPTURING_PHASE=1;static AT_TARGET=2;static BUBBLING_PHASE=3;get[Symbol.toStringTag](){return`Event`}constructor(n,S){this[kn]=n,this[An]=S?.bubbles??!1,this[jn]=S?.cancelable??!1,this[Mn]=S?.composed??!1,this[Rn]=Date.now(),Object.defineProperty(this,"isTrusted",{get:()=>this[Ln],enumerable:!0,configurable:!1})}composedPath(){return this[Pn]?[this[Pn]]:[]}preventDefault(){this[jn]&&!this[Hn]&&(this[In]=!0)}stopPropagation(){this[zn]=!0}stopImmediatePropagation(){this[zn]=!0,this[Bn]=!0}},EventTarget=class{#e=new Map;get[Symbol.toStringTag](){return`EventTarget`}addEventListener(n,S,C){if(S===null)return;let N=typeof C==`boolean`?C:C?.capture??!1,F=typeof C==`object`?C?.once??!1:!1,I=typeof C==`object`?C?.passive??!1:!1,H=this.#e.get(n);H||(H=[],this.#e.set(n,H));for(let n of H)if(n.listener===S&&n.capture===N)return;let W={listener:S,capture:N,once:F,passive:I,removed:!1};H.push(W),typeof C==`object`&&C?.signal&&C.signal.addEventListener(`abort`,()=>{this.removeEventListener(n,S,{capture:N})},{once:!0})}removeEventListener(n,S,C){if(S===null)return;let N=typeof C==`boolean`?C:C?.capture??!1,F=this.#e.get(n);if(!F)return;let I=F.findIndex(n=>n.listener===S&&n.capture===N);I!==-1&&(F[I].removed=!0,F.splice(I,1),F.length===0&&this.#e.delete(n))}dispatchEvent(n){let S=n;if(S[Vn])throw new On(`The event is already being dispatched.`,`InvalidStateError`);S[Vn]=!0,S[Nn]=this,S[Pn]=this,S[Fn]=Event.AT_TARGET;try{let C=this.#e.get(n.type);if(C){let N=[...C];for(let C of N)if(!C.removed){if(S[Bn]||S[zn])break;C.once&&this.removeEventListener(n.type,C.listener,{capture:C.capture});try{C.passive&&(S[Hn]=!0),typeof C.listener==`function`?C.listener.call(this,n):typeof C.listener.handleEvent==`function`&&C.listener.handleEvent.call(C.listener,n)}catch(n){reportListenerException(n)}finally{S[Hn]=!1}}}}finally{S[Fn]=Event.NONE,S[Pn]=null,S[Vn]=!1}return!n.defaultPrevented}};function reportListenerException(n){try{let S=globalThis;if(typeof S.reportError==`function`)S.reportError(n);else if(n instanceof Error){let S=`${n.name}: ${n.message}`;ve.error(n.stack?`${S}\n${n.stack}`:S)}else ve.error(String(n))}catch{}}for(let[n,S]of[[`NONE`,0],[`CAPTURING_PHASE`,1],[`AT_TARGET`,2],[`BUBBLING_PHASE`,3]])Object.defineProperty(Event.prototype,n,{value:S,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Event,n,{value:S,writable:!1,enumerable:!0,configurable:!1});const Un=Symbol(`abort`),Wn=Symbol(`internal`);var Gn=class AbortSignal extends EventTarget{#e=!1;#t=void 0;onabort=null;constructor(n){if(super(),n!==Wn)throw TypeError(`Illegal constructor.`)}get aborted(){if(!(this instanceof AbortSignal))throw TypeError(`'get aborted' called on an object that is not a valid instance of AbortSignal.`);return this.#e}get reason(){return this.#t}get[Symbol.toStringTag](){return`AbortSignal`}throwIfAborted(){if(this.#e)throw this.#t}[Un](n){if(this.#e)return;this.#e=!0,this.#t=n??new On(`The operation was aborted.`,`AbortError`);let S=new Event(`abort`);typeof this.onabort==`function`&&this.onabort.call(this,S),this.dispatchEvent(S)}static abort(n){let S=new AbortSignal(Wn);return S[Un](n),S}static timeout(n){let S=new AbortSignal(Wn);return setTimeout(()=>{S[Un](new On(`The operation timed out.`,`TimeoutError`))},n),S}static any(n){let S=new AbortSignal(Wn);for(let C of n)if(C.aborted)return S[Un](C.reason),S;let onAbort=()=>{if(!S.aborted){let C=n.find(n=>n.aborted);S[Un](C?.reason)}};for(let S of n)S.addEventListener(`abort`,onAbort,{once:!0});return S}},Kn=class AbortController{signal;constructor(){this.signal=new Gn(Wn)}get[Symbol.toStringTag](){return`AbortController`}abort(n){if(!(this instanceof AbortController))throw TypeError(`'abort' called on an object that is not a valid instance of AbortController.`);this.signal[Un](n)}};const qn=globalThis;globalThis.AbortController===void 0&&(qn.AbortController=Kn),globalThis.AbortSignal===void 0&&(qn.AbortSignal=Gn);const Jn=Symbol(`kState`),Yn=Symbol(`kType`);function isBrandCheck(n){return S=>typeof S==`object`&&!!S&&S[Jn]!==void 0&&S[Yn]===n}function dequeueValue(n){let S=n[Jn].queue.shift();if(S===void 0)throw Error(`dequeueValue called on an empty queue`);let{value:C,size:N}=S;return n[Jn].queueTotalSize=Math.max(0,n[Jn].queueTotalSize-N),C}function resetQueue(n){n[Jn].queue=[],n[Jn].queueTotalSize=0}function peekQueueValue(n){return n[Jn].queue[0].value}function enqueueValueWithSize(n,S,C){if(C=+C,typeof C!=`number`||C<0||Number.isNaN(C)||C===1/0)throw RangeError(`Invalid size: ${C}`);n[Jn].queue.push({value:S,size:C}),n[Jn].queueTotalSize+=C}function extractHighWaterMark(n,S){if(n===void 0)return S;if(n=+n,typeof n!=`number`||Number.isNaN(n)||n<0)throw RangeError(`Invalid highWaterMark: ${n}`);return n}function extractSizeAlgorithm(n){if(n===void 0)return()=>1;if(typeof n!=`function`)throw TypeError(`strategy.size must be a function`);return n}function transferArrayBuffer(n){return typeof ArrayBuffer.prototype.transfer==`function`?n.transfer():n.slice(0)}function isDetachedBuffer(n){if(typeof SharedArrayBuffer<`u`&&n instanceof SharedArrayBuffer||n.byteLength!==0)return!1;try{return n.slice(0,0),!1}catch{return!0}}function typedArrayConstructorByTag(n){switch(n){case`Int8Array`:return Int8Array;case`Uint8Array`:return Uint8Array;case`Uint8ClampedArray`:return Uint8ClampedArray;case`Int16Array`:return Int16Array;case`Uint16Array`:return Uint16Array;case`Int32Array`:return Int32Array;case`Uint32Array`:return Uint32Array;case`Float32Array`:return Float32Array;case`Float64Array`:return Float64Array;case`BigInt64Array`:return typeof BigInt64Array<`u`?BigInt64Array:void 0;case`BigUint64Array`:return typeof BigUint64Array<`u`?BigUint64Array:void 0;default:return}}function elementSizeByTag(n){switch(n){case`Int8Array`:case`Uint8Array`:case`Uint8ClampedArray`:return 1;case`Int16Array`:case`Uint16Array`:return 2;case`Int32Array`:case`Uint32Array`:case`Float32Array`:return 4;case`Float64Array`:case`BigInt64Array`:case`BigUint64Array`:return 8;default:return 1}}function setPromiseHandled(n){n.then(()=>{},()=>{})}function createPromiseCallback(n,S,C){if(typeof S!=`function`)throw TypeError(`${n} must be a function`);return async(...n)=>S.call(C,...n)}async function nonOpFlush(){}function nonOpStart(){}async function nonOpPull(){}async function nonOpCancel(){}async function nonOpWrite(){}const Xn={__proto__:Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),next:void 0,return:void 0};function createAsyncFromSyncIterator(n){let S={[Symbol.iterator]:()=>n.iterator},C=(async function*(){return yield*S})();return{iterator:C,nextMethod:C.next,done:!1}}function getIterator(n,S=`sync`,C){if(C===void 0)if(S===`async`){if(C=n[Symbol.asyncIterator],C==null){let S=n[Symbol.iterator];if(S===void 0)throw TypeError(`Object is not iterable`);return createAsyncFromSyncIterator(getIterator(n,`sync`,S))}}else C=n[Symbol.iterator];if(C===void 0)throw TypeError(`Object is not iterable`);let N=C.call(n);if(typeof N!=`object`||!N)throw TypeError(`The iterator method must return an object`);return{iterator:N,nextMethod:N.next,done:!1}}function iteratorNext(n,S){let C;if(C=S===void 0?n.nextMethod.call(n.iterator):n.nextMethod.call(n.iterator,S),typeof C!=`object`||!C)throw TypeError(`The iterator.next() method must return an object`);return C}const Zn=typeof globalThis.AbortController==`function`?globalThis.AbortController:class AbortControllerShim{signal={aborted:!1,reason:void 0,addEventListener(){},removeEventListener(){}};abort(n){this.signal.aborted=!0,this.signal.reason=n}},Qn=Symbol(`kAbort`),$n=Symbol(`kCloseSentinel`),er=Symbol(`kError`),tr=Symbol(`kSkipThrow`);var WritableStream=class{[Yn]=`WritableStream`;[Jn];constructor(n={},S={}){if(n!=null&&typeof n!=`object`)throw TypeError(`sink must be an object`);if(S!=null&&typeof S!=`object`)throw TypeError(`strategy must be an object`);let C=n?.type;if(C!==void 0)throw RangeError(`Invalid type: ${C}`);this[Jn]=createWritableStreamState();let N=extractSizeAlgorithm(S?.size),F=extractHighWaterMark(S?.highWaterMark,1);setupWritableStreamDefaultControllerFromSink(this,n,F,N)}get locked(){if(!nr(this))throw TypeError(`Invalid this`);return isWritableStreamLocked(this)}abort(n){return nr(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamAbort(this,n):Promise.reject(TypeError(`Invalid this`))}close(){return nr(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamCloseQueuedOrInFlight(this)?Promise.reject(TypeError(`Failure closing WritableStream`)):writableStreamClose(this):Promise.reject(TypeError(`Invalid this`))}getWriter(){if(!nr(this))throw TypeError(`Invalid this`);return new WritableStreamDefaultWriter(this)}get[Symbol.toStringTag](){return`WritableStream`}},WritableStreamDefaultWriter=class{[Yn]=`WritableStreamDefaultWriter`;[Jn];constructor(n){if(!nr(n))throw TypeError(`Expected a WritableStream`);this[Jn]={stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0},ready:{promise:void 0,resolve:void 0,reject:void 0}},setupWritableStreamDefaultWriter(this,n)}get closed(){return rr(this)?this[Jn].close.promise:Promise.reject(TypeError(`Invalid this`))}get desiredSize(){if(!rr(this))throw TypeError(`Invalid this`);if(this[Jn].stream===void 0)throw TypeError(`Writer is not bound to a WritableStream`);return writableStreamDefaultWriterGetDesiredSize(this)}get ready(){return rr(this)?this[Jn].ready.promise:Promise.reject(TypeError(`Invalid this`))}abort(n){return rr(this)?this[Jn].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterAbort(this,n):Promise.reject(TypeError(`Invalid this`))}close(){if(!rr(this))return Promise.reject(TypeError(`Invalid this`));let{stream:n}=this[Jn];return n===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamCloseQueuedOrInFlight(n)?Promise.reject(TypeError(`Failure to close WritableStream`)):writableStreamDefaultWriterClose(this)}releaseLock(){if(!rr(this))throw TypeError(`Invalid this`);let{stream:n}=this[Jn];n!==void 0&&writableStreamDefaultWriterRelease(this)}write(n){return rr(this)?this[Jn].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterWrite(this,n):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`WritableStreamDefaultWriter`}},WritableStreamDefaultController=class{[Yn]=`WritableStreamDefaultController`;[Jn];constructor(n){if(n!==tr)throw TypeError(`Illegal constructor`)}[Qn](n){let S=this[Jn].abortAlgorithm(n);return writableStreamDefaultControllerClearAlgorithms(this),S}[er](){resetQueue(this)}get signal(){if(!ir(this))throw TypeError(`Invalid this`);return this[Jn].abortController.signal}error(n){if(!ir(this))throw TypeError(`Invalid this`);this[Jn].stream[Jn].state===`writable`&&writableStreamDefaultControllerError(this,n)}get[Symbol.toStringTag](){return`WritableStreamDefaultController`}};const nr=isBrandCheck(`WritableStream`),rr=isBrandCheck(`WritableStreamDefaultWriter`),ir=isBrandCheck(`WritableStreamDefaultController`);function createEmptyPromiseRecord(){return{promise:void 0,resolve:void 0,reject:void 0}}function createWritableStreamState(){return{close:Promise.withResolvers(),closeRequest:createEmptyPromiseRecord(),inFlightWriteRequest:createEmptyPromiseRecord(),inFlightCloseRequest:createEmptyPromiseRecord(),pendingAbortRequest:{abort:createEmptyPromiseRecord(),reason:void 0,wasAlreadyErroring:!1},backpressure:!1,controller:void 0,state:`writable`,storedError:void 0,writeRequests:[],writer:void 0}}function isWritableStreamLocked(n){return n[Jn].writer!==void 0}function setupWritableStreamDefaultWriter(n,S){if(isWritableStreamLocked(S))throw TypeError(`WritableStream is locked`);switch(n[Jn].stream=S,S[Jn].writer=n,S[Jn].state){case`writable`:!writableStreamCloseQueuedOrInFlight(S)&&S[Jn].backpressure?n[Jn].ready=Promise.withResolvers():n[Jn].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},n[Jn].close=Promise.withResolvers();break;case`erroring`:n[Jn].ready={promise:Promise.reject(S[Jn].storedError),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].ready.promise),n[Jn].close=Promise.withResolvers();break;case`closed`:n[Jn].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},n[Jn].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;default:n[Jn].ready={promise:Promise.reject(S[Jn].storedError),resolve:void 0,reject:void 0},n[Jn].close={promise:Promise.reject(S[Jn].storedError),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].ready.promise),setPromiseHandled(n[Jn].close.promise)}}function writableStreamAbort(n,S){let{state:C,controller:N}=n[Jn];if(C===`closed`||C===`errored`)return Promise.resolve();if(N[Jn].abortController.abort(S),n[Jn].pendingAbortRequest.abort.promise!==void 0)return n[Jn].pendingAbortRequest.abort.promise;let F=!1;C===`erroring`&&(F=!0,S=void 0);let I=Promise.withResolvers();return n[Jn].pendingAbortRequest={abort:I,reason:S,wasAlreadyErroring:F},F||writableStreamStartErroring(n,S),I.promise}function writableStreamClose(n){let{state:S,writer:C,backpressure:N,controller:F}=n[Jn];if(S===`closed`||S===`errored`)return Promise.reject(TypeError(`WritableStream is closed`));n[Jn].closeRequest=Promise.withResolvers();let{promise:I}=n[Jn].closeRequest;return C!==void 0&&N&&S===`writable`&&C[Jn].ready.resolve?.(),writableStreamDefaultControllerClose(F),I}function writableStreamUpdateBackpressure(n,S){let{writer:C}=n[Jn];C!==void 0&&n[Jn].backpressure!==S&&(S?C[Jn].ready=Promise.withResolvers():C[Jn].ready.resolve?.()),n[Jn].backpressure=S}function writableStreamStartErroring(n,S){let{controller:C,writer:N}=n[Jn];n[Jn].state=`erroring`,n[Jn].storedError=S,N!==void 0&&writableStreamDefaultWriterEnsureReadyPromiseRejected(N,S),!writableStreamHasOperationMarkedInFlight(n)&&C[Jn].started&&writableStreamFinishErroring(n)}function writableStreamRejectCloseAndClosedPromiseIfNeeded(n){n[Jn].closeRequest.promise!==void 0&&(n[Jn].closeRequest.reject?.(n[Jn].storedError),n[Jn].closeRequest={promise:void 0,resolve:void 0,reject:void 0}),setPromiseHandled(n[Jn].close.promise),n[Jn].close.reject?.(n[Jn].storedError);let{writer:S}=n[Jn];S!==void 0&&(setPromiseHandled(S[Jn].close.promise),S[Jn].close.reject?.(n[Jn].storedError))}function writableStreamMarkFirstWriteRequestInFlight(n){let S=n[Jn].writeRequests.shift();n[Jn].inFlightWriteRequest=S}function writableStreamMarkCloseRequestInFlight(n){n[Jn].inFlightCloseRequest=n[Jn].closeRequest,n[Jn].closeRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamHasOperationMarkedInFlight(n){return n[Jn].inFlightWriteRequest.promise!==void 0||n[Jn].inFlightCloseRequest.promise!==void 0}function writableStreamFinishInFlightWriteWithError(n,S){n[Jn].inFlightWriteRequest.reject?.(S),n[Jn].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0},writableStreamDealWithRejection(n,S)}function writableStreamFinishInFlightWrite(n){n[Jn].inFlightWriteRequest.resolve?.(),n[Jn].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamFinishInFlightCloseWithError(n,S){n[Jn].inFlightCloseRequest.reject?.(S),n[Jn].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},n[Jn].pendingAbortRequest.abort.promise!==void 0&&(n[Jn].pendingAbortRequest.abort.reject?.(S),n[Jn].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1}),writableStreamDealWithRejection(n,S)}function writableStreamFinishInFlightClose(n){n[Jn].inFlightCloseRequest.resolve?.(),n[Jn].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},n[Jn].state===`erroring`&&(n[Jn].storedError=void 0,n[Jn].pendingAbortRequest.abort.promise!==void 0&&(n[Jn].pendingAbortRequest.abort.resolve?.(),n[Jn].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1})),n[Jn].state=`closed`,n[Jn].writer!==void 0&&n[Jn].writer[Jn].close.resolve?.(),n[Jn].close.resolve?.()}function writableStreamFinishErroring(n){n[Jn].state=`errored`,n[Jn].controller[er]();let S=n[Jn].storedError;for(let C of n[Jn].writeRequests)C.reject?.(S);if(n[Jn].writeRequests=[],n[Jn].pendingAbortRequest.abort.promise===void 0){writableStreamRejectCloseAndClosedPromiseIfNeeded(n);return}let C=n[Jn].pendingAbortRequest;if(n[Jn].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1},C.wasAlreadyErroring){C.abort.reject?.(S),writableStreamRejectCloseAndClosedPromiseIfNeeded(n);return}n[Jn].controller[Qn](C.reason).then(()=>{C.abort.resolve?.(),writableStreamRejectCloseAndClosedPromiseIfNeeded(n)},S=>{C.abort.reject?.(S),writableStreamRejectCloseAndClosedPromiseIfNeeded(n)})}function writableStreamDealWithRejection(n,S){if(n[Jn].state===`writable`){writableStreamStartErroring(n,S);return}writableStreamFinishErroring(n)}function writableStreamCloseQueuedOrInFlight(n){return n[Jn].closeRequest.promise!==void 0||n[Jn].inFlightCloseRequest.promise!==void 0}function writableStreamAddWriteRequest(n){let{promise:S,resolve:C,reject:N}=Promise.withResolvers();return n[Jn].writeRequests.push({promise:S,resolve:C,reject:N}),S}function writableStreamDefaultWriterWrite(n,S){let{stream:C}=n[Jn],{controller:N}=C[Jn],F=writableStreamDefaultControllerGetChunkSize(N,S);if(C!==n[Jn].stream)return Promise.reject(TypeError(`Mismatched WritableStreams`));let{state:I}=C[Jn];if(I===`errored`)return Promise.reject(C[Jn].storedError);if(writableStreamCloseQueuedOrInFlight(C)||I===`closed`)return Promise.reject(TypeError(`WritableStream is closed`));if(I===`erroring`)return Promise.reject(C[Jn].storedError);let H=writableStreamAddWriteRequest(C);return writableStreamDefaultControllerWrite(N,S,F),H}function writableStreamDefaultWriterRelease(n){let{stream:S}=n[Jn],C=TypeError(`Writer has been released`);writableStreamDefaultWriterEnsureReadyPromiseRejected(n,C),writableStreamDefaultWriterEnsureClosedPromiseRejected(n,C),S[Jn].writer=void 0,n[Jn].stream=void 0}function writableStreamDefaultWriterGetDesiredSize(n){let{stream:S}=n[Jn];switch(S[Jn].state){case`errored`:case`erroring`:return null;case`closed`:return 0}return writableStreamDefaultControllerGetDesiredSize(S[Jn].controller)}function writableStreamDefaultWriterEnsureReadyPromiseRejected(n,S){n[Jn].ready.reject?(n[Jn].ready.reject(S),n[Jn].ready.resolve=void 0,n[Jn].ready.reject=void 0):n[Jn].ready={promise:Promise.reject(S),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].ready.promise)}function writableStreamDefaultWriterEnsureClosedPromiseRejected(n,S){n[Jn].close.reject?(n[Jn].close.reject(S),n[Jn].close.resolve=void 0,n[Jn].close.reject=void 0):n[Jn].close={promise:Promise.reject(S),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].close.promise)}function writableStreamDefaultWriterCloseWithErrorPropagation(n){let{stream:S}=n[Jn],{state:C}=S[Jn];return writableStreamCloseQueuedOrInFlight(S)||C===`closed`?Promise.resolve():C===`errored`?Promise.reject(S[Jn].storedError):writableStreamDefaultWriterClose(n)}function writableStreamDefaultWriterClose(n){return writableStreamClose(n[Jn].stream)}function writableStreamDefaultWriterAbort(n,S){return writableStreamAbort(n[Jn].stream,S)}function writableStreamDefaultControllerWrite(n,S,C){try{enqueueValueWithSize(n,S,C)}catch(S){writableStreamDefaultControllerErrorIfNeeded(n,S);return}let{stream:N}=n[Jn];!writableStreamCloseQueuedOrInFlight(N)&&N[Jn].state===`writable`&&writableStreamUpdateBackpressure(N,writableStreamDefaultControllerGetBackpressure(n)),writableStreamDefaultControllerAdvanceQueueIfNeeded(n)}function writableStreamDefaultControllerProcessWrite(n,S){let{stream:C,writeAlgorithm:N}=n[Jn];writableStreamMarkFirstWriteRequestInFlight(C),N(S,n).then(()=>{writableStreamFinishInFlightWrite(C);let{state:S}=C[Jn];dequeueValue(n),!writableStreamCloseQueuedOrInFlight(C)&&S===`writable`&&writableStreamUpdateBackpressure(C,writableStreamDefaultControllerGetBackpressure(n)),writableStreamDefaultControllerAdvanceQueueIfNeeded(n)},S=>{C[Jn].state===`writable`&&writableStreamDefaultControllerClearAlgorithms(n),writableStreamFinishInFlightWriteWithError(C,S)})}function writableStreamDefaultControllerProcessClose(n){let{closeAlgorithm:S,stream:C}=n[Jn];writableStreamMarkCloseRequestInFlight(C),dequeueValue(n);let N=S();writableStreamDefaultControllerClearAlgorithms(n),N.then(()=>writableStreamFinishInFlightClose(C),n=>writableStreamFinishInFlightCloseWithError(C,n))}function writableStreamDefaultControllerGetDesiredSize(n){return n[Jn].highWaterMark-n[Jn].queueTotalSize}function writableStreamDefaultControllerGetChunkSize(n,S){let{sizeAlgorithm:C}=n[Jn];if(C===void 0)return 1;try{return C(S)}catch(S){return writableStreamDefaultControllerErrorIfNeeded(n,S),1}}function writableStreamDefaultControllerErrorIfNeeded(n,S){n[Jn].stream[Jn].state===`writable`&&writableStreamDefaultControllerError(n,S)}function writableStreamDefaultControllerError(n,S){writableStreamDefaultControllerClearAlgorithms(n),writableStreamStartErroring(n[Jn].stream,S)}function writableStreamDefaultControllerClose(n){enqueueValueWithSize(n,$n,0),writableStreamDefaultControllerAdvanceQueueIfNeeded(n)}function writableStreamDefaultControllerClearAlgorithms(n){n[Jn].writeAlgorithm=void 0,n[Jn].closeAlgorithm=void 0,n[Jn].abortAlgorithm=void 0,n[Jn].sizeAlgorithm=void 0}function writableStreamDefaultControllerGetBackpressure(n){return writableStreamDefaultControllerGetDesiredSize(n)<=0}function writableStreamDefaultControllerAdvanceQueueIfNeeded(n){let{queue:S,started:C,stream:N}=n[Jn];if(!C||N[Jn].inFlightWriteRequest.promise!==void 0)return;if(N[Jn].state===`erroring`){writableStreamFinishErroring(N);return}if(!S.length)return;let F=peekQueueValue(n);F===$n?writableStreamDefaultControllerProcessClose(n):writableStreamDefaultControllerProcessWrite(n,F)}function setupWritableStreamDefaultControllerFromSink(n,S,C,N){let F=new WritableStreamDefaultController(tr),I=S?.start,H=S?.write,W=S?.close,q=S?.abort;setupWritableStreamDefaultController(n,F,I?I.bind(S,F):nonOpStart,H?createPromiseCallback(`sink.write`,H,S):nonOpWrite,W?createPromiseCallback(`sink.close`,W,S):nonOpCancel,q?createPromiseCallback(`sink.abort`,q,S):nonOpCancel,C,N)}function setupWritableStreamDefaultController(n,S,C,N,F,I,H,W){S[Jn]={abortAlgorithm:I,closeAlgorithm:F,highWaterMark:H,queue:[],queueTotalSize:0,abortController:new Zn,sizeAlgorithm:W,started:!1,stream:n,writeAlgorithm:N},n[Jn].controller=S,writableStreamUpdateBackpressure(n,writableStreamDefaultControllerGetBackpressure(S));let q=C();new Promise(n=>n(q)).then(()=>{S[Jn].started=!0,writableStreamDefaultControllerAdvanceQueueIfNeeded(S)},C=>{S[Jn].started=!0,writableStreamDealWithRejection(n,C)})}function createWritableStream(n,S,C,N,F=1,I=()=>1){let H=Object.create(WritableStream.prototype);return H[Yn]=`WritableStream`,H[Jn]=createWritableStreamState(),setupWritableStreamDefaultController(H,new WritableStreamDefaultController(tr),n,S,C,N,F,I),H}Be();const ar=Symbol(`kCancel`),sr=Symbol(`kClose`),cr=Symbol(`kChunk`),lr=Symbol(`kError`),ur=Symbol(`kPull`),dr=Symbol(`kRelease`),fr=Symbol(`kSkipThrow`);let pr,mr;function lazyReadableReleasedError(){return pr||(pr=TypeError(`Reader released`),pr)}function lazyReadableReleasingError(){return mr||(mr=TypeError(`Releasing reader`),mr)}function createAbortError$1(){if(typeof globalThis.DOMException==`function`)return new DOMException(`The operation was aborted`,`AbortError`);let n=Error(`The operation was aborted`);return n.name=`AbortError`,n}__name$1(createAbortError$1,`createAbortError`);function createReadableStreamState(){return{disturbed:!1,reader:void 0,state:`readable`,storedError:void 0,controller:void 0,closedPromise:Promise.withResolvers()}}var ReadableStream$1=class{static{__name$1(this,`ReadableStream`)}[Yn]=`ReadableStream`;[Jn];constructor(n={},S={}){if(n!=null&&typeof n!=`object`)throw TypeError(`source must be an object`);if(S!=null&&typeof S!=`object`)throw TypeError(`strategy must be an object`);this[Jn]=createReadableStreamState();let C=S?.size,N=S?.highWaterMark,F=n?.type;if(F!==void 0){if(`${F}`==`bytes`){if(C!==void 0)throw RangeError(`strategy.size must not be set for a byte stream`);setupReadableByteStreamControllerFromSource(this,n,extractHighWaterMark(N,0));return}throw RangeError(`Invalid type: ${F}`)}setupReadableStreamDefaultControllerFromSource(this,n,extractHighWaterMark(N,1),extractSizeAlgorithm(C))}get locked(){if(!hr(this))throw TypeError(`Invalid this`);return isReadableStreamLocked(this)}static from(n){return readableStreamFromIterable(n)}cancel(n=void 0){return hr(this)?isReadableStreamLocked(this)?Promise.reject(TypeError(`ReadableStream is locked`)):readableStreamCancel(this,n):Promise.reject(TypeError(`Invalid this`))}getReader(n={}){if(!hr(this))throw TypeError(`Invalid this`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let S=n?.mode;if(S===void 0)return new ReadableStreamDefaultReader(this);if(`${S}`==`byob`)return new ReadableStreamBYOBReader(this);throw RangeError(`Invalid mode: ${S}`)}pipeThrough(n,S={}){if(!hr(this))throw TypeError(`Invalid this`);let C=n?.readable;if(!hr(C))throw TypeError(`transform.readable must be a ReadableStream`);let N=n?.writable;if(!nr(N))throw TypeError(`transform.writable must be a WritableStream`);if(S!=null&&typeof S!=`object`)throw TypeError(`options must be an object`);let F=S?.preventAbort,I=S?.preventCancel,H=S?.preventClose,W=S?.signal;if(W!==void 0&&!(W instanceof Object&&`aborted`in W))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(N))throw TypeError(`The WritableStream is locked`);return setPromiseHandled(readableStreamPipeTo(this,N,!!H,!!F,!!I,W)),C}pipeTo(n,S={}){try{if(!hr(this))throw TypeError(`Invalid this`);if(!nr(n))throw TypeError(`destination must be a WritableStream`);if(S!=null&&typeof S!=`object`)throw TypeError(`options must be an object`);let C=S?.preventAbort,N=S?.preventCancel,F=S?.preventClose,I=S?.signal;if(I!==void 0&&!(I instanceof Object&&`aborted`in I))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(n))throw TypeError(`The WritableStream is locked`);return readableStreamPipeTo(this,n,!!F,!!C,!!N,I)}catch(n){return Promise.reject(n)}}tee(){if(!hr(this))throw TypeError(`Invalid this`);let n=this[Jn].controller;return vr(n)?readableByteStreamTee(this):readableStreamDefaultTee(this,!1)}values(n={}){if(!hr(this))throw TypeError(`Invalid this`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let S=!!n?.preventCancel,C=new ReadableStreamDefaultReader(this),N={done:!1,current:void 0},F=!1;function nextSteps(){if(N.done)return Promise.resolve({done:!0,value:void 0});if(C[Jn].stream===void 0)return Promise.reject(TypeError(`The reader is not bound to a ReadableStream`));let{promise:n,resolve:S,reject:F}=Promise.withResolvers();return readableStreamDefaultReaderRead(C,{[cr](n){N.current=void 0,S({value:n,done:!1})},[sr](){N.current=void 0,N.done=!0,readableStreamReaderGenericRelease(C),S({done:!0,value:void 0})},[lr](n){N.current=void 0,N.done=!0,readableStreamReaderGenericRelease(C),F(n)}}),n}async function returnSteps(n){if(N.done)return{done:!0,value:n};if(N.done=!0,C[Jn].stream===void 0)throw TypeError(`The reader is not bound to a ReadableStream`);if(!S){let S=readableStreamReaderGenericCancel(C,n);return readableStreamReaderGenericRelease(C),await S,{done:!0,value:n}}return readableStreamReaderGenericRelease(C),{done:!0,value:n}}return Object.setPrototypeOf({next(){return F||=(N.current=Promise.resolve(),!0),N.current=N.current===void 0?nextSteps():N.current.then(nextSteps,nextSteps),N.current},return(n){return F=!0,N.current=N.current===void 0?returnSteps(n):N.current.then(()=>returnSteps(n),()=>returnSteps(n)),N.current},[Symbol.asyncIterator](){return this}},Xn)}[Symbol.asyncIterator](){return this.values()}get[Symbol.toStringTag](){return`ReadableStream`}},DefaultReadRequest=class{[Jn];constructor(){this[Jn]=Promise.withResolvers()}[cr](n){this[Jn].resolve?.({value:n,done:!1})}[sr](){this[Jn].resolve?.({value:void 0,done:!0})}[lr](n){this[Jn].reject?.(n)}get promise(){return this[Jn].promise}},ReadableStreamDefaultReader=class{[Yn]=`ReadableStreamDefaultReader`;[Jn];constructor(n){if(!hr(n))throw TypeError(`Expected a ReadableStream`);this[Jn]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamDefaultReader(this,n)}read(){if(!_r(this))return Promise.reject(TypeError(`Invalid this`));if(this[Jn].stream===void 0)return Promise.reject(TypeError(`The reader is not attached to a stream`));let n=this[Jn].stream,S=n[Jn].controller;if(n[Jn].state===`readable`&&gr(S)&&S[Jn].queue.length>0){n[Jn].disturbed=!0;let C=dequeueValue(S);return S[Jn].closeRequested&&!S[Jn].queue.length?(readableStreamDefaultControllerClearAlgorithms(S),readableStreamClose(n)):readableStreamDefaultControllerCallPullIfNeeded(S),Promise.resolve({value:C,done:!1})}let C=new DefaultReadRequest;return readableStreamDefaultReaderRead(this,C),C.promise}releaseLock(){if(!_r(this))throw TypeError(`Invalid this`);this[Jn].stream!==void 0&&readableStreamDefaultReaderRelease(this)}get closed(){return _r(this)?this[Jn].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(n=void 0){return _r(this)?this[Jn].stream===void 0?Promise.reject(TypeError(`The reader is not attached to a stream`)):readableStreamReaderGenericCancel(this,n):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamDefaultReader`}},ReadableStreamDefaultController=class{[Yn]=`ReadableStreamDefaultController`;[Jn];constructor(n){if(n!==fr)throw TypeError(`Illegal constructor`)}get desiredSize(){return readableStreamDefaultControllerGetDesiredSize(this)}close(){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerClose(this)}enqueue(n=void 0){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerEnqueue(this,n)}error(n=void 0){readableStreamDefaultControllerError(this,n)}[ar](n){return readableStreamDefaultControllerCancelSteps(this,n)}[ur](n){readableStreamDefaultControllerPullSteps(this,n)}[dr](){}get[Symbol.toStringTag](){return`ReadableStreamDefaultController`}};const hr=isBrandCheck(`ReadableStream`),gr=isBrandCheck(`ReadableStreamDefaultController`),_r=isBrandCheck(`ReadableStreamDefaultReader`);function isReadableStreamLocked(n){return n[Jn].reader!==void 0}function readableStreamCancel(n,S){switch(n[Jn].disturbed=!0,n[Jn].state){case`closed`:return Promise.resolve();case`errored`:return Promise.reject(n[Jn].storedError)}readableStreamClose(n);let C=n[Jn].reader;if(C!==void 0&&readableStreamHasBYOBReader(n)){let n=C[Jn].readIntoRequests;C[Jn].readIntoRequests=[];for(let S=0;S<n.length;S++)n[S][sr](void 0)}return n[Jn].controller[ar](S).then(()=>{})}function readableStreamClose(n){n[Jn].state=`closed`,n[Jn].closedPromise.resolve();let{reader:S}=n[Jn];if(S!==void 0&&(S[Jn].close.resolve?.(),readableStreamHasDefaultReader(n))){for(let n=0;n<S[Jn].readRequests.length;n++)S[Jn].readRequests[n][sr]();S[Jn].readRequests=[]}}function readableStreamError(n,S){n[Jn].state=`errored`,n[Jn].storedError=S,setPromiseHandled(n[Jn].closedPromise.promise),n[Jn].closedPromise.reject(S);let{reader:C}=n[Jn];if(C!==void 0){if(setPromiseHandled(C[Jn].close.promise),C[Jn].close.reject?.(S),readableStreamHasDefaultReader(n)){for(let n=0;n<C[Jn].readRequests.length;n++)C[Jn].readRequests[n][lr](S);C[Jn].readRequests=[]}else if(readableStreamHasBYOBReader(n)){for(let n=0;n<C[Jn].readIntoRequests.length;n++)C[Jn].readIntoRequests[n][lr](S);C[Jn].readIntoRequests=[]}}}function readableStreamHasDefaultReader(n){let{reader:S}=n[Jn];return S===void 0?!1:S[Jn]!==void 0&&S[Yn]===`ReadableStreamDefaultReader`}function readableStreamGetNumReadRequests(n){return n[Jn].reader[Jn].readRequests.length}function readableStreamFulfillReadRequest(n,S,C){let{reader:N}=n[Jn],F=N[Jn].readRequests.shift();C?F[sr]():F[cr](S)}function readableStreamAddReadRequest(n,S){n[Jn].reader[Jn].readRequests.push(S)}function readableStreamReaderGenericCancel(n,S){let{stream:C}=n[Jn];return readableStreamCancel(C,S)}function readableStreamReaderGenericInitialize(n,S){switch(n[Jn].stream=S,S[Jn].reader=n,S[Jn].state){case`readable`:n[Jn].close=Promise.withResolvers();break;case`closed`:n[Jn].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;case`errored`:n[Jn].close={promise:Promise.reject(S[Jn].storedError),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].close.promise);break}}function readableStreamReaderGenericRelease(n){let{stream:S}=n[Jn],C=lazyReadableReleasedError();S[Jn].state===`readable`?n[Jn].close.reject?.(C):n[Jn].close={promise:Promise.reject(C),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].close.promise),S[Jn].controller[dr](),S[Jn].reader=void 0,n[Jn].stream=void 0}function readableStreamDefaultReaderRelease(n){readableStreamReaderGenericRelease(n),readableStreamDefaultReaderErrorReadRequests(n,lazyReadableReleasingError())}function readableStreamDefaultReaderErrorReadRequests(n,S){for(let C=0;C<n[Jn].readRequests.length;++C)n[Jn].readRequests[C][lr](S);n[Jn].readRequests=[]}function readableStreamDefaultReaderRead(n,S){let{stream:C}=n[Jn];switch(C[Jn].disturbed=!0,C[Jn].state){case`closed`:S[sr]();break;case`errored`:S[lr](C[Jn].storedError);break;case`readable`:C[Jn].controller[ur](S);break}}function setupReadableStreamDefaultReader(n,S){if(isReadableStreamLocked(S))throw TypeError(`ReadableStream is locked`);readableStreamReaderGenericInitialize(n,S),n[Jn].readRequests=[]}function readableStreamDefaultControllerClose(n){readableStreamDefaultControllerCanCloseOrEnqueue(n)&&(n[Jn].closeRequested=!0,n[Jn].queue.length||(readableStreamDefaultControllerClearAlgorithms(n),readableStreamClose(n[Jn].stream)))}function readableStreamDefaultControllerEnqueue(n,S){if(!readableStreamDefaultControllerCanCloseOrEnqueue(n))return;let{stream:C}=n[Jn];if(isReadableStreamLocked(C)&&readableStreamGetNumReadRequests(C))readableStreamFulfillReadRequest(C,S,!1);else try{enqueueValueWithSize(n,S,n[Jn].sizeAlgorithm(S))}catch(S){throw readableStreamDefaultControllerError(n,S),S}readableStreamDefaultControllerCallPullIfNeeded(n)}function readableStreamDefaultControllerCanCloseOrEnqueue(n){let{stream:S}=n[Jn];return!n[Jn].closeRequested&&S[Jn].state===`readable`}function readableStreamDefaultControllerGetDesiredSize(n){let{stream:S,highWaterMark:C,queueTotalSize:N}=n[Jn];switch(S[Jn].state){case`errored`:return null;case`closed`:return 0;default:return C-N}}function readableStreamDefaultControllerHasBackpressure(n){return!readableStreamDefaultControllerShouldCallPull(n)}function readableStreamDefaultControllerShouldCallPull(n){let{stream:S}=n[Jn];if(!readableStreamDefaultControllerCanCloseOrEnqueue(n)||!n[Jn].started)return!1;if(isReadableStreamLocked(S)&&readableStreamGetNumReadRequests(S))return!0;let C=readableStreamDefaultControllerGetDesiredSize(n);return C!==null&&C>0}function readableStreamDefaultControllerCallPullIfNeeded(n){if(readableStreamDefaultControllerShouldCallPull(n)){if(n[Jn].pulling){n[Jn].pullAgain=!0;return}n[Jn].pulling=!0,n[Jn].pullAlgorithm(n).then(()=>{n[Jn].pulling=!1,n[Jn].pullAgain&&(n[Jn].pullAgain=!1,readableStreamDefaultControllerCallPullIfNeeded(n))},S=>readableStreamDefaultControllerError(n,S))}}function readableStreamDefaultControllerClearAlgorithms(n){n[Jn].pullAlgorithm=void 0,n[Jn].cancelAlgorithm=void 0,n[Jn].sizeAlgorithm=void 0}function readableStreamDefaultControllerError(n,S){let{stream:C}=n[Jn];C[Jn].state===`readable`&&(resetQueue(n),readableStreamDefaultControllerClearAlgorithms(n),readableStreamError(C,S))}function readableStreamDefaultControllerCancelSteps(n,S){resetQueue(n);let C=n[Jn].cancelAlgorithm?.(S)??Promise.resolve();return readableStreamDefaultControllerClearAlgorithms(n),C}function readableStreamDefaultControllerPullSteps(n,S){let{stream:C,queue:N}=n[Jn];if(N.length){let F=dequeueValue(n);n[Jn].closeRequested&&!N.length?(readableStreamDefaultControllerClearAlgorithms(n),readableStreamClose(C)):readableStreamDefaultControllerCallPullIfNeeded(n),S[cr](F);return}readableStreamAddReadRequest(C,S),readableStreamDefaultControllerCallPullIfNeeded(n)}function setupReadableStreamDefaultController(n,S,C,N,F,I,H){S[Jn]={cancelAlgorithm:F,closeRequested:!1,highWaterMark:I,pullAgain:!1,pullAlgorithm:N,pulling:!1,queue:[],queueTotalSize:0,started:!1,sizeAlgorithm:H,stream:n},n[Jn].controller=S;let W=C();new Promise(n=>n(W)).then(()=>{S[Jn].started=!0,readableStreamDefaultControllerCallPullIfNeeded(S)},n=>readableStreamDefaultControllerError(S,n))}function setupReadableStreamDefaultControllerFromSource(n,S,C,N){let F=new ReadableStreamDefaultController(fr),I=S?.start,H=S?.pull,W=S?.cancel;setupReadableStreamDefaultController(n,F,I?I.bind(S,F):nonOpStart,H?createPromiseCallback(`source.pull`,H,S):nonOpPull,W?createPromiseCallback(`source.cancel`,W,S):nonOpCancel,C,N)}function createReadableStream(n,S,C,N=1,F=()=>1){let I=Object.create(ReadableStream$1.prototype);return I[Yn]=`ReadableStream`,I[Jn]=createReadableStreamState(),setupReadableStreamDefaultController(I,new ReadableStreamDefaultController(fr),n,S,C,N,F),I}function readableStreamFromIterable(n){let S,C=getIterator(n,`async`),N=nonOpStart;async function pullAlgorithm(){let n=iteratorNext(C);return Promise.resolve(n).then(n=>{if(typeof n!=`object`||!n)throw TypeError(`The promise returned by the iterator.next() method must fulfill with an object`);n.done?readableStreamDefaultControllerClose(S[Jn].controller):readableStreamDefaultControllerEnqueue(S[Jn].controller,n.value)})}async function cancelAlgorithm(n){let S=C.iterator,N=S.return;if(N===void 0)return Promise.resolve();let F=N.call(S,n);return Promise.resolve(F).then(n=>{if(typeof n!=`object`||!n)throw TypeError(`The promise returned by the iterator.return() method must fulfill with an object`)})}return S=createReadableStream(N,pullAlgorithm,cancelAlgorithm,0),S}function readableStreamPipeTo(n,S,C,N,F,I){let H,W;try{H=new ReadableStreamDefaultReader(n),W=new WritableStreamDefaultWriter(S)}catch(n){return Promise.reject(n)}n[Jn].disturbed=!0;let q=!1,{promise:Y,resolve:X,reject:Z}=Promise.withResolvers(),te={currentWrite:Promise.resolve()},ne;function finalize(n,S){writableStreamDefaultWriterRelease(W),readableStreamReaderGenericRelease(H),I!==void 0&&ne&&(I.removeEventListener(`abort`,ne),ne=void 0),n?Z(S):X()}async function waitForCurrentWrite(){let n=te.currentWrite;await n,n!==te.currentWrite&&await waitForCurrentWrite()}function shutdownWithAnAction(n,C,N){if(q)return;if(q=!0,S[Jn].state===`writable`&&!writableStreamCloseQueuedOrInFlight(S)){waitForCurrentWrite().then(complete,n=>finalize(!0,n));return}complete();function complete(){n().then(()=>finalize(!!C,N),n=>finalize(!0,n))}}function shutdown(n,C){if(!q){if(q=!0,S[Jn].state===`writable`&&!writableStreamCloseQueuedOrInFlight(S)){waitForCurrentWrite().then(()=>finalize(!!n,C),n=>finalize(!0,n));return}finalize(!!n,C)}}function abortAlgorithm(){let C;C=I.reason&&I.reason.name===`AbortError`?createAbortError$1():I.reason;let H=[];N||H.push(()=>S[Jn].state===`writable`?writableStreamAbort(S,C):Promise.resolve()),F||H.push(()=>n[Jn].state===`readable`?readableStreamCancel(n,C):Promise.resolve()),shutdownWithAnAction(()=>Promise.all(H.map(n=>n())).then(()=>void 0),!0,C)}function watchErrored(n,S,C){n[Jn].state===`errored`?C(n[Jn].storedError):S.then(void 0,C)}function watchClosed(n,S,C){n[Jn].state===`closed`?C():S.then(C,()=>{})}class PipeToReadRequest{[cr](n){be(()=>{te.currentWrite=writableStreamDefaultWriterWrite(W,n),setPromiseHandled(te.currentWrite),re.resolve(!1)})}[sr](){re.resolve(!0)}[lr](n){re.reject(n)}}let re={resolve:null,reject:null};async function step(){if(q||S[Jn].backpressure&&(await W[Jn].ready.promise,q))return!0;let C=n[Jn].controller;if(n[Jn].state===`readable`&&gr(C)&&C[Jn].queue.length>0){for(;C[Jn].queue.length>0;){if(q)return!0;let N=dequeueValue(C);if(C[Jn].closeRequested&&!C[Jn].queue.length&&(readableStreamDefaultControllerClearAlgorithms(C),readableStreamClose(n)),te.currentWrite=writableStreamDefaultWriterWrite(W,N),setPromiseHandled(te.currentWrite),S[Jn].backpressure||S[Jn].state!==`writable`||writableStreamCloseQueuedOrInFlight(S))break}return readableStreamDefaultControllerCallPullIfNeeded(C),n[Jn].state===`closed`}let{promise:N,resolve:F,reject:I}=Promise.withResolvers();return re={resolve:F,reject:I},readableStreamDefaultReaderRead(H,new PipeToReadRequest),N}async function run(){for(;!await step(););}if(I!==void 0){if(I.aborted)return abortAlgorithm(),Y;ne=abortAlgorithm,I.addEventListener(`abort`,ne,{once:!0})}if(setPromiseHandled(run()),watchErrored(n,H[Jn].close.promise,n=>{if(!N)return shutdownWithAnAction(()=>writableStreamAbort(S,n),!0,n);shutdown(!0,n)}),watchErrored(S,W[Jn].close.promise,S=>{if(!F)return shutdownWithAnAction(()=>readableStreamCancel(n,S),!0,S);shutdown(!0,S)}),watchClosed(n,H[Jn].close.promise,()=>{if(!C)return shutdownWithAnAction(()=>writableStreamDefaultWriterCloseWithErrorPropagation(W));shutdown()}),writableStreamCloseQueuedOrInFlight(S)||S[Jn].state===`closed`){let S=TypeError(`Destination WritableStream is closed`);F?shutdown(!0,S):shutdownWithAnAction(()=>readableStreamCancel(n,S),!0,S)}return Y}function readableStreamDefaultTee(n,S){let C=new ReadableStreamDefaultReader(n),N=!1,F=!1,I=!1,H,W,q,Y,X=Promise.withResolvers();async function pullAlgorithm(){N||(N=!0,readableStreamDefaultReaderRead(C,{[cr](n){be(()=>{N=!1;let C=n,H=n;if(!I&&S)try{H=structuredClone(H)}catch{}F||readableStreamDefaultControllerEnqueue(q[Jn].controller,C),I||readableStreamDefaultControllerEnqueue(Y[Jn].controller,H)})},[sr](){be(()=>{N=!1,F||readableStreamDefaultControllerClose(q[Jn].controller),I||readableStreamDefaultControllerClose(Y[Jn].controller),(!F||!I)&&X.resolve(void 0)})},[lr](){N=!1}}))}function cancel1Algorithm(S){if(F=!0,H=S,I){let S=[H,W];X.resolve(readableStreamCancel(n,S))}return X.promise}function cancel2Algorithm(S){if(I=!0,W=S,F){let S=[H,W];X.resolve(readableStreamCancel(n,S))}return X.promise}return q=createReadableStream(nonOpStart,pullAlgorithm,cancel1Algorithm),Y=createReadableStream(nonOpStart,pullAlgorithm,cancel2Algorithm),C[Jn].close.promise.then(void 0,n=>{readableStreamDefaultControllerError(q[Jn].controller,n),readableStreamDefaultControllerError(Y[Jn].controller,n),(!F||!I)&&X.resolve(void 0)}),[q,Y]}var BYOBReadIntoRequest=class{[Jn];constructor(){this[Jn]=Promise.withResolvers()}[cr](n){this[Jn].resolve?.({value:n,done:!1})}[sr](n){this[Jn].resolve?.({value:n,done:!0})}[lr](n){this[Jn].reject?.(n)}get promise(){return this[Jn].promise}},ReadableStreamBYOBReader=class{[Yn]=`ReadableStreamBYOBReader`;[Jn];constructor(n){if(!hr(n))throw TypeError(`Expected a ReadableStream`);this[Jn]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamBYOBReader(this,n)}read(n,S={}){if(!yr(this))return Promise.reject(TypeError(`Invalid this`));if(typeof n!=`object`||!n||!ArrayBuffer.isView(n))return Promise.reject(TypeError(`view must be an ArrayBufferView`));let C=n.buffer,N=n.byteLength;if(N===0)return Promise.reject(TypeError(`view must have non-zero byteLength`));if(C.byteLength===0)return isDetachedBuffer(C)?Promise.reject(TypeError(`view's buffer has been detached`)):Promise.reject(TypeError(`view's buffer must have non-zero byteLength`));let F=S?.min??1;if(typeof F!=`number`||F<1||!Number.isInteger(F)||Number.isNaN(F))return Promise.reject(TypeError(`options.min must be a positive integer`));let I=n[Symbol.toStringTag];if(I!==void 0&&I!==`DataView`){if(F>n.length)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`))}else if(F>N)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`));if(this[Jn].stream===void 0)return Promise.reject(TypeError(`Reader has no associated stream`));let H=new BYOBReadIntoRequest;return readableStreamBYOBReaderRead(this,n,F,H),H.promise}releaseLock(){if(!yr(this))throw TypeError(`Invalid this`);this[Jn].stream!==void 0&&readableStreamBYOBReaderRelease(this)}get closed(){return yr(this)?this[Jn].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(n=void 0){return yr(this)?this[Jn].stream===void 0?Promise.reject(TypeError(`Reader has no associated stream`)):readableStreamReaderGenericCancel(this,n):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamBYOBReader`}},ReadableStreamBYOBRequest=class{[Yn]=`ReadableStreamBYOBRequest`;[Jn];constructor(n){if(n!==fr)throw TypeError(`Illegal constructor`)}get view(){if(!br(this))throw TypeError(`Invalid this`);return this[Jn].view}respond(n){if(!br(this))throw TypeError(`Invalid this`);if(this[Jn].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(n=+n,!Number.isInteger(n)||n<0||!Number.isFinite(n))throw RangeError(`bytesWritten must be a non-negative integer`);let S=this[Jn].view;if(isDetachedBuffer(S.buffer))throw TypeError(`The BYOB request's buffer has been detached`);readableByteStreamControllerRespond(this[Jn].controller,n)}respondWithNewView(n){if(!br(this))throw TypeError(`Invalid this`);if(this[Jn].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(typeof n!=`object`||!n||!ArrayBuffer.isView(n))throw TypeError(`view must be an ArrayBufferView`);if(isDetachedBuffer(n.buffer))throw TypeError(`The given view's buffer has been detached`);readableByteStreamControllerRespondWithNewView(this[Jn].controller,n)}get[Symbol.toStringTag](){return`ReadableStreamBYOBRequest`}},ReadableByteStreamController=class{[Yn]=`ReadableByteStreamController`;[Jn];constructor(n){if(n!==fr)throw TypeError(`Illegal constructor`)}get byobRequest(){if(!vr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetBYOBRequest(this)}get desiredSize(){if(!vr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetDesiredSize(this)}close(){if(!vr(this))throw TypeError(`Invalid this`);if(this[Jn].closeRequested)throw TypeError(`Close already requested`);if(this[Jn].stream[Jn].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerClose(this)}enqueue(n){if(!vr(this))throw TypeError(`Invalid this`);if(typeof n!=`object`||!n||!ArrayBuffer.isView(n))throw TypeError(`chunk must be an ArrayBufferView`);if(n.byteLength===0)throw TypeError(`chunk length must be non-zero`);if(n.buffer.byteLength===0)throw TypeError(`chunk's buffer length must be non-zero`);if(this[Jn].closeRequested)throw TypeError(`Cannot enqueue after close has been requested`);if(this[Jn].stream[Jn].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerEnqueue(this,n)}error(n=void 0){if(!vr(this))throw TypeError(`Invalid this`);readableByteStreamControllerError(this,n)}[ar](n){return readableByteStreamControllerCancelSteps(this,n)}[ur](n){readableByteStreamControllerPullSteps(this,n)}[dr](){if(this[Jn].pendingPullIntos.length>0){let n=this[Jn].pendingPullIntos[0];n.readerType=`none`,this[Jn].pendingPullIntos=[n]}}get[Symbol.toStringTag](){return`ReadableByteStreamController`}};const vr=isBrandCheck(`ReadableByteStreamController`),yr=isBrandCheck(`ReadableStreamBYOBReader`),br=isBrandCheck(`ReadableStreamBYOBRequest`);function readableStreamHasBYOBReader(n){let{reader:S}=n[Jn];return S===void 0?!1:S[Jn]!==void 0&&S[Yn]===`ReadableStreamBYOBReader`}function readableStreamGetNumReadIntoRequests(n){return n[Jn].reader[Jn].readIntoRequests.length}function readableStreamAddReadIntoRequest(n,S){n[Jn].reader[Jn].readIntoRequests.push(S)}function readableStreamFulfillReadIntoRequest(n,S,C){let{reader:N}=n[Jn],F=N[Jn].readIntoRequests.shift();C?F[sr](S):F[cr](S)}function setupReadableStreamBYOBReader(n,S){if(isReadableStreamLocked(S))throw TypeError(`ReadableStream is locked`);if(!vr(S[Jn].controller))throw TypeError(`Cannot use a BYOB reader with a non-byte stream`);readableStreamReaderGenericInitialize(n,S),n[Jn].readIntoRequests=[]}function readableStreamBYOBReaderRead(n,S,C,N){let{stream:F}=n[Jn];F[Jn].disturbed=!0,F[Jn].state===`errored`?N[lr](F[Jn].storedError):readableByteStreamControllerPullInto(F[Jn].controller,S,C,N)}function readableStreamBYOBReaderRelease(n){readableStreamReaderGenericRelease(n);let S=TypeError(`Reader was released`);for(let C=0;C<n[Jn].readIntoRequests.length;C++)n[Jn].readIntoRequests[C][lr](S);n[Jn].readIntoRequests=[]}function readableByteStreamControllerClearAlgorithms(n){n[Jn].pullAlgorithm=void 0,n[Jn].cancelAlgorithm=void 0}function readableByteStreamControllerClearPendingPullIntos(n){readableByteStreamControllerInvalidateBYOBRequest(n),n[Jn].pendingPullIntos=[]}function readableByteStreamControllerInvalidateBYOBRequest(n){let S=n[Jn].byobRequest;S!=null&&(S[Jn].controller=void 0,S[Jn].view=null,n[Jn].byobRequest=null)}function readableByteStreamControllerError(n,S){let{stream:C}=n[Jn];C[Jn].state===`readable`&&(readableByteStreamControllerClearPendingPullIntos(n),resetQueue(n),readableByteStreamControllerClearAlgorithms(n),readableStreamError(C,S))}function readableByteStreamControllerGetDesiredSize(n){let S=n[Jn].stream[Jn].state;return S===`errored`?null:S===`closed`?0:n[Jn].highWaterMark-n[Jn].queueTotalSize}function readableByteStreamControllerShouldCallPull(n){let{stream:S}=n[Jn];if(S[Jn].state!==`readable`||n[Jn].closeRequested||!n[Jn].started)return!1;if(readableStreamHasDefaultReader(S)&&readableStreamGetNumReadRequests(S)>0||readableStreamHasBYOBReader(S)&&readableStreamGetNumReadIntoRequests(S)>0)return!0;let C=readableByteStreamControllerGetDesiredSize(n);return C!==null&&C>0}function readableByteStreamControllerCallPullIfNeeded(n){if(readableByteStreamControllerShouldCallPull(n)){if(n[Jn].pulling){n[Jn].pullAgain=!0;return}n[Jn].pulling=!0,n[Jn].pullAlgorithm(n).then(()=>{n[Jn].pulling=!1,n[Jn].pullAgain&&(n[Jn].pullAgain=!1,readableByteStreamControllerCallPullIfNeeded(n))},S=>readableByteStreamControllerError(n,S))}}function readableByteStreamControllerHandleQueueDrain(n){n[Jn].queueTotalSize===0&&n[Jn].closeRequested?(readableByteStreamControllerClearAlgorithms(n),readableStreamClose(n[Jn].stream)):readableByteStreamControllerCallPullIfNeeded(n)}function readableByteStreamControllerEnqueueChunkToQueue(n,S,C,N){n[Jn].queue.push({buffer:S,byteOffset:C,byteLength:N}),n[Jn].queueTotalSize+=N}function readableByteStreamControllerEnqueueClonedChunkToQueue(n,S,C,N){let F;try{F=S.slice(C,C+N)}catch(S){readableByteStreamControllerError(n,S);return}readableByteStreamControllerEnqueueChunkToQueue(n,F,0,N)}function readableByteStreamControllerEnqueueDetachedPullIntoToQueue(n,S){S.bytesFilled>0&&readableByteStreamControllerEnqueueClonedChunkToQueue(n,S.buffer,S.byteOffset,S.bytesFilled),readableByteStreamControllerShiftPendingPullInto(n)}function readableByteStreamControllerShiftPendingPullInto(n){return n[Jn].pendingPullIntos.shift()}function readableByteStreamControllerFillHeadPullIntoDescriptor(n,S,C){C.bytesFilled+=S}function readableByteStreamControllerConvertPullIntoDescriptor(n){let S=n.bytesFilled,C=n.elementSize,N=transferArrayBuffer(n.buffer);return n.buffer=N,new n.viewConstructor(N,n.byteOffset,S/C)}function readableByteStreamControllerCommitPullIntoDescriptor(n,S){let C=!1;n[Jn].state===`closed`&&(C=!0);let N=readableByteStreamControllerConvertPullIntoDescriptor(S);S.readerType==="default"?readableStreamFulfillReadRequest(n,N,C):readableStreamFulfillReadIntoRequest(n,N,C)}function readableByteStreamControllerFillPullIntoDescriptorFromQueue(n,S){let C=Math.min(n[Jn].queueTotalSize,S.byteLength-S.bytesFilled),N=S.bytesFilled+C,F=C,I=!1,H=N-N%S.elementSize;H>=S.minimumFill&&(F=H-S.bytesFilled,I=!0);let W=n[Jn].queue;for(;F>0;){let C=W[0],N=Math.min(F,C.byteLength),I=S.byteOffset+S.bytesFilled,H=new Uint8Array(S.buffer,I,N),q=new Uint8Array(C.buffer,C.byteOffset,N);H.set(q),C.byteLength===N?W.shift():(C.byteOffset+=N,C.byteLength-=N),n[Jn].queueTotalSize-=N,readableByteStreamControllerFillHeadPullIntoDescriptor(n,N,S),F-=N}return I}function readableByteStreamControllerFillReadRequestFromQueue(n,S){let C=n[Jn].queue.shift();n[Jn].queueTotalSize-=C.byteLength,readableByteStreamControllerHandleQueueDrain(n);let N=new Uint8Array(C.buffer,C.byteOffset,C.byteLength);S[cr](N)}function readableByteStreamControllerProcessReadRequestsUsingQueue(n){let S=n[Jn].stream[Jn].reader;for(;S[Jn].readRequests.length!==0;){if(n[Jn].queueTotalSize===0)return;readableByteStreamControllerFillReadRequestFromQueue(n,S[Jn].readRequests.shift())}}function readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(n){for(;n[Jn].pendingPullIntos.length!==0;){if(n[Jn].queueTotalSize===0)return;let S=n[Jn].pendingPullIntos[0];readableByteStreamControllerFillPullIntoDescriptorFromQueue(n,S)&&(readableByteStreamControllerShiftPendingPullInto(n),readableByteStreamControllerCommitPullIntoDescriptor(n[Jn].stream,S))}}function readableByteStreamControllerGetBYOBRequest(n){if(n[Jn].byobRequest===null&&n[Jn].pendingPullIntos.length!==0){let S=n[Jn].pendingPullIntos[0],C=new Uint8Array(S.buffer,S.byteOffset+S.bytesFilled,S.byteLength-S.bytesFilled),N=new ReadableStreamBYOBRequest(fr);N[Jn]={controller:n,view:C},n[Jn].byobRequest=N}return n[Jn].byobRequest}function readableByteStreamControllerEnqueue(n,S){let{stream:C}=n[Jn];if(n[Jn].closeRequested||C[Jn].state!==`readable`)return;let N=S.buffer,F=S.byteLength,I=S.byteOffset;if(isDetachedBuffer(N))throw TypeError(`chunk's buffer is detached`);let H=transferArrayBuffer(N);if(n[Jn].pendingPullIntos.length!==0){let S=n[Jn].pendingPullIntos[0];if(isDetachedBuffer(S.buffer))throw TypeError(`BYOB request's buffer has been detached`);readableByteStreamControllerInvalidateBYOBRequest(n),S.buffer=transferArrayBuffer(S.buffer),S.readerType===`none`&&readableByteStreamControllerEnqueueDetachedPullIntoToQueue(n,S)}readableStreamHasDefaultReader(C)?(readableByteStreamControllerProcessReadRequestsUsingQueue(n),readableStreamGetNumReadRequests(C)===0?readableByteStreamControllerEnqueueChunkToQueue(n,H,I,F):(n[Jn].pendingPullIntos.length!==0&&readableByteStreamControllerShiftPendingPullInto(n),readableStreamFulfillReadRequest(C,new Uint8Array(H,I,F),!1))):readableStreamHasBYOBReader(C)?(readableByteStreamControllerEnqueueChunkToQueue(n,H,I,F),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(n)):readableByteStreamControllerEnqueueChunkToQueue(n,H,I,F),readableByteStreamControllerCallPullIfNeeded(n)}function readableByteStreamControllerClose(n){let{stream:S}=n[Jn];if(!(n[Jn].closeRequested||S[Jn].state!==`readable`)){if(n[Jn].queueTotalSize>0){n[Jn].closeRequested=!0;return}if(n[Jn].pendingPullIntos.length!==0){let S=n[Jn].pendingPullIntos[0];if(S.bytesFilled%S.elementSize!==0){let S=TypeError(`Insufficient bytes to fill elements in the given buffer`);throw readableByteStreamControllerError(n,S),S}}readableByteStreamControllerClearAlgorithms(n),readableStreamClose(S)}}function readableByteStreamControllerPullInto(n,S,C,N){let F=n[Jn].stream,I=S[Symbol.toStringTag],H,W;if(I===void 0||I===`DataView`)H=DataView,W=1;else{let n=typedArrayConstructorByTag(I);if(!n){N[lr](TypeError(`Unsupported typed array: ${I}`));return}H=n,W=elementSizeByTag(I)}let q=S.buffer,Y=S.byteLength,X=S.byteOffset,Z=C*W,te;try{te=transferArrayBuffer(q)}catch(n){N[lr](n);return}let ne={buffer:te,bufferByteLength:te.byteLength,byteOffset:X,byteLength:Y,bytesFilled:0,minimumFill:Z,elementSize:W,viewConstructor:H,readerType:`byob`};if(n[Jn].pendingPullIntos.length!==0){n[Jn].pendingPullIntos.push(ne),readableStreamAddReadIntoRequest(F,N);return}if(F[Jn].state===`closed`){let n=new H(ne.buffer,ne.byteOffset,0);N[sr](n);return}if(n[Jn].queueTotalSize>0){if(readableByteStreamControllerFillPullIntoDescriptorFromQueue(n,ne)){let S=readableByteStreamControllerConvertPullIntoDescriptor(ne);readableByteStreamControllerHandleQueueDrain(n),N[cr](S);return}if(n[Jn].closeRequested){let S=TypeError(`Insufficient bytes to fill elements in the given buffer`);readableByteStreamControllerError(n,S),N[lr](S);return}}n[Jn].pendingPullIntos.push(ne),readableStreamAddReadIntoRequest(F,N),readableByteStreamControllerCallPullIfNeeded(n)}function readableByteStreamControllerRespond(n,S){let C=n[Jn].pendingPullIntos[0];if(n[Jn].stream[Jn].state===`closed`){if(S!==0)throw TypeError(`bytesWritten must be 0 when calling respond() on a closed stream`)}else{if(S===0)throw TypeError(`bytesWritten must be greater than 0 when calling respond() on a readable stream`);if(C.bytesFilled+S>C.byteLength)throw RangeError(`bytesWritten out of range`)}C.buffer=transferArrayBuffer(C.buffer),readableByteStreamControllerRespondInternal(n,S)}function readableByteStreamControllerRespondWithNewView(n,S){let C=n[Jn].pendingPullIntos[0],N=n[Jn].stream[Jn].state,F=S.byteLength,I=S.byteOffset,H=S.buffer;if(N===`closed`){if(F!==0)throw TypeError(`view's length must be 0 when calling respondWithNewView() on a closed stream`)}else if(F===0)throw TypeError(`view's length must be greater than 0 when calling respondWithNewView() on a readable stream`);if(C.byteOffset+C.bytesFilled!==I)throw RangeError(`The region specified by view does not match byobRequest`);if(C.bufferByteLength!==H.byteLength)throw RangeError(`The buffer of view has different capacity than byobRequest`);if(C.bytesFilled+F>C.byteLength)throw RangeError(`The region specified by view is larger than byobRequest`);C.buffer=transferArrayBuffer(H),readableByteStreamControllerRespondInternal(n,F)}function readableByteStreamControllerRespondInternal(n,S){let C=n[Jn].pendingPullIntos[0];readableByteStreamControllerInvalidateBYOBRequest(n),n[Jn].stream[Jn].state===`closed`?readableByteStreamControllerRespondInClosedState(n,C):readableByteStreamControllerRespondInReadableState(n,S,C),readableByteStreamControllerCallPullIfNeeded(n)}function readableByteStreamControllerRespondInClosedState(n,S){S.readerType===`none`&&readableByteStreamControllerShiftPendingPullInto(n);let C=n[Jn].stream;if(readableStreamHasBYOBReader(C))for(;readableStreamGetNumReadIntoRequests(C)>0;)readableByteStreamControllerCommitPullIntoDescriptor(C,readableByteStreamControllerShiftPendingPullInto(n))}function readableByteStreamControllerRespondInReadableState(n,S,C){if(readableByteStreamControllerFillHeadPullIntoDescriptor(n,S,C),C.readerType===`none`){readableByteStreamControllerEnqueueDetachedPullIntoToQueue(n,C),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(n);return}if(C.bytesFilled<C.minimumFill)return;readableByteStreamControllerShiftPendingPullInto(n);let N=C.bytesFilled%C.elementSize;if(N>0){let S=C.byteOffset+C.bytesFilled;readableByteStreamControllerEnqueueClonedChunkToQueue(n,C.buffer,S-N,N)}C.bytesFilled-=N,readableByteStreamControllerCommitPullIntoDescriptor(n[Jn].stream,C),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(n)}function readableByteStreamControllerCancelSteps(n,S){readableByteStreamControllerClearPendingPullIntos(n),resetQueue(n);let C=n[Jn].cancelAlgorithm?.(S)??Promise.resolve();return readableByteStreamControllerClearAlgorithms(n),C}function readableByteStreamControllerPullSteps(n,S){let C=n[Jn].stream;if(n[Jn].queueTotalSize>0){readableByteStreamControllerFillReadRequestFromQueue(n,S);return}let N=n[Jn].autoAllocateChunkSize;if(N!==void 0){let C;try{C=new ArrayBuffer(N)}catch(n){S[lr](n);return}let F={buffer:C,bufferByteLength:N,byteOffset:0,byteLength:N,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:`default`};n[Jn].pendingPullIntos.push(F)}readableStreamAddReadRequest(C,S),readableByteStreamControllerCallPullIfNeeded(n)}function setupReadableByteStreamController(n,S,C,N,F,I,H){S[Jn]={cancelAlgorithm:F,closeRequested:!1,highWaterMark:I,pullAgain:!1,pullAlgorithm:N,pulling:!1,queue:[],queueTotalSize:0,started:!1,stream:n,byobRequest:null,pendingPullIntos:[],autoAllocateChunkSize:H},n[Jn].controller=S;let W=C();new Promise(n=>n(W)).then(()=>{S[Jn].started=!0,readableByteStreamControllerCallPullIfNeeded(S)},n=>readableByteStreamControllerError(S,n))}function setupReadableByteStreamControllerFromSource(n,S,C){let N=new ReadableByteStreamController(fr),F=S?.start,I=S?.pull,H=S?.cancel,W=S?.autoAllocateChunkSize;if(W!==void 0&&(W===0||!Number.isInteger(W)||W<0))throw TypeError(`autoAllocateChunkSize must be a positive integer`);setupReadableByteStreamController(n,N,F?F.bind(S,N):nonOpStart,I?createPromiseCallback(`source.pull`,I,S):nonOpPull,H?createPromiseCallback(`source.cancel`,H,S):nonOpCancel,C,W)}function readableByteStreamTee(n){let S=new ReadableStreamDefaultReader(n),C=!1,N=!1,F=!1,I,H,W=Promise.withResolvers(),q,Y,X,Z;function pullAlgorithm(){return C?Promise.resolve():(C=!0,S.read().then(n=>{if(C=!1,n.done){N||X.close(),F||Z.close();return}let S=n.value,I=new Uint8Array(S.buffer.slice(S.byteOffset,S.byteOffset+S.byteLength));N||X.enqueue(I),F||Z.enqueue(new Uint8Array(I))},()=>{}),Promise.resolve())}return q=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(S){if(N=!0,I=S,F){let S=readableStreamCancel(n,[I,H]);return W.resolve(),S}return W.promise}}),Y=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(S){if(F=!0,H=S,N){let S=readableStreamCancel(n,[I,H]);return W.resolve(),S}return W.promise}}),X=q[Jn].controller,Z=Y[Jn].controller,S.closed.catch(n=>{X.error(n),Z.error(n),(!N||!F)&&W.resolve()}),[q,Y]}const Sr=Symbol(`kSkipThrow`);var TransformStream=class{[Yn]=`TransformStream`;[Jn];constructor(n={},S={},C={}){if(n!=null&&typeof n!=`object`)throw TypeError(`transformer must be an object`);if(S!=null&&typeof S!=`object`)throw TypeError(`writableStrategy must be an object`);if(C!=null&&typeof C!=`object`)throw TypeError(`readableStrategy must be an object`);let N=n?.readableType,F=n?.writableType,I=n?.start;if(N!==void 0)throw RangeError(`Invalid readableType: ${N}`);if(F!==void 0)throw RangeError(`Invalid writableType: ${F}`);let H=extractHighWaterMark(C?.highWaterMark,0),W=extractSizeAlgorithm(C?.size),q=extractHighWaterMark(S?.highWaterMark,1),Y=extractSizeAlgorithm(S?.size),X=Promise.withResolvers();initializeTransformStream(this,X,q,Y,H,W),setupTransformStreamDefaultControllerFromTransformer(this,n),I===void 0?X.resolve():X.resolve(I.call(n,this[Jn].controller))}get readable(){if(!Cr(this))throw TypeError(`Invalid this`);return this[Jn].readable}get writable(){if(!Cr(this))throw TypeError(`Invalid this`);return this[Jn].writable}get[Symbol.toStringTag](){return`TransformStream`}},TransformStreamDefaultController=class{[Yn]=`TransformStreamDefaultController`;[Jn];constructor(n){if(n!==Sr)throw TypeError(`Illegal constructor`)}get desiredSize(){if(!wr(this))throw TypeError(`Invalid this`);let{stream:n}=this[Jn],{readable:S}=n[Jn],C=S[Jn].controller;return readableStreamDefaultControllerGetDesiredSize(C)}enqueue(n){if(!wr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerEnqueue(this,n)}error(n){if(!wr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerError(this,n)}terminate(){if(!wr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerTerminate(this)}get[Symbol.toStringTag](){return`TransformStreamDefaultController`}};const Cr=isBrandCheck(`TransformStream`),wr=isBrandCheck(`TransformStreamDefaultController`);async function defaultTransformAlgorithm(n,S){transformStreamDefaultControllerEnqueue(S,n)}function initializeTransformStream(n,S,C,N,F,I){let startAlgorithm=()=>S.promise,H=createWritableStream(startAlgorithm,S=>transformStreamDefaultSinkWriteAlgorithm(n,S),()=>transformStreamDefaultSinkCloseAlgorithm(n),S=>transformStreamDefaultSinkAbortAlgorithm(n,S),C,N);n[Jn]={readable:createReadableStream(startAlgorithm,()=>transformStreamDefaultSourcePullAlgorithm(n),S=>transformStreamDefaultSourceCancelAlgorithm(n,S),F,I),writable:H,controller:void 0,backpressure:void 0,backpressureChange:{promise:void 0,resolve:void 0,reject:void 0}},transformStreamSetBackpressure(n,!0)}function transformStreamError(n,S){let{readable:C}=n[Jn];readableStreamDefaultControllerError(C[Jn].controller,S),transformStreamErrorWritableAndUnblockWrite(n,S)}function transformStreamErrorWritableAndUnblockWrite(n,S){let{controller:C,writable:N}=n[Jn];transformStreamDefaultControllerClearAlgorithms(C),writableStreamDefaultControllerErrorIfNeeded(N[Jn].controller,S),transformStreamUnblockWrite(n)}function transformStreamUnblockWrite(n){n[Jn].backpressure&&transformStreamSetBackpressure(n,!1)}function transformStreamSetBackpressure(n,S){n[Jn].backpressureChange.promise!==void 0&&n[Jn].backpressureChange.resolve?.(),n[Jn].backpressureChange=Promise.withResolvers(),n[Jn].backpressure=S}function setupTransformStreamDefaultController(n,S,C,N,F){S[Jn]={stream:n,transformAlgorithm:C,flushAlgorithm:N,cancelAlgorithm:F,finishPromise:void 0},n[Jn].controller=S}function setupTransformStreamDefaultControllerFromTransformer(n,S){let C=new TransformStreamDefaultController(Sr),N=S?.transform,F=S?.flush,I=S?.cancel;setupTransformStreamDefaultController(n,C,N?createPromiseCallback(`transformer.transform`,N,S):defaultTransformAlgorithm,F?createPromiseCallback(`transformer.flush`,F,S):nonOpFlush,I?createPromiseCallback(`transformer.cancel`,I,S):nonOpCancel)}function transformStreamDefaultControllerClearAlgorithms(n){n[Jn].transformAlgorithm=void 0,n[Jn].flushAlgorithm=void 0,n[Jn].cancelAlgorithm=void 0}function transformStreamDefaultControllerEnqueue(n,S){let{stream:C}=n[Jn],{readable:N}=C[Jn],F=N[Jn].controller;if(!readableStreamDefaultControllerCanCloseOrEnqueue(F))throw TypeError(`Unable to enqueue`);try{readableStreamDefaultControllerEnqueue(F,S)}catch(n){throw transformStreamErrorWritableAndUnblockWrite(C,n),N[Jn].storedError}readableStreamDefaultControllerHasBackpressure(F)!==C[Jn].backpressure&&transformStreamSetBackpressure(C,!0)}function transformStreamDefaultControllerError(n,S){transformStreamError(n[Jn].stream,S)}async function transformStreamDefaultControllerPerformTransform(n,S){try{let C=n[Jn].transformAlgorithm;if(C===void 0)return;await C(S,n)}catch(S){throw transformStreamError(n[Jn].stream,S),S}}function transformStreamDefaultControllerTerminate(n){let{stream:S}=n[Jn],{readable:C}=S[Jn];readableStreamDefaultControllerClose(C[Jn].controller),transformStreamErrorWritableAndUnblockWrite(S,TypeError(`TransformStream has been terminated`))}function transformStreamDefaultSinkWriteAlgorithm(n,S){let{controller:C}=n[Jn];return n[Jn].backpressure?n[Jn].backpressureChange.promise.then(()=>{let{writable:N}=n[Jn];if(N[Jn].state===`erroring`)throw N[Jn].storedError;return transformStreamDefaultControllerPerformTransform(C,S)}):transformStreamDefaultControllerPerformTransform(C,S)}async function transformStreamDefaultSinkAbortAlgorithm(n,S){let{controller:C,readable:N}=n[Jn];if(C[Jn].finishPromise!==void 0)return C[Jn].finishPromise;let{promise:F,resolve:I,reject:H}=Promise.withResolvers();C[Jn].finishPromise=F;let W=C[Jn].cancelAlgorithm(S);return transformStreamDefaultControllerClearAlgorithms(C),W.then(()=>{N[Jn].state===`errored`?H(N[Jn].storedError):(readableStreamDefaultControllerError(N[Jn].controller,S),I())},n=>{readableStreamDefaultControllerError(N[Jn].controller,n),H(n)}),C[Jn].finishPromise}function transformStreamDefaultSinkCloseAlgorithm(n){let{readable:S,controller:C}=n[Jn];if(C[Jn].finishPromise!==void 0)return C[Jn].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();C[Jn].finishPromise=N;let H=C[Jn].flushAlgorithm(C);return transformStreamDefaultControllerClearAlgorithms(C),H.then(()=>{S[Jn].state===`errored`?I(S[Jn].storedError):(readableStreamDefaultControllerClose(S[Jn].controller),F())},n=>{readableStreamDefaultControllerError(S[Jn].controller,n),I(n)}),C[Jn].finishPromise}function transformStreamDefaultSourcePullAlgorithm(n){return transformStreamSetBackpressure(n,!1),n[Jn].backpressureChange.promise}function transformStreamDefaultSourceCancelAlgorithm(n,S){let{controller:C,writable:N}=n[Jn];if(C[Jn].finishPromise!==void 0)return C[Jn].finishPromise;let{promise:F,resolve:I,reject:H}=Promise.withResolvers();C[Jn].finishPromise=F;let W=C[Jn].cancelAlgorithm(S);return transformStreamDefaultControllerClearAlgorithms(C),W.then(()=>{N[Jn].state===`errored`?H(N[Jn].storedError):(writableStreamDefaultControllerErrorIfNeeded(N[Jn].controller,S),transformStreamUnblockWrite(n),I())},S=>{writableStreamDefaultControllerErrorIfNeeded(N[Jn].controller,S),transformStreamUnblockWrite(n),H(S)}),C[Jn].finishPromise}const Tr=Object.defineProperty(n=>n.byteLength,"name",{value:`size`}),Er=Object.defineProperty(()=>1,"name",{value:`size`});var ByteLengthQueuingStrategy=class{#e;constructor(n){if(typeof n!=`object`||!n)throw TypeError(`init must be an object`);if(n.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+n.highWaterMark}get highWaterMark(){return this.#e}get size(){return Tr}get[Symbol.toStringTag](){return`ByteLengthQueuingStrategy`}},CountQueuingStrategy=class{#e;constructor(n){if(typeof n!=`object`||!n)throw TypeError(`init must be an object`);if(n.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+n.highWaterMark}get highWaterMark(){return this.#e}get size(){return Er}get[Symbol.toStringTag](){return`CountQueuingStrategy`}},TextEncoderStream=class{#e=null;#t=new TextEncoder;#n;constructor(){this.#n=new TransformStream({transform:(n,S)=>{if(n=String(n),n===``)return;this.#e!==null&&(n=this.#e+n);let C=n.charCodeAt(n.length-1);55296<=C&&C<=56319?(this.#e=n.slice(-1),n=n.slice(0,-1)):this.#e=null,n&&S.enqueue(this.#t.encode(n))},flush:n=>{this.#e!==null&&n.enqueue(new Uint8Array([239,191,189]))}})}get encoding(){return`utf-8`}get readable(){return this.#n.readable}get writable(){return this.#n.writable}};function hasStreamingSupport(){try{return new TextDecoder().decode(new Uint8Array([195]),{stream:!0}),!0}catch{return!1}}const Dr=hasStreamingSupport();function incompleteUtf8Tail$1(n){let S=n.length;if(S===0)return 0;for(let C=1;C<=Math.min(3,S);C++){let N=n[S-C];if(!(N&128))return 0;if((N&192)!=128){let n;if((N&224)==192)n=2;else if((N&240)==224)n=3;else if((N&248)==240)n=4;else return 0;return C<n?C:0}}return 0}__name$1(incompleteUtf8Tail$1,`incompleteUtf8Tail`);var TextDecoderStream=class{#e;#t;constructor(n,S){if(this.#e=new TextDecoder(n,S),Dr)this.#t=new TransformStream({transform:(n,S)=>{let C=toUint8Array$3(n),N=this.#e.decode(C,{stream:!0});N&&S.enqueue(N)},flush:n=>{let S=this.#e.decode();S&&n.enqueue(S)},cancel:()=>{this.#e.decode()}});else{let n=new Uint8Array;this.#t=new TransformStream({transform:(S,C)=>{let N=toUint8Array$3(S),F;n.length>0?(F=new Uint8Array(n.length+N.length),F.set(n,0),F.set(N,n.length)):F=N;let I=incompleteUtf8Tail$1(F),H;if(I>0?(H=F.slice(0,F.length-I),n=F.slice(F.length-I)):(H=F,n=new Uint8Array),H.length>0){let n=this.#e.decode(H);n&&C.enqueue(n)}},flush:S=>{if(n.length>0){let C=this.#e.decode(n);C&&S.enqueue(C),n=new Uint8Array}},cancel:()=>{n=new Uint8Array}})}}get encoding(){return this.#e.encoding}get fatal(){return this.#e.fatal}get ignoreBOM(){return this.#e.ignoreBOM}get readable(){return this.#t.readable}get writable(){return this.#t.writable}};function toUint8Array$3(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);throw TypeError(`chunk must be a BufferSource`)}__name$1(toUint8Array$3,`toUint8Array`);function isNativeStreamUsable$3(n,S){try{return typeof n==`function`?typeof n.prototype?.[S]==`function`:!1}catch{return!1}}__name$1(isNativeStreamUsable$3,`isNativeStreamUsable`);const Or=isNativeStreamUsable$3(globalThis.ReadableStream,`getReader`)?globalThis.ReadableStream:ReadableStream$1,kr=isNativeStreamUsable$3(globalThis.WritableStream,`getWriter`)?globalThis.WritableStream:WritableStream,Ar=isNativeStreamUsable$3(globalThis.TransformStream,`readable`)?globalThis.TransformStream:TransformStream,jr=typeof globalThis.ByteLengthQueuingStrategy==`function`?globalThis.ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,Mr=typeof globalThis.CountQueuingStrategy==`function`?globalThis.CountQueuingStrategy:CountQueuingStrategy,Nr=typeof globalThis.TextEncoderStream==`function`?globalThis.TextEncoderStream:TextEncoderStream,Pr=typeof globalThis.TextDecoderStream==`function`?globalThis.TextDecoderStream:TextDecoderStream;var Fr,Ir=__esmMin(()=>{Fr=S}),Lr,Rr=__esmMin(()=>{Ir(),Lr=Fr});function getGioFormat(n){switch(n){case`gzip`:return Lr.ZlibCompressorFormat.GZIP;case`deflate`:return Lr.ZlibCompressorFormat.ZLIB;case`deflate-raw`:return Lr.ZlibCompressorFormat.RAW}}function concat$2(n){let S=n.reduce((n,S)=>n+S.length,0),C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}function compressWithGio(n,S){let C=new Lr.ZlibCompressor({format:getGioFormat(S)}),N=new Lr.ConverterOutputStream({base_stream:Lr.MemoryOutputStream.new_resizable(),converter:C});N.write_bytes(new ft.Bytes(n),null),N.close(null);let F=N.get_base_stream().steal_as_bytes();return new Uint8Array(F.get_data()??[])}function decompressStreamWithGio(n,S){let C=new Lr.ZlibDecompressor({format:getGioFormat(S)}),N=Lr.MemoryInputStream.new_from_bytes(new ft.Bytes(n)),F=new Lr.ConverterInputStream({base_stream:N,converter:C}),I=[];for(;;){let n=F.read_bytes(Br,null);if(n.get_size()===0)break;I.push(new Uint8Array(n.get_data()))}return F.close(null),concat$2(I)}function findGzipMemberEnd(n){let S=new Lr.ZlibDecompressor({format:Lr.ZlibCompressorFormat.GZIP}),C=new Uint8Array(262144),N=0;for(;;){let F=n.subarray(N,N+zr);try{let[n,I,H]=S.convert(F,C,Lr.ConverterFlags.NONE);if(N+=I,n===Lr.ConverterResult.FINISHED||I===0&&H===0)return N}catch{return N}}}function gunzipWithGio(n){let S=[],C=0;for(;C<n.length&&!(n.length-C<2||n[C]!==31||n[C+1]!==139);){let N=n.subarray(C),F=findGzipMemberEnd(N);if(F<=0)break;S.push(decompressStreamWithGio(N.subarray(0,F),`gzip`)),C+=F}return S.length===0?decompressStreamWithGio(n,`gzip`):concat$2(S)}var zr,Br,Vr=__esmMin(()=>{Rr(),pt(),zr=256*1024,Br=1024*1024,__name$1(concat$2,`concat`)}),Hr=__esmMin(()=>{Be()});function _setPipeImpl(n){Ur=n}var Ur,Stream_,Wr=__esmMin(()=>{Kt(),Stream_=class extends Ft{constructor(n){super(n)}pipe(n,S){return Ur(this,n,S)}}});function finished$1(n,S,C){let N;N=typeof S==`function`?S:C;let F=!1;function done(n){F||(F=!0,N(n))}let onFinish=()=>done(),onEnd=()=>done(),onError=n=>done(n),onClose=()=>{let S=n,C=n;!S.writableFinished&&!C.readableEnded&&done(Error(`premature close`))};n.on(`finish`,onFinish),n.on(`end`,onEnd),n.on(`error`,onError),n.on(`close`,onClose);let I=n,H=typeof n.write==`function`,W=typeof n.read==`function`,q=I.writableFinished===!0,Y=I.readableEnded===!0;if(I.destroyed===!0){let n=I._err;be(n?()=>done(n):H&&q||W&&Y?()=>done():()=>done(Error(`premature close`)))}else(H&&!W&&q||!H&&W&&Y||H&&W&&q&&Y)&&be(()=>done());return function cleanup(){n.removeListener(`finish`,onFinish),n.removeListener(`end`,onEnd),n.removeListener(`error`,onError),n.removeListener(`close`,onClose)}}function addAbortSignal(n,S){if(!(n instanceof AbortSignal))throw TypeError(`The first argument must be an AbortSignal`);if(!(S instanceof Stream_))throw TypeError(`The second argument must be a Stream`);let C=S;if(n.aborted)C.destroy(Error(`The operation was aborted`));else{let onAbort=()=>{C.destroy(Error(`The operation was aborted`))};n.addEventListener(`abort`,onAbort,{once:!0}),S.once(`close`,()=>{n.removeEventListener(`abort`,onAbort)})}return S}function isReadable(n){if(n==null)return!1;let S=n;return typeof S.readable!=`boolean`||typeof S.read!=`function`||S.destroyed===!0||S.readableEnded===!0?!1:S.readable===!0}function isWritable(n){if(n==null)return!1;let S=n;return typeof S.writable!=`boolean`||typeof S.write!=`function`||S.destroyed===!0||S.writableEnded===!0?!1:S.writable===!0}function isDestroyed(n){return n==null?!1:n.destroyed===!0}function isDisturbed(n){if(n==null)return!1;let S=n;return S.readableDidRead===!0||S.readableFlowing!==null&&S.readableFlowing!==void 0}function isErrored(n){if(n==null)return!1;let S=n;return S.destroyed===!0&&typeof S.readable==`boolean`&&S.readable===!1||S.destroyed===!0&&typeof S.writable==`boolean`&&S.writable===!1}var Gr=__esmMin(()=>{Wr(),Be(),__name$1(finished$1,`finished`)});function getDefaultHighWaterMark(n){return n?qr:Kr}function setDefaultHighWaterMark(n,S){if(typeof S!=`number`||S<0||Number.isNaN(S))throw TypeError(`Invalid highWaterMark: ${S}`);n?qr=S:Kr=S}function validateHighWaterMark(n,S){if(S!==void 0&&(typeof S!=`number`||Number.isNaN(S))){let C=TypeError(`The value of "${n}" is invalid. Received ${S}`);throw C.code=`ERR_INVALID_ARG_VALUE`,C}}var Kr,qr,Jr=__esmMin(()=>{Kr=16384,qr=16});function createAbortError(){let n=Error(`The operation was aborted`);return n.name=`AbortError`,n.code=`ABORT_ERR`,n}async function streamAsyncDispose(n,S){let C;n.destroyed||(C=S?void 0:createAbortError(),n.destroy(C)),await new Promise((S,N)=>{finished$1(n,n=>{n&&n!==C?N(n):S()})})}var Yr,Xr=__esmMin(()=>{Gr(),Yr=Symbol.asyncDispose??Symbol.for(`Symbol.asyncDispose`)});function chunkLength(n){if(n==null)return 1;let S=n.length;return typeof S==`number`?S:1}function sliceChunk(n,S,C){if(typeof n==`string`)return C===void 0?n.slice(S):n.slice(S,C);let N=n.slice;return typeof N==`function`?N.call(n,S,C):n}var Zr,Qr=__esmMin(()=>{Wr(),Xr(),Jr(),Be(),Zr=class Readable_ extends Stream_{readable=!0;readableFlowing=null;readableLength=0;readableHighWaterMark;readableEncoding;readableObjectMode;readableEnded=!1;readableAborted=!1;destroyed=!1;_pipeDests=[];_buffer=[];_readableState={ended:!1,endEmitted:!1,reading:!1,constructed:!0,highWaterMark:0,objectMode:!1,pipes:[]};_err;_readablePending=!1;_readImpl;_destroyImpl;_constructImpl;constructor(n){super(n),this.readableHighWaterMark=n?.highWaterMark??getDefaultHighWaterMark(n?.objectMode??!1),this.readableEncoding=n?.encoding??null,this.readableObjectMode=n?.objectMode??!1,this._readableState.highWaterMark=this.readableHighWaterMark,this._readableState.objectMode=this.readableObjectMode,n?.read&&(this._readImpl=n.read),n?.destroy&&(this._destroyImpl=n.destroy),n?.construct&&(this._constructImpl=n.construct),(this._constructImpl||this._construct!==Readable_.prototype._construct)&&(this._readableState.constructed=!1,nextTick(()=>{this._construct(n=>{this._readableState.constructed=!0,n?this.destroy(n):this.readableFlowing===!0&&this._flow()})}))}_construct(n){this._constructImpl?this._constructImpl.call(this,n):n()}_read(n){this._readImpl&&this._readImpl.call(this,n)}read(n){if(!this._readableState.constructed)return null;if(this._buffer.length===0){if(this._readableState.ended)return null;this._readableState.reading=!0,this._read(n??this.readableHighWaterMark),this._readableState.reading=!1}if(this._buffer.length===0||n===0)return null;if(this.readableObjectMode){if(n===void 0){let n=this._buffer.shift();return--this.readableLength,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),n}if(n>this.readableLength)return null;let S=this._buffer.shift();return--this.readableLength,S}if(n!=null)return n>this.readableLength?null:this._readBytes(n);let S=this._buffer.splice(0);if(this.readableLength=0,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),S.length===1)return S[0];if(S.length===0)return null;if(typeof S[0]==`string`)return S.join(``);let C=globalThis.Buffer;return C?.concat?C.concat(S):S}_readBytes(n){let S=0,C=[];for(;S<n&&this._buffer.length>0;){let N=this._buffer[0],F=chunkLength(N);if(S+F<=n)C.push(this._buffer.shift()),S+=F,this.readableLength-=F;else{let F=n-S;C.push(sliceChunk(N,0,F)),this._buffer[0]=sliceChunk(N,F),this.readableLength-=F,S+=F}}if(C.length===1)return C[0];let N=globalThis.Buffer;return N?.concat?N.concat(C):C}push(n,S){if(n===null)return this._readableState.ended=!0,this.readableEnded=!0,this._buffer.length===0&&!this._readableState.endEmitted&&nextTick(()=>this._emitEnd()),this._scheduleReadable(),!1;if(!this.readableObjectMode&&!(typeof n==`string`||ArrayBuffer.isView(n))){let S=Object.assign(TypeError(`Invalid non-string/buffer chunk type: ${typeof n}`),{code:`ERR_INVALID_ARG_TYPE`});return nextTick(()=>this.emit(`error`,S)),!1}return this._buffer.push(n),this.readableLength+=this.readableObjectMode?1:chunkLength(n),this.readableFlowing&&!this._flowing&&nextTick(()=>this._flow()),this.readableFlowing!==!0&&this._scheduleReadable(),this.readableLength<this.readableHighWaterMark}_emitEnd(){this._readableState.endEmitted||(this._readableState.endEmitted=!0,this.emit(`end`),nextTick(()=>this._autoClose()))}_autoClose(){this.emit(`close`)}_scheduleReadable(){this._readablePending||this.listenerCount(`readable`)===0||(this._readablePending=!0,nextTick(()=>{this._readablePending=!1,this.destroyed||this.emit(`readable`)}))}on(n,S){return super.on(n,S),n===`data`&&this.readableFlowing!==!1&&this.resume(),n===`readable`&&(this._buffer.length>0||this._readableState.ended)&&this._scheduleReadable(),this}unshift(n){this._buffer.unshift(n),this.readableLength+=this.readableObjectMode?1:chunkLength(n)}setEncoding(n){return this.readableEncoding=n,this}pause(){return this.readableFlowing=!1,this.emit(`pause`),this}resume(){return this.readableFlowing!==!0&&(this.readableFlowing=!0,this.emit(`resume`),this._readableState.constructed&&this._flow()),this}_flowing=!1;_flow(){if(!(this.readableFlowing!==!0||this._flowing||this.destroyed)&&this._readableState.constructed){this._flowing=!0;try{for(;this._buffer.length>0&&this.readableFlowing&&!this.destroyed;){let n=this._buffer.shift();if(this.readableLength-=this.readableObjectMode?1:chunkLength(n),this.readableEncoding&&typeof n!=`string`){let S=globalThis.Buffer;S?.isBuffer&&S.isBuffer(n)?n=n.toString(this.readableEncoding):n instanceof Uint8Array&&(n=new TextDecoder(this.readableEncoding).decode(n))}this.emit(`data`,n)}if(this.destroyed)return;if(this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted){nextTick(()=>this._emitEnd());return}!this._readableState.ended&&!this._readableState.reading&&!this.destroyed&&(this._readableState.reading=!0,this._read(this.readableHighWaterMark),this._readableState.reading=!1)}finally{this._flowing=!1}this._buffer.length>0&&this.readableFlowing&&!this.destroyed&&nextTick(()=>this._flow())}}isPaused(){return this.readableFlowing===!1}unpipe(n){if(n){let S=this._pipeDests.findIndex(S=>S.dest===n);if(S!==-1){this._pipeDests[S].cleanup(),this._pipeDests.splice(S,1);let C=this._readableState.pipes.indexOf(n);C!==-1&&this._readableState.pipes.splice(C,1),n.emit(`unpipe`,this),this._pipeDests.length===0&&(this.readableFlowing=!1)}}else{for(let n of this._pipeDests)n.cleanup(),n.dest.emit(`unpipe`,this);this._pipeDests=[],this._readableState.pipes=[],this.readableFlowing=!1}return this}_destroy(n,S){this._destroyImpl?this._destroyImpl.call(this,n,S):S(n??void 0)}destroy(n){if(this.destroyed)return this;this.destroyed=!0,this.readable=!1,this.readableAborted=!this.readableEnded,n&&(this._err=n);let cb=n=>{n&&nextTick(()=>this.emit(`error`,n)),nextTick(()=>this.emit(`close`))};return Object.prototype.hasOwnProperty.call(this,`_destroy`)?this._destroy(n??null,cb):this._destroyImpl?this._destroyImpl.call(this,n??null,cb):cb(n),this}static toWeb(n){return new ReadableStream({start(S){n.on(`data`,n=>{typeof n==`string`?S.enqueue(new TextEncoder().encode(n)):n instanceof Uint8Array?S.enqueue(n):n&&typeof n.length==`number`&&S.enqueue(new Uint8Array(n))}),n.on(`end`,()=>{S.close()}),n.on(`error`,n=>{S.error(n)})},cancel(){n.destroy()}})}static fromWeb(n,S){let C=n.getReader();return new Readable_({...S,read(){C.read().then(({done:n,value:S})=>{n?this.push(null):this.push(S)},n=>{this.destroy(n)})},destroy(n,S){C.cancel(n?.message).then(()=>S(null),S)}})}[Symbol.asyncIterator](){let n=this,S=[],C=!1,N=null,F=null,I=null;return n.on(`data`,n=>{if(F){let S=F;F=null,I=null,S({value:n,done:!1})}else S.push(n)}),n.on(`end`,()=>{if(C=!0,F){let n=F;F=null,I=null,n({value:void 0,done:!0})}}),n.on(`error`,n=>{if(N=n,C=!0,I){let S=I;F=null,I=null,S(n)}}),{next(){return N?Promise.reject(N):S.length>0?Promise.resolve({value:S.shift(),done:!1}):C?Promise.resolve({value:void 0,done:!0}):new Promise((n,S)=>{F=n,I=S})},return(){return n.destroy(),Promise.resolve({value:void 0,done:!0})},[Symbol.asyncIterator](){return this}}}static from(n,S){let C=new Readable_({objectMode:!0,...S,read(){}});return typeof n==`string`||ArrayBuffer.isView(n)?(C.push(n),C.push(null),C):((async()=>{try{for await(let S of n)C.push(S)||await new Promise(n=>C.once(`drain`,n));C.push(null)}catch(n){C.destroy(n)}})(),C)}},Zr.prototype[Yr]=function(){return streamAsyncDispose(this,this.readableEnded)}});function chunkLen$1(n){if(n==null)return 1;let S=n.length;return typeof S==`number`?S:1}var Duplex_,$r=__esmMin(()=>{Jr(),Qr(),Be(),Duplex_=class extends Zr{writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;allowHalfOpen;_decodeStrings;_writableState={highWaterMark:0,objectMode:!1};_duplexCorkedBuffer=[];_duplexWriting=!1;_duplexWriteQueue=[];_writeImpl;_finalImpl;_defaultEncoding=`utf8`;_pendingWrites=0;_pendingEndCb=null;constructor(n){super(n),validateHighWaterMark(`writableHighWaterMark`,n?.writableHighWaterMark),validateHighWaterMark(`readableHighWaterMark`,n?.readableHighWaterMark),this.writableObjectMode=n?.writableObjectMode??n?.objectMode??!1,this.writableHighWaterMark=n?.highWaterMark??n?.writableHighWaterMark??getDefaultHighWaterMark(this.writableObjectMode),this._writableState.highWaterMark=this.writableHighWaterMark,this._writableState.objectMode=this.writableObjectMode,n?.highWaterMark===void 0&&n?.readableHighWaterMark!==void 0&&(this.readableHighWaterMark=n.readableHighWaterMark,this._readableState.highWaterMark=n.readableHighWaterMark),n?.readableObjectMode!==void 0&&(this.readableObjectMode=n.readableObjectMode,this._readableState.objectMode=n.readableObjectMode,n?.readableHighWaterMark===void 0&&n?.highWaterMark===void 0&&(this.readableHighWaterMark=getDefaultHighWaterMark(n.readableObjectMode),this._readableState.highWaterMark=this.readableHighWaterMark)),this.allowHalfOpen=n?.allowHalfOpen!==!1,this._decodeStrings=n?.decodeStrings!==!1,n?.write&&(this._writeImpl=n.write),n?.final&&(this._finalImpl=n.final),this.allowHalfOpen||this.once(`end`,()=>{this.writableEnded||nextTick(()=>this.end())})}_write(n,S,C){this._writeImpl?this._writeImpl.call(this,n,S,C):C()}_final(n){this._finalImpl?this._finalImpl.call(this,n):n()}destroy(n){return this.destroyed?this:(this.writable=!1,super.destroy(n))}write(n,S,C){let N,F;if(typeof S==`function`?(N=S,F=this._defaultEncoding):(F=S??this._defaultEncoding,N=C??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof n==`string`){let S=globalThis.Buffer;S&&(n=S.from(n,F),F=`buffer`)}if(typeof n!=`string`&&!this.writableObjectMode){let S=globalThis.Buffer;(S&&S.isBuffer(n)||n instanceof Uint8Array)&&(F=`buffer`)}if(this.writableEnded){let n=Error(`write after end`);return nextTick(()=>{N(n),this.emit(`error`,n)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen$1(n),this.writableCorked>0)return this._duplexCorkedBuffer.push({chunk:n,encoding:F,callback:N}),this.writableLength<this.writableHighWaterMark;let I=this.writableLength<this.writableHighWaterMark;return I||(this.writableNeedDrain=!0),this._duplexDoWrite(n,F,N),I}_duplexDoWrite(n,S,C){if(this._duplexWriting){this._duplexWriteQueue.push({chunk:n,encoding:S,callback:C});return}this._duplexWriting=!0,this._duplexStartWrite(n,S,C)}_duplexStartWrite(n,S,C){this._pendingWrites++,this._write(n,S,S=>{this._pendingWrites--,this.writableLength-=this.writableObjectMode?1:chunkLen$1(n),nextTick(S?()=>{if(C(S),this._duplexWriting=!1,this.emit(`error`,S),this._duplexWriteQueue.length>0){let n=this._duplexWriteQueue.shift();this._duplexWriting=!0,this._duplexStartWrite(n.chunk,n.encoding,n.callback)}}:()=>{if(C(),this._duplexWriteQueue.length>0){let n=this._duplexWriteQueue.shift();this._duplexStartWrite(n.chunk,n.encoding,n.callback);return}if(this._duplexWriting=!1,this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._pendingWrites===0&&this._pendingEndCb){let n=this._pendingEndCb;this._pendingEndCb=null,n()}})})}end(n,S,C){typeof n==`function`&&(C=n,n=void 0),typeof S==`function`&&(C=S,S=void 0),n!=null&&this.write(n,S),this.writableEnded=!0;let doFinal=()=>{this._final(n=>{this.writableFinished=!0,this._doPrefinishHooks(()=>{nextTick(()=>{n&&this.emit(`error`,n),this.emit(`finish`),nextTick(()=>this.emit(`close`)),C&&C()})})})};return this._pendingWrites>0||this._duplexWriting||this._duplexWriteQueue.length>0?this._pendingEndCb=doFinal:doFinal(),this}_doPrefinishHooks(n){n()}cork(){this.writableCorked++}uncork(){if(this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._duplexCorkedBuffer.length>0)){let n=this._duplexCorkedBuffer.splice(0);for(let{chunk:S,encoding:C,callback:N}of n)this._write(S,C,n=>{this.writableLength-=this.writableObjectMode?1:chunkLen$1(S),n?(N(n),this.emit(`error`,n)):N()});this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,nextTick(()=>this.emit(`drain`)))}}setDefaultEncoding(n){return this._defaultEncoding=n,this}},__name$1(chunkLen$1,`chunkLen`)});function pipe(n,S,C){let N=n,F=C?.end!==!1,I=!1,ondrain=()=>{I=!1,S.removeListener(`drain`,ondrain);let n=N;typeof n.resume==`function`&&n.resume()},ondata=n=>{if(S.writable){let C=N;S.write(n)===!1&&typeof C.pause==`function`&&(C.pause(),I||(I=!0,S.on(`drain`,ondrain)))}};N.on(`data`,ondata);let H=!1,onend=()=>{H||(H=!0,F&&S.end())},onclose=()=>{if(!H&&(H=!0,F&&!(N instanceof Zr))){let n=S;typeof n.destroy==`function`&&n.destroy()}};F&&(N.on(`end`,onend),N.on(`close`,onclose));let cleanup=()=>{N.removeListener(`data`,ondata),I&&S.removeListener(`drain`,ondrain),N.removeListener(`end`,onend),N.removeListener(`close`,onclose),N.removeListener(`end`,cleanup),N.removeListener(`close`,cleanup),S.removeListener(`close`,cleanup)};return N.on(`end`,cleanup),N.on(`close`,cleanup),S.on(`close`,cleanup),N instanceof Zr&&(N._pipeDests.push({dest:S,cleanup}),N._readableState.pipes.push(S)),S.emit(`pipe`,N),S}var ei=__esmMin(()=>{Wr(),Qr(),_setPipeImpl(pipe)});function chunkLen(n){if(n==null)return 1;let S=n.length;return typeof S==`number`?S:1}var ti,ni=__esmMin(()=>{Wr(),Xr(),Jr(),Be(),ti=class Writable_ extends Stream_{static[Symbol.hasInstance](n){let S=this;return S.prototype!==void 0&&Object.prototype.isPrototypeOf.call(S.prototype,n)?!0:S.prototype!==Writable_.prototype||n==null?!1:typeof n.writableHighWaterMark==`number`}writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;destroyed=!1;_err;_writableState={ended:!1,finished:!1,constructed:!0,writing:!1};_corkedBuffer=[];_writeBuffer=[];_pendingConstruct=[];_ending=!1;_endCallback;_pendingEnd=null;_writeImpl;_writev;_finalImpl;_destroyImpl;_constructImpl;_decodeStrings;_defaultEncoding=`utf8`;_autoDestroy;constructor(n){super(n),this.writableHighWaterMark=n?.highWaterMark??getDefaultHighWaterMark(n?.objectMode??!1),this.writableObjectMode=n?.objectMode??!1,this._decodeStrings=n?.decodeStrings!==!1,this._autoDestroy=n?.autoDestroy!==!1,n?.write&&(this._writeImpl=n.write),n?.writev&&(this._writev=n.writev),n?.final&&(this._finalImpl=n.final),n?.destroy&&(this._destroyImpl=n.destroy),n?.construct&&(this._constructImpl=n.construct),(this._constructImpl||this._construct!==Writable_.prototype._construct)&&(this._writableState.constructed=!1,nextTick(()=>{this._construct(n=>{this._writableState.constructed=!0,n?this.destroy(n):this._maybeFlush()})}))}_construct(n){this._constructImpl?this._constructImpl.call(this,n):n()}_write(n,S,C){this._writeImpl?this._writeImpl.call(this,n,S,C):C()}_final(n){this._finalImpl?this._finalImpl.call(this,n):n()}_destroy(n,S){this._destroyImpl?this._destroyImpl.call(this,n,S):S(n)}_maybeFlush(){let n=this._pendingConstruct.splice(0);if(n.length>0){let[S,...C]=n;this._writeBuffer.push(...C),this._doWrite(S.chunk,S.encoding,S.callback)}if(this._pendingEnd){let{chunk:n,encoding:S,callback:C}=this._pendingEnd;this._pendingEnd=null,this._doEnd(n,S,C)}}_doWrite(n,S,C){this._writableState.writing=!0;let N=!0;this._write(n,S,S=>{if(this.writableLength-=this.writableObjectMode?1:chunkLen(n),N){nextTick(()=>{if(S){C(S),this.emit(`error`,S);return}C(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}),S||this._drainWriteBuffer();return}nextTick(S?()=>{C(S),this.emit(`error`,S),this._drainWriteBuffer()}:()=>{C(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._drainWriteBuffer()})}),N=!1}_drainWriteBuffer(){if(this._writeBuffer.length>0){let n=this._writeBuffer.shift();this._doWrite(n.chunk,n.encoding,n.callback)}else this._writableState.writing=!1,this._maybeFinish()}_maybeFinish(){!this._ending||this._writableState.finished||this._writableState.writing||this._writeBuffer.length>0||(this._ending=!1,this._final(n=>{this.writableFinished=!0,this._writableState.finished=!0,nextTick(()=>{n&&this.emit(`error`,n),this.emit(`finish`),this._autoDestroy?this.destroy():nextTick(()=>this.emit(`close`)),this._endCallback&&this._endCallback()})}))}write(n,S,C){let N,F;if(typeof S==`function`?(N=S,F=this._defaultEncoding):(F=S??this._defaultEncoding,N=C??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof n==`string`){let S=globalThis.Buffer;S&&(n=S.from(n,F),F=`buffer`)}if(typeof n!=`string`&&!this.writableObjectMode){let S=globalThis.Buffer;(S&&S.isBuffer(n)||n instanceof Uint8Array)&&(F=`buffer`)}if(this.writableEnded){let n=Error(`write after end`);return nextTick(()=>{N(n),this.emit(`error`,n)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen(n),this.writableCorked>0)return this._corkedBuffer.push({chunk:n,encoding:F,callback:N}),this.writableLength<this.writableHighWaterMark;if(!this._writableState.constructed)return this._pendingConstruct.push({chunk:n,encoding:F,callback:N}),this.writableLength<this.writableHighWaterMark;let I=this.writableLength<this.writableHighWaterMark;return I||(this.writableNeedDrain=!0),this._writableState.writing?this._writeBuffer.push({chunk:n,encoding:F,callback:N}):this._doWrite(n,F,N),I}_doEnd(n,S,C){n!=null&&this.write(n,S),this.writableEnded=!0,this._writableState.ended=!0,this._ending=!0,this._endCallback=C,this._maybeFinish()}end(n,S,C){return typeof n==`function`&&(C=n,n=void 0),typeof S==`function`&&(C=S,S=void 0),this.writableEnded?(C&&nextTick(C),this):this._writableState.constructed?(this._doEnd(n,S,C),this):(this._pendingEnd={chunk:n,encoding:S,callback:C},this)}cork(){this.writableCorked++}uncork(){this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._corkedBuffer.length>0&&this._flushCorkedBuffer())}_flushCorkedBuffer(){if(this._writev&&this._corkedBuffer.length>1){let n=this._corkedBuffer.splice(0),S=n.map(n=>({chunk:n.chunk,encoding:n.encoding}));this._writev.call(this,S,S=>{for(let S of n)this.writableLength-=this.writableObjectMode?1:chunkLen(S.chunk);if(S){for(let C of n)C.callback(S);this.emit(`error`,S)}else{for(let S of n)S.callback();this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}})}else{let n=this._corkedBuffer.splice(0);if(n.length>0){let[S,...C]=n;this._writeBuffer.push(...C),this._doWrite(S.chunk,S.encoding,S.callback)}}}setDefaultEncoding(n){return this._defaultEncoding=n,this}destroy(n){if(this.destroyed)return this;this.destroyed=!0,this.writable=!1,n&&(this._err=n);let cb=n=>{n&&nextTick(()=>this.emit(`error`,n)),nextTick(()=>this.emit(`close`))};return this._destroy(n??null,cb),this}},ti.prototype[Yr]=function(){return streamAsyncDispose(this,this.writableFinished)}}),ri,ii=__esmMin(()=>{$r(),Be(),ri=class Transform_ extends Duplex_{constructor(n){super({...n,write:void 0,final:void 0});let S=this;n?.transform&&(S._transform=n.transform),n?.flush&&(S._flush=n.flush),n?.final&&(S._final=n.final)}_transform(n,S,C){throw Object.assign(Error(`The _transform() method is not implemented`),{code:`ERR_METHOD_NOT_IMPLEMENTED`})}_flush(n){n()}_write(n,S,C){let N=!1;try{this._transform(n,S,(n,S)=>{if(N){let n=Object.assign(Error(`Callback called multiple times`),{code:`ERR_MULTIPLE_CALLBACK`});nextTick(()=>this.emit(`error`,n));return}if(N=!0,n){C(n);return}S!=null&&this.push(S),C()})}catch(n){if(n?.code===`ERR_METHOD_NOT_IMPLEMENTED`)throw n;C(n)}}_final(n){this._flush((S,C)=>{if(S){n(S);return}C!=null&&this.push(C),this.push(null),n()})}_doPrefinishHooks(n){let S=Transform_.prototype._final;this._final===S?n():S.call(this,n)}}}),PassThrough_,ai=__esmMin(()=>{ii(),PassThrough_=class extends ri{constructor(n){super({...n,transform(n,S,C){C(null,n)}})}}});function pipeline(...n){let S=n,C=typeof S[S.length-1]==`function`?S.pop():void 0,N=S;if(N.length<2)throw Error(`pipeline requires at least 2 streams`);let F=null;function onError(n){if(!F){F=n;for(let n of N)typeof n.destroy==`function`&&n.destroy();C&&C(n)}}let I=N[0];for(let n=1;n<N.length;n++){let S=N[n];I.pipe(S),I.on(`error`,onError),I=S}let H=N[N.length-1];return H.on(`error`,onError),H.on(`finish`,()=>{C&&!F&&C(null)}),H}var oi=__esmMin(()=>{}),si=__exportAll$4({Duplex:()=>fi,PassThrough:()=>mi,Readable:()=>li,Stream:()=>ci,Transform:()=>pi,Writable:()=>di,addAbortSignal:()=>addAbortSignal,default:()=>hi,finished:()=>finished$1,getDefaultHighWaterMark:()=>getDefaultHighWaterMark,isDestroyed:()=>isDestroyed,isDisturbed:()=>isDisturbed,isErrored:()=>isErrored,isReadable:()=>isReadable,isWritable:()=>isWritable,"module.exports":()=>hi,pipeline:()=>pipeline,setDefaultHighWaterMark:()=>setDefaultHighWaterMark}),ci,li,di,fi,pi,mi,hi,gi=__esmMin(()=>{Hr(),Wr(),Gr(),Jr(),Qr(),$r(),ei(),ni(),ii(),ai(),oi(),ci=makeCallable(Stream_),li=makeCallable(Zr),di=makeCallable(ti),fi=makeCallable(Duplex_),pi=makeCallable(ri),mi=makeCallable(PassThrough_),hi=Object.assign(ci,{Stream:ci,Readable:li,Writable:di,Duplex:fi,Transform:pi,PassThrough:mi,pipeline,finished:finished$1,addAbortSignal,isReadable,isWritable,isDestroyed,isDisturbed,isErrored,getDefaultHighWaterMark,setDefaultHighWaterMark})});function toUint8Array$2(n){return typeof n==`string`?new TextEncoder().encode(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function concat$1(n){let S=n.reduce((n,S)=>n+S.length,0),C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}function createGzip(n){return new Gzip(n)}function createGunzip(n){return new Gunzip(n)}function createDeflate(n){return new Deflate(n)}function createInflate(n){return new Inflate(n)}function createDeflateRaw(n){return new DeflateRaw(n)}function createInflateRaw(n){return new InflateRaw(n)}function createUnzip(n){return new Unzip(n)}function createBrotliCompress(n){throw Error(`createBrotliCompress is not supported on GJS (no Brotli in GLib)`)}function createBrotliDecompress(n){throw Error(`createBrotliDecompress is not supported on GJS (no Brotli in GLib)`)}function createZstdCompress(n){let S=Error(`createZstdCompress is not supported on GJS (no Zstd in GLib)`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}function createZstdDecompress(n){let S=Error(`createZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}var ZlibBase,Gzip,Gunzip,Deflate,Inflate,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress,ZstdCompress,ZstdDecompress,_i=__esmMin(()=>{Vr(),gi(),__name$1(toUint8Array$2,`toUint8Array`),__name$1(concat$1,`concat`),ZlibBase=class extends pi{_mode;_chunks=[];constructor(n,S){super(S),this._mode=n}_transform(n,S,C){this._chunks.push(toUint8Array$2(n)),C()}_flush(n){let S=concat$1(this._chunks);this._chunks=[];try{this.push(Buffer.from(this._run(S))),n()}catch(S){n(S instanceof Error?S:Error(String(S)))}}_run(n){let S=this._mode;switch(S.kind){case`compress`:return compressWithGio(n,S.format);case`decompress`:return decompressStreamWithGio(n,S.format);case`gunzip`:return gunzipWithGio(n);case`unzip`:return n.length>=2&&n[0]===31&&n[1]===139?gunzipWithGio(n):decompressStreamWithGio(n,`deflate`)}}},Gzip=class extends ZlibBase{constructor(n){super({kind:`compress`,format:`gzip`},n)}},Gunzip=class extends ZlibBase{constructor(n){super({kind:`gunzip`},n)}},Deflate=class extends ZlibBase{constructor(n){super({kind:`compress`,format:`deflate`},n)}},Inflate=class extends ZlibBase{constructor(n){super({kind:`decompress`,format:`deflate`},n)}},DeflateRaw=class extends ZlibBase{constructor(n){super({kind:`compress`,format:`deflate-raw`},n)}},InflateRaw=class extends ZlibBase{constructor(n){super({kind:`decompress`,format:`deflate-raw`},n)}},Unzip=class extends ZlibBase{constructor(n){super({kind:`unzip`},n)}},BrotliCompress=class extends pi{constructor(){throw super(),Error(`BrotliCompress is not supported on GJS (no Brotli in GLib)`)}},BrotliDecompress=class extends pi{constructor(){throw super(),Error(`BrotliDecompress is not supported on GJS (no Brotli in GLib)`)}},ZstdCompress=class extends pi{constructor(){super();let n=Error(`ZstdCompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}},ZstdDecompress=class extends pi{constructor(){super();let n=Error(`ZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}}}),vi=__exportAll$4({BrotliCompress:()=>BrotliCompress,BrotliDecompress:()=>BrotliDecompress,Deflate:()=>Deflate,DeflateRaw:()=>DeflateRaw,Gunzip:()=>Gunzip,Gzip:()=>Gzip,Inflate:()=>Inflate,InflateRaw:()=>InflateRaw,Unzip:()=>Unzip,ZlibTransform:()=>ZlibBase,ZstdCompress:()=>ZstdCompress,ZstdDecompress:()=>ZstdDecompress,brotliCompress:()=>brotliCompress,brotliCompressSync:()=>brotliCompressSync,brotliDecompress:()=>brotliDecompress,brotliDecompressSync:()=>brotliDecompressSync,constants:()=>bi,createBrotliCompress:()=>createBrotliCompress,createBrotliDecompress:()=>createBrotliDecompress,createDeflate:()=>createDeflate,createDeflateRaw:()=>createDeflateRaw,createGunzip:()=>createGunzip,createGzip:()=>createGzip,createInflate:()=>createInflate,createInflateRaw:()=>createInflateRaw,createUnzip:()=>createUnzip,createZstdCompress:()=>createZstdCompress,createZstdDecompress:()=>createZstdDecompress,default:()=>xi,deflate:()=>deflate,deflateRaw:()=>deflateRaw,deflateRawSync:()=>deflateRawSync,deflateSync:()=>deflateSync,gunzip:()=>gunzip$1,gunzipSync:()=>gunzipSync,gzip:()=>gzip$1,gzipSync:()=>gzipSync,inflate:()=>inflate,inflateRaw:()=>inflateRaw,inflateRawSync:()=>inflateRawSync,inflateSync:()=>inflateSync,zstdCompress:()=>zstdCompress,zstdCompressSync:()=>zstdCompressSync,zstdDecompress:()=>zstdDecompress,zstdDecompressSync:()=>zstdDecompressSync});function decompressWithGio(n,S){return S===`gzip`?gunzipWithGio(n):decompressStreamWithGio(n,S)}async function runWebTransform(n,S){let C=new ReadableStream({start(S){S.enqueue(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),S.close()}}),N=[],F=C.pipeThrough(S).getReader();for(;;){let{done:n,value:S}=await F.read();if(n)break;N.push(S)}let I=N.reduce((n,S)=>n+S.length,0),H=new Uint8Array(I),W=0;for(let n of N)H.set(n,W),W+=n.length;return H}async function compressWithWeb(n,S){return runWebTransform(n,new CompressionStream(S))}async function decompressWithWeb(n,S){return runWebTransform(n,new DecompressionStream(S))}async function compress(n,S){return hasWebCompression()?compressWithWeb(n,S):compressWithGio(n,S)}async function decompress(n,S){if(hasWebCompression())try{return await decompressWithWeb(n,S)}catch(C){if(S!==`gzip`)throw C;return decompressWithGio(n,S)}return decompressWithGio(n,S)}function toUint8Array$1(n){return typeof n==`string`?new TextEncoder().encode(n):n instanceof ArrayBuffer?new Uint8Array(n):n}function gzip$1(n,S,C){let N=typeof S==`function`?S:C;compress(toUint8Array$1(n),`gzip`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function gunzip$1(n,S,C){let N=typeof S==`function`?S:C;decompress(toUint8Array$1(n),`gzip`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function deflate(n,S,C){let N=typeof S==`function`?S:C;compress(toUint8Array$1(n),`deflate`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function inflate(n,S,C){let N=typeof S==`function`?S:C;decompress(toUint8Array$1(n),`deflate`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function deflateRaw(n,S,C){let N=typeof S==`function`?S:C;compress(toUint8Array$1(n),`deflate-raw`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function inflateRaw(n,S,C){let N=typeof S==`function`?S:C;decompress(toUint8Array$1(n),`deflate-raw`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function gzipSync(n,S){return compressWithGio(toUint8Array$1(n),`gzip`)}function gunzipSync(n,S){return decompressWithGio(toUint8Array$1(n),`gzip`)}function deflateSync(n,S){return compressWithGio(toUint8Array$1(n),`deflate`)}function inflateSync(n,S){return decompressWithGio(toUint8Array$1(n),`deflate`)}function deflateRawSync(n,S){return compressWithGio(toUint8Array$1(n),`deflate-raw`)}function inflateRawSync(n,S){return decompressWithGio(toUint8Array$1(n),`deflate-raw`)}function brotliCompress(n,S,C){(typeof S==`function`?S:C)(Error(`brotliCompress: Brotli is not supported in this environment`),yi)}function brotliDecompress(n,S,C){(typeof S==`function`?S:C)(Error(`brotliDecompress: Brotli is not supported in this environment`),yi)}function brotliCompressSync(n,S){throw Error(`brotliCompressSync: Brotli is not supported in this environment`)}function brotliDecompressSync(n,S){throw Error(`brotliDecompressSync: Brotli is not supported in this environment`)}function zstdCompress(n,S,C){let N=typeof S==`function`?S:C,F=Error(`zstdCompress: Zstd is not supported in this environment`);F.code=`ERR_UNSUPPORTED_OPERATION`,N(F,yi)}function zstdDecompress(n,S,C){let N=typeof S==`function`?S:C,F=Error(`zstdDecompress: Zstd is not supported in this environment`);F.code=`ERR_UNSUPPORTED_OPERATION`,N(F,yi)}function zstdCompressSync(n,S){let C=Error(`zstdCompressSync: Zstd is not supported in this environment`);throw C.code=`ERR_UNSUPPORTED_OPERATION`,C}function zstdDecompressSync(n,S){let C=Error(`zstdDecompressSync: Zstd is not supported in this environment`);throw C.code=`ERR_UNSUPPORTED_OPERATION`,C}var hasWebCompression,yi,bi,xi,Si=__esmMin(()=>{Vr(),_i(),hasWebCompression=()=>globalThis.CompressionStream!==void 0,__name$1(toUint8Array$1,`toUint8Array`),__name$1(gzip$1,`gzip`),__name$1(gunzip$1,`gunzip`),yi=new Uint8Array,bi={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_DEFLATED:8},xi={gzip:gzip$1,gunzip:gunzip$1,deflate,inflate,deflateRaw,inflateRaw,gzipSync,gunzipSync,deflateSync,inflateSync,deflateRawSync,inflateRawSync,brotliCompress,brotliDecompress,brotliCompressSync,brotliDecompressSync,zstdCompress,zstdDecompress,zstdCompressSync,zstdDecompressSync,Gzip,Gunzip,Deflate,Inflate,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress,ZstdCompress,ZstdDecompress,createGzip,createGunzip,createDeflate,createInflate,createDeflateRaw,createInflateRaw,createUnzip,createBrotliCompress,createBrotliDecompress,createZstdCompress,createZstdDecompress,constants:bi}});const Ci=new Set([`gzip`,`deflate`,`deflate-raw`]);function validateFormat(n){if(!Ci.has(n))throw TypeError(`Unsupported compression format: '${n}'. Supported formats: 'gzip', 'deflate', 'deflate-raw'.`);return n}const wi=typeof globalThis.CompressionStream==`function`&&typeof globalThis.DecompressionStream==`function`;let Ti=!1,Ei,Di,Oi,ki,Ai,ji;async function loadZlib(){if(Ti)return;let n=await Promise.resolve().then(()=>(Si(),vi));Ei=n.gzipSync,Di=n.gunzipSync,Oi=n.deflateSync,ki=n.inflateSync,Ai=n.deflateRawSync,ji=n.inflateRawSync,Ti=!0}function getCompressFn(n){switch(n){case`gzip`:return n=>Ei(n);case`deflate`:return n=>Oi(n);case`deflate-raw`:return n=>Ai(n)}}function getDecompressFn(n){switch(n){case`gzip`:return n=>Di(n);case`deflate`:return n=>ki(n);case`deflate-raw`:return n=>ji(n)}}function concatChunks$1(n){if(n.length===1)return n[0];let S=0;for(let C of n)S+=C.length;let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}__name$1(concatChunks$1,`concatChunks`);let Mi,Ni;if(wi)Mi=globalThis.CompressionStream,Ni=globalThis.DecompressionStream;else{let n=loadZlib();Mi=class CompressionStream{readable;writable;constructor(S){let C=validateFormat(S),N=[],F=new Ar({transform(n){N.push(n)},async flush(S){try{await n;let F=getCompressFn(C)(concatChunks$1(N));F.length>0&&S.enqueue(F)}catch(n){S.error(n)}}});this.readable=F.readable,this.writable=F.writable}},Ni=class DecompressionStream{readable;writable;constructor(S){let C=validateFormat(S),N=[],F=new Ar({transform(n){N.push(n)},async flush(S){try{await n;let F=getDecompressFn(C)(concatChunks$1(N));F.length>0&&S.enqueue(F)}catch(n){S.error(n)}}});this.readable=F.readable,this.writable=F.writable}}}const Pi=globalThis;globalThis.CompressionStream===void 0&&(Pi.CompressionStream=Mi),globalThis.DecompressionStream===void 0&&(Pi.DecompressionStream=Ni);const Fi=globalThis;globalThis.DOMException===void 0&&(Fi.DOMException=On);var Ii,__name,Li=__esmMin(()=>{Ii=Object.defineProperty,__name=(n,S)=>Ii(n,`name`,{value:S,configurable:!0})});function validateHeaderName(n){if(typeof n!=`string`||!/^[\^`\-\w!#$%&'*+.|~]+$/.test(n)){let S=TypeError(`Header name must be a valid HTTP token ["${n}"]`);throw Object.defineProperty(S,"code",{value:`ERR_INVALID_HTTP_TOKEN`}),S}}function validateHeaderValue(n,S){if(S===void 0){let S=TypeError(`Header "${n}" value must not be undefined`);throw Object.defineProperty(S,"code",{value:`ERR_HTTP_INVALID_HEADER_VALUE`}),S}if(typeof S==`string`&&/[^\t -~-ÿ]/.test(S)){let S=TypeError(`Invalid character in header content ["${n}"]`);throw Object.defineProperty(S,"code",{value:`ERR_INVALID_CHAR`}),S}}const Ri=Symbol(`Headers.headers`);function isBoxedPrimitive$2(n){return n instanceof String||n instanceof Number||n instanceof Boolean||typeof Symbol<`u`&&n instanceof Symbol||typeof BigInt<`u`&&n instanceof BigInt}__name$1(isBoxedPrimitive$2,`isBoxedPrimitive`);var zi=class Headers{[Ri];constructor(n){if(this[Ri]=new Map,n!=null){if(n instanceof Headers){for(let[S,C]of n[Ri])this[Ri].set(S,[...C]);return}if(typeof n==`object`&&!isBoxedPrimitive$2(n)){let S=n[Symbol.iterator];if(S==null)for(let[S,C]of Object.entries(n))validateHeaderName(S),validateHeaderValue(S,String(C)),this.append(S,String(C));else{if(typeof S!=`function`)throw TypeError(`Header pairs must be iterable`);for(let S of n){if(typeof S!=`object`||isBoxedPrimitive$2(S))throw TypeError(`Each header pair must be an iterable object`);let n=[...S];if(n.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);validateHeaderName(n[0]),validateHeaderValue(n[0],String(n[1])),this.append(n[0],String(n[1]))}}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'`)}}append(n,S){validateHeaderName(n),validateHeaderValue(n,S);let C=String(n).toLowerCase(),N=String(S),F=this[Ri].get(C);F?F.push(N):this[Ri].set(C,[N])}set(n,S){validateHeaderName(n),validateHeaderValue(n,S);let C=String(n).toLowerCase();this[Ri].set(C,[String(S)])}delete(n){this[Ri].delete(String(n).toLowerCase())}has(n){return this[Ri].has(String(n).toLowerCase())}get(n){let S=this[Ri].get(String(n).toLowerCase());if(!S||S.length===0)return null;let C=S.join(`, `);return/^content-encoding$/i.test(n)&&(C=C.toLowerCase()),C}getAll(n){return this[Ri].get(String(n).toLowerCase())??[]}getSetCookie(){return this[Ri].get(`set-cookie`)??[]}forEach(n,S){for(let C of this.keys())Reflect.apply(n,S,[this.get(C),C,this])}*keys(){let n=[...this[Ri].keys()].sort(),S=new Set;for(let C of n)S.has(C)||(S.add(C),yield C)}*values(){for(let n of this.keys())yield this.get(n)}*entries(){for(let n of this.keys())yield[n,this.get(n)]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`Headers`}toString(){return Object.prototype.toString.call(this)}raw(){let n={};for(let S of this.keys())n[S]=this.getAll(S);return n}_appendToSoupMessage(n,S,C=n.MessageHeadersType.REQUEST){let N=S?S.get_request_headers():new n.MessageHeaders(C);for(let[n,S]of this.entries())N.append(n,S);return N}static _newFromSoupMessage(n,S,C=n.MessageHeadersType.RESPONSE){let N=new Headers,F;return F=C===n.MessageHeadersType.RESPONSE?S.get_response_headers():S.get_request_headers(),F.foreach((n,S)=>{N.append(n,S)}),N}[Symbol.for(`nodejs.util.inspect.custom`)](){let n={};for(let S of this.keys()){let C=this.getAll(S);S===`host`?n[S]=C[0]:n[S]=C.length>1?C:C[0]}return n}};Object.defineProperties(zi.prototype,[`get`,`entries`,`forEach`,`values`].reduce((n,S)=>(n[S]={enumerable:!0},n),{}));var Bi=__esmMin(()=>{lt()});Bi();var FetchBaseError=class extends Error{type;constructor(n,S){super(n),typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,this.constructor),this.type=S}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},FetchError=class extends FetchBaseError{code;errno;erroredSysCall;constructor(n,S,C){super(n,S),C&&(this.code=this.errno=C.code,this.erroredSysCall=C.syscall)}};gn();const Vi=Symbol.toStringTag,isURLSearchParameters=n=>typeof n==`object`&&typeof n.append==`function`&&typeof n.delete==`function`&&typeof n.get==`function`&&typeof n.getAll==`function`&&typeof n.has==`function`&&typeof n.set==`function`&&typeof n.sort==`function`&&n[Vi]===`URLSearchParams`,isBlob=n=>{if(!n||typeof n!=`object`)return!1;let S=n;return typeof S.arrayBuffer==`function`&&typeof S.type==`string`&&typeof S.stream==`function`&&typeof S.constructor==`function`&&/^(Blob|File)$/.test(S[Vi])},isAbortSignal=n=>{if(typeof n!=`object`||!n)return!1;let S=n;return S[Vi]===`AbortSignal`||S[Vi]===`EventTarget`},isDomainOrSubdomain=(n,S)=>{let C=new mn(S).hostname,N=new mn(n).hostname;return C===N||C.endsWith(`.${N}`)},isSameProtocol=(n,S)=>new mn(S).protocol===new mn(n).protocol;var Hi,Ui,File,Wi=__esmMin(()=>{Hi=Symbol(`File.name`),Ui=Symbol(`File.lastModified`),File=class extends Blob{[Hi];[Ui];webkitRelativePath=``;constructor(n,S,C){super(n,C),this[Hi]=String(S),this[Ui]=C?.lastModified??Date.now()}get name(){return this[Hi]}get lastModified(){return this[Ui]}get[Symbol.toStringTag](){return`File`}}});function generateBoundary(){let n=`----formdata-`;for(let S=0;S<24;S++)n+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*62));return n}function escape(n){return n.replace(/\n/g,`%0A`).replace(/\r/g,`%0D`).replace(/"/g,`%22`)}function formDataToBlob(n,S){S??=generateBoundary();let C=[],N=`--${S}\r\nContent-Disposition: form-data; name="`;for(let[S,F]of n.entries())if(typeof F==`string`)C.push(`${N}${escape(S)}"\r\n\r\n${F.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
|
|
10
|
+
`)){let S=/^(\w+):\s+(\d+)(\s+kB)?/.exec(C);S&&n.set(S[1],parseInt(S[2],10)*(S[3]?1024:1))}if(n.size>0)return{virtual:n.get(`VmSize`)??0,resident:n.get(`VmRSS`)??0,data:n.get(`VmData`)??0,peak:n.get(`VmPeak`)??0}}let C=shellOut(n,`sh -c 'ps -o rss=,vsz= -p $PPID'`);if(!C)return null;let N=/^(\d+)\s+(\d+)$/.exec(C);return N?{virtual:parseInt(N[2],10)*1024,resident:parseInt(N[1],10)*1024,data:0,peak:0}:null}var ke,Ae=__esmMin(()=>{ke=null,__name$1(readProcessMemory$4,`readProcessMemory`)});function glib(){return globalThis.imports?.gi?.GLib}function arm(n){Fe||(Fe=!0,n.runAsync().catch(()=>{}))}function ensureMainLoop(){let n=glib();if(n)return Me?je:(je=new n.MainLoop(null,!1),Me=!0,n.main_depth()===0&&arm(je),je)}function holdMainLoop(){let n=ensureMainLoop();return n&&arm(n),n}function quitMainLoop(){je&&=(je.quit(),Me=!1,Fe=!1,null)}var je,Me,Fe,Ie=__esmMin(()=>{je=null,Me=!1,Fe=!1});function drainOnce(n){let S=Math.min(64,Le.length);for(let C=0;C<S;C++){let S=Le.shift();try{S()}catch(S){try{n.log_default_handler(`gjsify-nextTick`,n.LogLevelFlags.LEVEL_WARNING,String(S?.stack||S),null)}catch{}}}Le.length>0?n.timeout_add(n.PRIORITY_DEFAULT,1,()=>(drainOnce(n),!1)):Re=!1}function tryGLibTimeout(n){let S=globalThis.imports?.gi?.GLib;return S?.timeout_add?(Le.push(n),Re||(Re=!0,S.timeout_add(S.PRIORITY_DEFAULT,0,()=>(drainOnce(S),!1))),!0):!1}var Le,Re,nextTick,ze=__esmMin(()=>{Le=[],Re=!1,nextTick=(n,...S)=>{let C=S.length>0?()=>n(...S):n;if(!tryGLibTimeout(C)){if(typeof globalThis.process?.nextTick==`function`){globalThis.process.nextTick(n,...S);return}if(typeof queueMicrotask==`function`){queueMicrotask(C);return}Promise.resolve().then(C)}}}),Be=__esmMin(()=>{ae(),se(),ce(),le(),de(),xe(),Ce(),we(),Oe(),Ae(),Ie(),ze()});ie(),Be(),registerGlobal(`Blob`,ne),registerGlobal(`File`,re);function atobPolyfill(n){if(typeof globalThis.atob==`function`)return globalThis.atob(n);let S=n.replace(/[=\s]/g,``),C=``,N=0,F=0;for(let n=0;n<S.length;n++)N=N<<6|He[S.charCodeAt(n)],F+=6,F>=8&&(F-=8,C+=String.fromCharCode(N>>F&255));return C}function btoaPolyfill(n){if(typeof globalThis.btoa==`function`)return globalThis.btoa(n);let S=``,C=0;for(;C+2<n.length;C+=3){let N=n.charCodeAt(C)<<16|n.charCodeAt(C+1)<<8|n.charCodeAt(C+2);S+=Ve[N>>18&63]+Ve[N>>12&63]+Ve[N>>6&63]+Ve[N&63]}if(C+1===n.length){let N=n.charCodeAt(C)<<16;S+=Ve[N>>18&63]+Ve[N>>12&63]+`==`}else if(C+2===n.length){let N=n.charCodeAt(C)<<16|n.charCodeAt(C+1)<<8;S+=Ve[N>>18&63]+Ve[N>>12&63]+Ve[N>>6&63]+`=`}return S}function base64Decode$2(n){let S=n.replace(/[=\s]/g,``),C=new Uint8Array(S.length*3>>2),N=0,F=0,I=0;for(let n=0;n<S.length;n++)N=N<<6|He[S.charCodeAt(n)],F+=6,F>=8&&(F-=8,C[I++]=N>>F&255);return C.subarray(0,I)}function base64Encode$1(n){let S=``,C=n.length;for(let N=0;N<C;N+=3){let F=n[N],I=N+1<C?n[N+1]:0,H=N+2<C?n[N+2]:0;S+=Ve[F>>2],S+=Ve[(F&3)<<4|I>>4],S+=N+1<C?Ve[(I&15)<<2|H>>6]:`=`,S+=N+2<C?Ve[H&63]:`=`}return S}var Ve,He,Ue=__esmMin(()=>{Ve=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,He=new Uint8Array(256);for(let n=0;n<64;n++)He[Ve.charCodeAt(n)]=n;__name$1(base64Decode$2,`base64Decode`),__name$1(base64Encode$1,`base64Encode`)});function normalizeEncoding(n){if(!n||n===`utf8`||n===`utf-8`)return`utf8`;switch((``+n).toLowerCase().replace(/-/g,``)){case`utf8`:return`utf8`;case`ascii`:return`ascii`;case`latin1`:case`binary`:return`latin1`;case`base64`:return`base64`;case`base64url`:return`base64url`;case`hex`:return`hex`;case`ucs2`:case`utf16le`:return`utf16le`;default:return`utf8`}}function checkEncoding(n){let S=(``+n).toLowerCase().replace(/-/g,``);if(!Ge.includes(S))throw TypeError(`Unknown encoding: ${n}`)}var Ge,Ke=__esmMin(()=>{Ge=[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`]});function encodeString(n,S){switch(S){case`utf8`:return Ye().encode(n);case`ascii`:{let S=new Uint8Array(n.length);for(let C=0;C<n.length;C++)S[C]=n.charCodeAt(C)&127;return S}case`latin1`:{let S=new Uint8Array(n.length);for(let C=0;C<n.length;C++)S[C]=n.charCodeAt(C)&255;return S}case`base64`:return base64Decode$2(n.replace(/-/g,`+`).replace(/_/g,`/`));case`base64url`:return encodeString(n.replace(/-/g,`+`).replace(/_/g,`/`),`base64`);case`hex`:{let S=n.length>>>1,C=new Uint8Array(S);for(let N=0;N<S;N++){let S=parseInt(n[N*2],16),F=parseInt(n[N*2+1],16);if(Number.isNaN(S)||Number.isNaN(F))break;C[N]=S<<4|F}return C}case`utf16le`:{let S=new Uint8Array(n.length*2);for(let C=0;C<n.length;C++){let N=n.charCodeAt(C);S[C*2]=N&255,S[C*2+1]=N>>8&255}return S}default:return Ye().encode(n)}}function decodeString(n,S,C,N){let F=C!==void 0||N!==void 0?n.subarray(C??0,N??n.length):n;switch(S){case`utf8`:return Xe().decode(F);case`ascii`:{let n=``;for(let S=0;S<F.length;S++)n+=String.fromCharCode(F[S]&127);return n}case`latin1`:{let n=``;for(let S=0;S<F.length;S++)n+=String.fromCharCode(F[S]);return n}case`base64`:{let n=``;for(let S=0;S<F.length;S++)n+=String.fromCharCode(F[S]);return btoaPolyfill(n)}case`base64url`:return decodeString(F,`base64`).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);case`hex`:{let n=``;for(let S=0;S<F.length;S++)n+=F[S].toString(16).padStart(2,`0`);return n}case`utf16le`:{let n=``;for(let S=0;S+1<F.length;S+=2)n+=String.fromCharCode(F[S]|F[S+1]<<8);return n}default:return Xe().decode(F)}}function checkOffset(n,S,C){if(n+S>C)throw RangeError(`Attempt to access memory outside buffer bounds`)}var qe,Je,Ye,Xe,Ze=__esmMin(()=>{Ue(),Ye=__name$1(()=>qe??=new TextEncoder,`textEncoder`),Xe=__name$1(()=>Je??=new TextDecoder,`textDecoder`)}),Qe,$e,et,tt,nt,SlowBuffer,rt=__esmMin(()=>{Ze(),Ke(),Qe=typeof SharedArrayBuffer<`u`,$e=class Buffer extends Uint8Array{static _isBuffer=!0;static alloc(n,S,C){if(typeof n!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof n}`);if(n<0)throw RangeError(`The value "${n}" is invalid for option "size"`);let N=new Buffer(n);return S!==void 0&&S!==0&&N.fill(S,0,n,C),N}static allocUnsafe(n){if(typeof n!=`number`)throw TypeError(`The "size" argument must be of type number. Received type ${typeof n}`);return new Buffer(n)}static allocUnsafeSlow(n){return Buffer.allocUnsafe(n)}static from(n,S,C){if(typeof n==`string`){let C=normalizeEncoding(S);if(S&&typeof S==`string`){let n=(``+S).toLowerCase().replace(/-/g,``);[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`,``].includes(n)||checkEncoding(S)}let N=encodeString(n,C);return new Buffer(N.buffer,N.byteOffset,N.byteLength)}if(ArrayBuffer.isView(n)){let S=new Buffer(n.buffer,n.byteOffset,n.byteLength),C=new Buffer(S.length);return C.set(S),C}if(n instanceof ArrayBuffer){let N=S||0,F=C===void 0?n.byteLength-N:C;return new Buffer(n,N,F)}if(Qe&&n instanceof SharedArrayBuffer){let N=S||0,F=C===void 0?n.byteLength-N:C;return new Buffer(new Uint8Array(n,N,F))}if(typeof n==`object`&&n&&typeof n.viewBytes==`function`&&typeof n.byteLength==`number`&&n.constructor?.name===`SharedBuffer`){let N=n,F=S||0,I=C===void 0?N.byteLength-F:C,H=N.viewBytes(F,I);return new Buffer(H.buffer,H.byteOffset,H.byteLength)}if(Array.isArray(n)){let S=new Buffer(n.length);for(let C=0;C<n.length;C++)S[C]=n[C]&255;return S}throw TypeError(`The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array`)}static isBuffer(n){return n instanceof Buffer}static isEncoding(n){if(typeof n!=`string`)return!1;let S=n.toLowerCase().replace(/-/g,``);return[`utf8`,`ascii`,`latin1`,`binary`,`base64`,`base64url`,`hex`,`ucs2`,`utf16le`].includes(S)}static byteLength(n,S){if(typeof n!=`string`){if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer||Qe&&n instanceof SharedArrayBuffer)return n.byteLength;throw TypeError(`The "string" argument must be one of type string, Buffer, or ArrayBuffer`)}switch(normalizeEncoding(S)){case`utf8`:return new TextEncoder().encode(n).byteLength;case`ascii`:case`latin1`:return n.length;case`base64`:case`base64url`:{let S=n.length;for(;S>0&&(n[S-1]===`=`||n[S-1]===` `);)S--;return S*3>>>2}case`hex`:return n.length>>>1;case`utf16le`:return n.length*2;default:return new TextEncoder().encode(n).byteLength}}static compare(n,S){if(!(n instanceof Uint8Array)||!(S instanceof Uint8Array))throw TypeError(`Arguments must be Buffers or Uint8Arrays`);let C=Math.min(n.length,S.length);for(let N=0;N<C;N++){if(n[N]<S[N])return-1;if(n[N]>S[N])return 1}return n.length<S.length?-1:+(n.length>S.length)}static concat(n,S){if(n.length===0)return Buffer.alloc(0);if(S===void 0){S=0;for(let C=0;C<n.length;C++)S+=n[C].length}let C=Buffer.alloc(S),N=0;for(let F=0;F<n.length;F++){let I=n[F],H=Math.min(I.length,S-N);H<=0||(C.set(I.subarray(0,H),N),N+=H)}return C}static poolSize=65536;toString(n,S,C){let N=normalizeEncoding(n);return decodeString(this,N,S,C)}toJSON(){return{type:`Buffer`,data:Array.from(this)}}equals(n){if(!(n instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);if(this.length!==n.length)return!1;for(let S=0;S<this.length;S++)if(this[S]!==n[S])return!1;return!0}compare(n,S,C,N,F){if(!(n instanceof Uint8Array))throw TypeError(`Argument must be a Buffer or Uint8Array`);let I=N!==void 0||F!==void 0?this.subarray(N??0,F??this.length):this,H=S!==void 0||C!==void 0?n.subarray(S??0,C??n.length):n;return Buffer.compare(I,H)}copy(n,S=0,C=0,N){let F=N??this.length,I=Math.min(F-C,n.length-S);return I<=0?0:(n.set(this.subarray(C,C+I),S),I)}slice(n,S){let C=n??0,N=S??this.length,F=super.subarray(C,N);return new Buffer(F.buffer,F.byteOffset,F.byteLength)}subarray(n,S){let C=super.subarray(n,S);return new Buffer(C.buffer,C.byteOffset,C.byteLength)}write(n,S,C,N){S??=0;let F=encodeString(n,normalizeEncoding(N||(typeof C==`string`?C:void 0))),I=C!==void 0&&typeof C==`number`?Math.min(C,this.length-S):this.length-S,H=Math.min(F.length,I);return this.set(F.subarray(0,H),S),H}fill(n,S,C,N){let F=S??0,I=C??this.length;if(typeof n==`number`)super.fill(n&255,F,I);else if(typeof n==`string`){let S=encodeString(n,normalizeEncoding(N));if(S.length===0)super.fill(0,F,I);else if(S.length===1)super.fill(S[0],F,I);else for(let n=F;n<I;n++)this[n]=S[(n-F)%S.length]}else if(n instanceof Uint8Array)if(n.length===0)super.fill(0,F,I);else for(let S=F;S<I;S++)this[S]=n[(S-F)%n.length];return this}indexOf(n,S,C){if(typeof n==`number`)return super.indexOf(n&255,S);let N=typeof n==`string`?encodeString(n,normalizeEncoding(C)):n,F=S??0;outer:for(let n=F;n<=this.length-N.length;n++){for(let S=0;S<N.length;S++)if(this[n+S]!==N[S])continue outer;return n}return-1}lastIndexOf(n,S,C){if(typeof n==`number`)return S===void 0?super.lastIndexOf(n&255):super.lastIndexOf(n&255,S);let N=typeof n==`string`?encodeString(n,normalizeEncoding(C)):n,F=S===void 0?this.length-N.length:Math.min(S,this.length-N.length);outer:for(let n=F;n>=0;n--){for(let S=0;S<N.length;S++)if(this[n+S]!==N[S])continue outer;return n}return-1}includes(n,S,C){return this.indexOf(n,S,C)!==-1}readUInt8(n=0){return checkOffset(n,1,this.length),this[n]}readUInt16BE(n=0){return checkOffset(n,2,this.length),this[n]<<8|this[n+1]}readUInt16LE(n=0){return checkOffset(n,2,this.length),this[n]|this[n+1]<<8}readUInt32BE(n=0){return checkOffset(n,4,this.length),this[n]*16777216+(this[n+1]<<16|this[n+2]<<8|this[n+3])}readUInt32LE(n=0){return checkOffset(n,4,this.length),this[n+3]*16777216+(this[n+2]<<16|this[n+1]<<8|this[n])>>>0}readInt8(n=0){return checkOffset(n,1,this.length),this[n]|(this[n]&128?4294967040:0)}readInt16BE(n=0){checkOffset(n,2,this.length);let S=this[n]<<8|this[n+1];return S&32768?S|4294901760:S}readInt16LE(n=0){checkOffset(n,2,this.length);let S=this[n]|this[n+1]<<8;return S&32768?S|4294901760:S}readInt32BE(n=0){return checkOffset(n,4,this.length),this[n]<<24|this[n+1]<<16|this[n+2]<<8|this[n+3]}readInt32LE(n=0){return checkOffset(n,4,this.length),this[n]|this[n+1]<<8|this[n+2]<<16|this[n+3]<<24}readFloatBE(n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).getFloat32(0,!1)}readFloatLE(n=0){return checkOffset(n,4,this.length),new DataView(this.buffer,this.byteOffset+n,4).getFloat32(0,!0)}readDoubleBE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getFloat64(0,!1)}readDoubleLE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getFloat64(0,!0)}readBigInt64BE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getBigInt64(0,!1)}readBigInt64LE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getBigInt64(0,!0)}readBigUInt64BE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getBigUint64(0,!1)}readBigUInt64LE(n=0){return checkOffset(n,8,this.length),new DataView(this.buffer,this.byteOffset+n,8).getBigUint64(0,!0)}readUIntBE(n,S){checkOffset(n,S,this.length);let C=0;for(let N=0;N<S;N++)C=C*256+this[n+N];return C}readUIntLE(n,S){checkOffset(n,S,this.length);let C=0,N=1;for(let F=0;F<S;F++)C+=this[n+F]*N,N*=256;return C}readIntBE(n,S){checkOffset(n,S,this.length);let C=0;for(let N=0;N<S;N++)C=C*256+this[n+N];return C>=2**(8*S-1)&&(C-=2**(8*S)),C}readIntLE(n,S){checkOffset(n,S,this.length);let C=0,N=1;for(let F=0;F<S;F++)C+=this[n+F]*N,N*=256;return C>=2**(8*S-1)&&(C-=2**(8*S)),C}writeUInt8(n,S=0){return checkOffset(S,1,this.length),this[S]=n&255,S+1}writeUInt16BE(n,S=0){return checkOffset(S,2,this.length),this[S]=n>>>8&255,this[S+1]=n&255,S+2}writeUInt16LE(n,S=0){return checkOffset(S,2,this.length),this[S]=n&255,this[S+1]=n>>>8&255,S+2}writeUInt32BE(n,S=0){return checkOffset(S,4,this.length),this[S]=n>>>24&255,this[S+1]=n>>>16&255,this[S+2]=n>>>8&255,this[S+3]=n&255,S+4}writeUInt32LE(n,S=0){return checkOffset(S,4,this.length),this[S]=n&255,this[S+1]=n>>>8&255,this[S+2]=n>>>16&255,this[S+3]=n>>>24&255,S+4}writeInt8(n,S=0){return checkOffset(S,1,this.length),n<0&&(n=255+n+1),this[S]=n&255,S+1}writeInt16BE(n,S=0){return checkOffset(S,2,this.length),this[S]=n>>>8&255,this[S+1]=n&255,S+2}writeInt16LE(n,S=0){return checkOffset(S,2,this.length),this[S]=n&255,this[S+1]=n>>>8&255,S+2}writeInt32BE(n,S=0){return checkOffset(S,4,this.length),this[S]=n>>>24&255,this[S+1]=n>>>16&255,this[S+2]=n>>>8&255,this[S+3]=n&255,S+4}writeInt32LE(n,S=0){return checkOffset(S,4,this.length),this[S]=n&255,this[S+1]=n>>>8&255,this[S+2]=n>>>16&255,this[S+3]=n>>>24&255,S+4}writeFloatBE(n,S=0){return checkOffset(S,4,this.length),new DataView(this.buffer,this.byteOffset+S,4).setFloat32(0,n,!1),S+4}writeFloatLE(n,S=0){return checkOffset(S,4,this.length),new DataView(this.buffer,this.byteOffset+S,4).setFloat32(0,n,!0),S+4}writeDoubleBE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setFloat64(0,n,!1),S+8}writeDoubleLE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setFloat64(0,n,!0),S+8}writeBigInt64BE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setBigInt64(0,n,!1),S+8}writeBigInt64LE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setBigInt64(0,n,!0),S+8}writeBigUInt64BE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setBigUint64(0,n,!1),S+8}writeBigUInt64LE(n,S=0){return checkOffset(S,8,this.length),new DataView(this.buffer,this.byteOffset+S,8).setBigUint64(0,n,!0),S+8}swap16(){let n=this.length;if(n%2!=0)throw RangeError(`Buffer size must be a multiple of 16-bits`);for(let S=0;S<n;S+=2){let n=this[S];this[S]=this[S+1],this[S+1]=n}return this}swap32(){let n=this.length;if(n%4!=0)throw RangeError(`Buffer size must be a multiple of 32-bits`);for(let S=0;S<n;S+=4){let n=this[S],C=this[S+1];this[S]=this[S+3],this[S+1]=this[S+2],this[S+2]=C,this[S+3]=n}return this}swap64(){let n=this.length;if(n%8!=0)throw RangeError(`Buffer size must be a multiple of 64-bits`);for(let S=0;S<n;S+=8){let n=this[S],C=this[S+1],N=this[S+2],F=this[S+3];this[S]=this[S+7],this[S+1]=this[S+6],this[S+2]=this[S+5],this[S+3]=this[S+4],this[S+4]=F,this[S+5]=N,this[S+6]=C,this[S+7]=n}return this}},et=2**31-1,tt=2**28-16,nt={MAX_LENGTH:et,MAX_STRING_LENGTH:tt},SlowBuffer=class extends $e{constructor(n){super(n)}}}),it=__exportAll$4({Blob:()=>ne,Buffer:()=>$e,File:()=>re,INSPECT_MAX_BYTES:()=>50,SlowBuffer:()=>SlowBuffer,atob:()=>ot,atobPolyfill:()=>atobPolyfill,base64Decode:()=>base64Decode$2,base64Encode:()=>base64Encode$1,btoa:()=>st,btoaPolyfill:()=>btoaPolyfill,checkEncoding:()=>checkEncoding,constants:()=>nt,default:()=>ct,kMaxLength:()=>et,kStringMaxLength:()=>tt,normalizeEncoding:()=>normalizeEncoding}),ot,st,ct,lt=__esmMin(()=>{Ue(),ie(),Ke(),rt(),ot=globalThis.atob,st=globalThis.btoa,ct={Buffer:$e,SlowBuffer,Blob:ne,File:re,atob:ot,btoa:st,kMaxLength:et,kStringMaxLength:tt,constants:nt,INSPECT_MAX_BYTES:50}});lt(),`Buffer`in globalThis||Object.defineProperty(globalThis,"Buffer",{value:$e,enumerable:!1,writable:!0,configurable:!0});var ut,dt=__esmMin(()=>{ut=n}),ft,pt=__esmMin(()=>{dt(),ft=ut});pt(),typeof globalThis.btoa!=`function`&&Object.defineProperty(globalThis,"btoa",{value:function btoa(n){let S=new Uint8Array(n.length);for(let C=0;C<n.length;C++)S[C]=n.charCodeAt(C)&255;return ft.base64_encode(S)},enumerable:!0,writable:!0,configurable:!0}),typeof globalThis.atob!=`function`&&Object.defineProperty(globalThis,"atob",{value:function atob(n){let S=ft.base64_decode(n),C=``;for(let n=0;n<S.length;n++)C+=String.fromCharCode(S[n]);return C},enumerable:!0,writable:!0,configurable:!0}),Be(),typeof queueMicrotask!=`function`&&Object.defineProperty(globalThis,"queueMicrotask",{value:be,enumerable:!0,writable:!0,configurable:!0});function getGjsGlobal(){return globalThis}function getGioNamespace(){let n=getGjsGlobal().imports?.gi;if(!n)return null;let S=null;try{S=n.GioUnix??null}catch{}if(!S)try{S=n.Gio??null}catch{}return S}var mt=__esmMin(()=>{});function getMonotonicTime(){try{let n=getGjsGlobal().imports?.gi?.GLib;if(n?.get_monotonic_time)return BigInt(n.get_monotonic_time())*1000n}catch{}return typeof performance?.now==`function`?BigInt(Math.round(performance.now()*1e6)):BigInt(Date.now())*1000000n}function hrtime(n){let S=getMonotonicTime()-ht,C=Number(S/1000000000n),N=Number(S%1000000000n);if(n){let S=C-n[0],F=N-n[1];return F<0&&(S--,F+=1e9),[S,F]}return[C,N]}function hrtimeBigint(){return getMonotonicTime()-ht}var ht,gt=__esmMin(()=>{mt(),ht=getMonotonicTime()});function probeUname(){if(_t!==void 0)return _t;_t=null;try{let n=getGjsGlobal().imports?.gi?.GLib;if(!n)return _t;let S=n.spawn_sync,C=n.SpawnFlags?.SEARCH_PATH;if(!S||C===void 0)return _t;let[N,F]=S(null,[`uname`,`-sm`],null,C,null);if(!N||!F)return _t;let I=new TextDecoder().decode(F).trim().split(/\s+/);if(I.length<2)return _t;let H=mapSysname(I[0]),W=mapMachine(I[I.length-1]);if(!H||!W)return _t;_t={platform:H,arch:W}}catch{}return _t}var _t,vt=__esmMin(()=>{mt(),Be()});function detectGjsVersion(){try{let n=getGjsGlobal().imports?.system;if(n?.version!==void 0){let S=Number(n.version);return`${Math.floor(S/1e4)}.${Math.floor(S%1e4/100)}.${S%100}`}}catch{}}function detectNodeVersion(){if(typeof globalThis.process?.versions?.node==`string`)return globalThis.process.versions.node}function detectVersionInfo(){if(detectNodeVersion())return{version:globalThis.process.version,versions:{...globalThis.process.versions},title:globalThis.process?.title||`node`};let n=detectGjsVersion(),S={node:`20.0.0`};return n&&(S.gjs=n),{version:`v20.0.0`,versions:S,title:`gjs`}}function detectPpid(){return!onGjs()&&typeof globalThis.process?.ppid==`number`?globalThis.process.ppid:hostPpid()??0}function onGjs(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function detectPlatform$1(){if(onGjs()){let n=probeUname();return n?n.platform:`linux`}let n=globalThis.process;return typeof n?.platform==`string`?n.platform:`linux`}function detectArch(){if(onGjs()){let n=probeUname();return n?n.arch:`x64`}let n=globalThis.process;return typeof n?.arch==`string`?n.arch:`x64`}function getPid$1(){return!onGjs()&&typeof globalThis.process?.pid==`number`?globalThis.process.pid:hostPid()??0}var yt=__esmMin(()=>{mt(),vt(),Be(),__name$1(detectPlatform$1,`detectPlatform`),__name$1(getPid$1,`getPid`)});function getEnvProxy(){if(typeof globalThis.process?.env==`object`)return globalThis.process.env;try{let n=getGjsGlobal().imports?.gi?.GLib;if(n)return new Proxy({},{get(S,C){if(typeof C==`string`)return n.getenv(C)??void 0},set(S,C,N){return typeof C==`string`?(n.setenv(C,String(N),!0),!0):!1},deleteProperty(S,C){return typeof C==`string`?(n.unsetenv(C),!0):!1},has(S,C){return typeof C==`string`?n.getenv(C)!==null:!1},ownKeys(S){return n.listenv()},getOwnPropertyDescriptor(S,C){if(typeof C!=`string`)return;let N=n.getenv(C);if(N!==null)return{configurable:!0,enumerable:!0,writable:!0,value:N}}})}catch{}return{}}function getArgv(){if(globalThis.process?.argv!==void 0)return globalThis.process.argv;try{let n=getGjsGlobal().imports?.system;if(n?.programArgs)return[`gjs`,n.programInvocationName||``,...n.programArgs]}catch{}return[`gjs`]}function getExecPath(){let n=globalThis.process;return!isGjsHost()&&typeof n?.execPath==`string`?n.execPath:hostExecPath()??`/usr/bin/gjs`}function isGjsHost(){try{return getGjsGlobal().imports?.gi!==void 0}catch{return!1}}function getCwd(){try{let n=getGjsGlobal().imports?.gi?.GLib;if(n?.get_current_dir)return n.get_current_dir()}catch{}return`/`}function chdir(n){let S=getGjsGlobal().imports?.gi?.GLib;try{if(S?.chdir){if(!S.file_test(n,16)){let S=Error(`ENOENT: no such file or directory, chdir '${n}'`);throw S.code=`ENOENT`,S.syscall=`chdir`,S.path=n,S}S.chdir(n);return}}catch(n){if(n&&typeof n==`object`&&n.code===`ENOENT`)throw n}if(!S){let S=globalThis.process;if(S&&typeof S.chdir==`function`){S.chdir(n);return}}throw Error(`process.chdir() is not supported in this environment`)}var bt=__esmMin(()=>{mt(),Be()});function exitProcess(n){let S=getGjsGlobal().imports,C=S?.gi?.GLib,N=S?.system,F=C?.idle_add,I=C?.SOURCE_REMOVE,H=C?.PRIORITY_DEFAULT,W=C?.MainContext;if(N?.exit&&F&&typeof H==`number`&&typeof I==`boolean`&&typeof W?.default==`function`){F(H,()=>(N.exit(n),I));let S=W.default();for(;;)S.iteration(!0)}try{N?.exit&&N.exit(n)}catch{}let q=globalThis.process;throw q&&typeof q.exit==`function`&&q.exit(n),Error(`process.exit(${n})`)}var xt=__esmMin(()=>{mt()});function isGjs$1(){return getGjsGlobal().imports?.gi?.GLib!==void 0}function killPid(n,S){try{let C=getGjsGlobal().imports?.gi?.GLib;if(C){let N=typeof S==`number`?String(S):S||`SIGTERM`,F=N.startsWith(`SIG`)?`-${N.slice(3)}`:`-${N}`;return C.spawn_command_line_sync(`kill ${F} ${n}`),!0}}catch{}if(!isGjs$1()){let C=globalThis.process;if(C&&typeof C.kill==`function`)return C.kill(n,S)}throw Error(`process.kill() is not supported in this environment`)}function memoryUsage(){let n=readProcessMemory$4();if(n)return{rss:n.resident,heapTotal:n.resident,heapUsed:n.resident,external:0,arrayBuffers:0};if(!isGjs$1()){let n=globalThis.process;if(n&&typeof n.memoryUsage==`function`)return n.memoryUsage()}return{rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}}function cpuUsage(n){if(!isGjs$1()){let S=globalThis.process;if(S&&typeof S.cpuUsage==`function`)return S.cpuUsage(n)}return{user:0,system:0}}function readUmask(){try{let n=getGjsGlobal().imports?.gi?.GLib;if(n){let[S,C]=n.file_get_contents(`/proc/self/status`);if(S){let n=/^Umask:\s*([0-7]+)/m.exec(new TextDecoder().decode(C));if(n)return parseInt(n[1],8)}}}catch{}return 18}var St=__esmMin(()=>{mt(),Be(),__name$1(isGjs$1,`isGjs`)});function resolveSignalAdd(){let n=getGjsGlobal().imports?.gi;if(!n)return null;for(let[S,C]of[[`GLibUnix`,`signal_add`],[`GLib`,`unix_signal_add`]])try{let N=n[S]?.[C];if(typeof N==`function`)return N}catch{}return null}function isDeliverableSignal(n){return typeof n==`string`&&n in Ct}function armSignal(n,S){if(wt.has(n))return;let C=Ct[n],N=resolveSignalAdd(),F=getGjsGlobal().imports?.gi?.GLib;if(C===void 0||N===null||!F)return;let I=F.PRIORITY_DEFAULT,H=N(I,C,()=>(S(n),!0));wt.set(n,H)}function disarmSignal(n){let S=wt.get(n);if(S===void 0)return;wt.delete(n);let C=getGjsGlobal().imports?.gi?.GLib;C&&typeof C.source_remove==`function`&&C.source_remove(S)}var Ct,wt,Tt=__esmMin(()=>{mt(),Ct={SIGHUP:1,SIGINT:2,SIGTERM:15},wt=new Map}),Et,Dt,Ot,kt=__esmMin(()=>{if(Et=null,Dt=globalThis.imports?.gi,Dt)try{Et=Dt.GjsifyTerminal}catch{}Ot=Et});function onceWrapper(){let{target:n,type:S,listener:C}=this;return this.wrapperFn&&n.removeListener(S,this.wrapperFn),C.apply(n,Array.from(arguments))}function _onceWrap(n,S,C){let N={target:n,type:S,listener:C,wrapperFn:void 0},F=onceWrapper.bind(N);return N.wrapperFn=F,F.listener=C,F}function arrayClone(n){switch(n.length){case 0:return[];case 1:return[n[0]];case 2:return[n[0],n[1]];case 3:return[n[0],n[1],n[2]];default:return n.slice()}}function checkListener(n){if(typeof n!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof n)}function validateNumber(n,S){if(typeof n!=`number`||n!==n)throw TypeError(`The "${S}" argument must be of type number. Received type ${typeof n}`)}function spliceOne(n,S){for(;S+1<n.length;S++)n[S]=n[S+1];n.pop()}function unwrapListeners(n){let S=Array.from({length:n.length});for(let C=0;C<S.length;++C)S[C]=n[C].listener??n[C];return S}function createAbortError$2(n){let S=Error(`The operation was aborted`);return S.name=`AbortError`,S.code=`ABORT_ERR`,n?.reason&&(S.cause=n.reason),S}var At,jt,Mt,Nt=__esmMin(()=>{ye(),At=Symbol(`kCapture`),jt=Symbol.for(`nodejs.rejection`),Mt=class EventEmitter{static defaultMaxListeners=10;static errorMonitor=Symbol(`events.errorMonitor`);static captureRejectionSymbol=jt;static _captureRejections=!1;static get captureRejections(){return EventEmitter._captureRejections}static set captureRejections(n){if(typeof n!=`boolean`)throw TypeError(`The "captureRejections" argument must be of type boolean.`);EventEmitter._captureRejections=n}_events;_eventsCount;_maxListeners;[At];constructor(n){this._events=Object.create(null),this._eventsCount=0,this._maxListeners=void 0,this[At]=n?.captureRejections??EventEmitter._captureRejections}setMaxListeners(n){if(validateNumber(n,`n`),n<0)throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+n);return this._maxListeners=n,this}getMaxListeners(){return this._maxListeners??EventEmitter.defaultMaxListeners}emit(n,...S){let C=this._events,N=n===`error`;if(C!==void 0)N&&C[EventEmitter.errorMonitor]!==void 0&&this.emit(EventEmitter.errorMonitor,...S),N&&=C.error===void 0;else if(!N)return!1;if(N){let n;if(n=S.length>0?S[0]:Error(`Unhandled error.`),n instanceof Error)throw n;let C=Error(`Unhandled error. (`+n+`)`);throw C.context=n,C}let F=C[n];if(F===void 0)return!1;if(typeof F==`function`){let C=F.apply(this,S);C!=null&&this[At]&&this._addCatch(C,n,S)}else{let C=arrayClone(F),N=C.length;for(let F=0;F<N;++F){let N=C[F].apply(this,S);N!=null&&this[At]&&this._addCatch(N,n,S)}}return!0}_addCatch(n,S,C){typeof n?.then==`function`&&n.then(void 0,n=>{let N=this[jt];if(typeof N==`function`)N.call(this,n,S,...C);else{let S=this[At];try{this[At]=!1,this.emit(`error`,n)}finally{this[At]=S}}})}addListener(n,S){return this._addListener(n,S,!1)}on(n,S){return this._addListener(n,S,!1)}prependListener(n,S){return this._addListener(n,S,!0)}_addListener(n,S,C){checkListener(S);let N=this._events;N===void 0?(N=this._events=Object.create(null),this._eventsCount=0):N.newListener!==void 0&&(this.emit(`newListener`,n,S.listener??S),N=this._events);let F=N[n];F===void 0?(N[n]=S,++this._eventsCount):typeof F==`function`?N[n]=C?[S,F]:[F,S]:C?F.unshift(S):F.push(S);let I=this.getMaxListeners();if(I>0){let S=typeof N[n]==`function`?1:N[n].length;if(S>I&&!N[n].warned){typeof N[n]!=`function`&&(N[n].warned=!0);let C=Error(`Possible EventEmitter memory leak detected. ${S} ${String(n)} listeners added to [${this.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);C.name=`MaxListenersExceededWarning`,ve.warn(C.message)}}return this}once(n,S){return checkListener(S),this.on(n,_onceWrap(this,n,S)),this}prependOnceListener(n,S){return checkListener(S),this.prependListener(n,_onceWrap(this,n,S)),this}removeListener(n,S){checkListener(S);let C=this._events;if(C===void 0)return this;let N=C[n];if(N===void 0)return this;if(N===S||N.listener===S)--this._eventsCount===0?this._events=Object.create(null):(delete C[n],C.removeListener&&this.emit(`removeListener`,n,N.listener??S));else if(typeof N!=`function`){let F=-1;for(let n=N.length-1;n>=0;n--)if(N[n]===S||N[n].listener===S){F=n;break}if(F<0)return this;F===0?N.shift():spliceOne(N,F),N.length===1&&(C[n]=N[0]),C.removeListener!==void 0&&this.emit(`removeListener`,n,S.listener??S)}return this}off(n,S){return this.removeListener(n,S)}removeAllListeners(n){let S=this._events;if(S===void 0)return this;if(S.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):S[n]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete S[n]),this;if(arguments.length===0){let n=Object.keys(S);for(let S=0;S<n.length;++S){let C=n[S];C!==`removeListener`&&this.removeAllListeners(C)}return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}let C=S[n];if(typeof C==`function`)this.removeListener(n,C);else if(C!==void 0)for(let S=C.length-1;S>=0;S--)this.removeListener(n,C[S]);return this}listeners(n){let S=this._events;if(S===void 0)return[];let C=S[n];return C===void 0?[]:typeof C==`function`?[C.listener??C]:unwrapListeners(C)}rawListeners(n){let S=this._events;if(S===void 0)return[];let C=S[n];return C===void 0?[]:typeof C==`function`?[C]:arrayClone(C)}listenerCount(n){let S=this._events;if(S===void 0)return 0;let C=S[n];return C===void 0?0:typeof C==`function`?1:C.length}eventNames(){return(this._eventsCount??0)>0?Reflect.ownKeys(this._events):[]}static once(n,S,C){return new Promise((N,F)=>{let I=C?.signal;if(I?.aborted){F(createAbortError$2(I));return}if(typeof n.addEventListener==`function`){let C=n,handler=(...n)=>{I&&I.removeEventListener(`abort`,abortHandler),N(n)},errorHandler=n=>{I&&I.removeEventListener(`abort`,abortHandler),C.removeEventListener(`error`,errorHandler),F(n)},abortHandler=()=>{C.removeEventListener(S,handler),C.removeEventListener(`error`,errorHandler),F(createAbortError$2(I))};C.addEventListener(S,handler,{once:!0}),S!==`error`&&C.addEventListener(`error`,errorHandler,{once:!0}),I&&I.addEventListener(`abort`,abortHandler,{once:!0});return}let H=n,eventHandler=(...n)=>{I&&I.removeEventListener(`abort`,abortHandler),errorHandler!==void 0&&H.removeListener(`error`,errorHandler),N(n)},errorHandler;S!==`error`&&(errorHandler=n=>{H.removeListener(S,eventHandler),I&&I.removeEventListener(`abort`,abortHandler),F(n)},H.once(`error`,errorHandler)),H.once(S,eventHandler);let abortHandler=()=>{H.removeListener(S,eventHandler),errorHandler&&H.removeListener(`error`,errorHandler),F(createAbortError$2(I))};I&&I.addEventListener(`abort`,abortHandler,{once:!0})})}static on(n,S,C){let N=C?.signal;if(N?.aborted)throw createAbortError$2(N);let F=C?.highWaterMark??2**53-1,I=C?.lowWaterMark??1;validateNumber(F,`highWaterMark`),validateNumber(I,`lowWaterMark`);let H=[],W=[],q=null,Y=!1,X=!1,eventHandler=(...S)=>{if(W.length>0){let{resolve:n}=W.shift();n({value:S,done:!1})}else H.push(S),H.length>=F&&!X&&(X=!0,typeof n.pause==`function`&&n.pause())},errorHandler=n=>{if(q=n,W.length>0){let{reject:S}=W.shift();S(n)}Z.return()},abortHandler=()=>{errorHandler(createAbortError$2(N))};n.on(S,eventHandler),S!==`error`&&n.on(`error`,errorHandler),N&&N.addEventListener(`abort`,abortHandler,{once:!0});let cleanup=()=>{n.removeListener(S,eventHandler),n.removeListener(`error`,errorHandler),N&&N.removeEventListener(`abort`,abortHandler),Y=!0;for(let{resolve:n}of W)n({value:void 0,done:!0});W.length=0,H.length=0},Z={next(){if(H.length>0){let S=H.shift();return X&&H.length<I&&(X=!1,typeof n.resume==`function`&&n.resume()),Promise.resolve({value:S,done:!1})}if(q){let n=Promise.reject(q);return q=null,n}return Y?Promise.resolve({value:void 0,done:!0}):new Promise((n,S)=>{W.push({resolve:n,reject:S})})},return(){return cleanup(),Promise.resolve({value:void 0,done:!0})},throw(n){return Y||(q=n,cleanup()),Promise.reject(n)},[Symbol.asyncIterator](){return this}};return Z}static listenerCount(n,S){return n.listenerCount(S)}static getEventListeners(n,S){return typeof n.listeners==`function`?n.listeners(S):[]}static setMaxListeners(n,...S){if(validateNumber(n,`n`),n<0)throw RangeError(`The value of "n" is out of range.`);if(S.length===0)EventEmitter.defaultMaxListeners=n;else for(let C of S)typeof C.setMaxListeners==`function`&&C.setMaxListeners(n)}static getMaxListeners(n){return typeof n.getMaxListeners==`function`?n.getMaxListeners():EventEmitter.defaultMaxListeners}static addAbortListener(n,S){n.aborted&&Promise.resolve().then(()=>S());let handler=()=>S();return n.addEventListener(`abort`,handler,{once:!0}),{[Symbol.dispose](){n.removeEventListener(`abort`,handler)}}}},Mt.EventEmitter=Mt;for(let n of[`setMaxListeners`,`getMaxListeners`,`emit`,`addListener`,`on`,`prependListener`,`once`,`prependOnceListener`,`removeListener`,`off`,`removeAllListeners`,`listeners`,`rawListeners`,`listenerCount`,`eventNames`]){let S=Mt.prototype[n];typeof S==`function`&&Object.defineProperty(Mt.prototype,n,{enumerable:!0,configurable:!0,writable:!0,value:S})}Object.defineProperty(Mt.prototype,"_events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(Mt.prototype,"_eventsCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(Mt.prototype,"_maxListeners",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),__name$1(createAbortError$2,`createAbortError`)}),Pt=__exportAll$4({EventEmitter:()=>Ft,addAbortListener:()=>Gt,captureRejectionSymbol:()=>It,default:()=>Ft,defaultMaxListeners:()=>Rt,errorMonitor:()=>Lt,getEventListeners:()=>Ut,getMaxListeners:()=>Bt,listenerCount:()=>Wt,"module.exports":()=>Ft,on:()=>Ht,once:()=>Vt,setMaxListeners:()=>zt}),Ft,It,Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt=__esmMin(()=>{Nt(),Be(),Ft=makeCallable(Mt),Ft.EventEmitter=Ft,It=Ft.captureRejectionSymbol,Lt=Ft.errorMonitor,Rt=Ft.defaultMaxListeners,zt=Ft.setMaxListeners,Bt=Ft.getMaxListeners,Vt=Ft.once,Ht=Ft.on,Ut=Ft.getEventListeners,Wt=Ft.listenerCount,Gt=Ft.addAbortListener});function normalizeAndValidateEncoding(n){return n&&checkEncoding(n),normalizeEncoding(n)}function utf8DecodeMaximalSubpart(n,S,C){let N=``,F=S;for(;F<C;){let S=n[F];if(S<=127){N+=String.fromCharCode(S),F++;continue}if(S>=194&&S<=223){F+1<C&&n[F+1]>=128&&n[F+1]<=191?(N+=String.fromCharCode((S&31)<<6|n[F+1]&63),F+=2):(N+=`�`,F++);continue}if(S>=224&&S<=239){let I,H;if(S===224?(I=160,H=191):S===237?(I=128,H=159):(I=128,H=191),F+1>=C){N+=`�`,F++;continue}let W=n[F+1];if(W<I||W>H){N+=`�`,F++;continue}if(F+2>=C){N+=`�`,F+=2;continue}let q=n[F+2];if(q<128||q>191){N+=`�`,F+=2;continue}let Y=(S&15)<<12|(W&63)<<6|q&63;N+=String.fromCharCode(Y),F+=3;continue}if(S>=240&&S<=244){let I,H;if(S===240?(I=144,H=191):S===244?(I=128,H=143):(I=128,H=191),F+1>=C){N+=`�`,F++;continue}let W=n[F+1];if(W<I||W>H){N+=`�`,F++;continue}if(F+2>=C){N+=`�`,F+=2;continue}let q=n[F+2];if(q<128||q>191){N+=`�`,F+=2;continue}if(F+3>=C){N+=`�`,F+=3;continue}let Y=n[F+3];if(Y<128||Y>191){N+=`�`,F+=3;continue}let X=(S&7)<<18|(W&63)<<12|(q&63)<<6|Y&63;N+=String.fromCharCode(55296+(X-65536>>10),56320+(X-65536&1023)),F+=4;continue}N+=`�`,F++}return N}function utf8CharLength(n){return n&128?n>=194&&n<=223?2:n>=224&&n<=239?3:n>=240&&n<=244?4:0:1}function isValidContinuation(n,S,C,N){if(C===1){if(S===3)return n===224?N>=160&&N<=191:n===237?N>=128&&N<=159:N>=128&&N<=191;if(S===4)return n===240?N>=144&&N<=191:n===244?N>=128&&N<=143:N>=128&&N<=191}return N>=128&&N<=191}function writeUtf8(n,S){let C=0,N=``;if(n._lastNeed>0){for(;C<S.length&&n._lastNeed>0;){let F=S[C],I=n._lastTotal-n._lastNeed;if(isValidContinuation(n._lastLeadByte,n._lastTotal,I,F))n._lastChar[I]=F,n._lastNeed--,C++;else{N+=`�`,n._lastNeed=0,n._lastTotal=0,n._lastLeadByte=0;break}}if(n._lastNeed===0&&n._lastTotal>0&&(N+=utf8DecodeMaximalSubpart(n._lastChar,0,n._lastTotal),n._lastTotal=0,n._lastLeadByte=0),n._lastNeed>0)return N}let F=S.length;for(let N=0;N<Math.min(4,S.length-C);N++){let I=S.length-1-N;if(I<C)break;let H=S[I];if((H&192)!=128){let C=utf8CharLength(H);if(C>0&&H>=128){let N=S.length-I;if(N<C){let W=!0;for(let n=1;n<N;n++)if(!isValidContinuation(H,C,n,S[I+n])){W=!1;break}if(W){F=I;for(let C=0;C<N;C++)n._lastChar[C]=S[I+C];n._lastNeed=C-N,n._lastTotal=C,n._lastLeadByte=H}}}break}}return F>C&&(N+=utf8DecodeMaximalSubpart(S,C,F)),N}function writeUtf16le(n,S){let C=``,N=0;if(n._lastNeed>0){let F=n._lastTotal-n._lastNeed,I=Math.min(n._lastNeed,S.length);for(let C=0;C<I;C++)n._lastChar[F+C]=S[C];if(n._lastNeed-=I,N=I,n._lastNeed>0)return``;let H=n._lastTotal,W=0;for(;W+1<H;){let F=n._lastChar[W]|n._lastChar[W+1]<<8;if(W+=2,F>=55296&&F<=56319){if(W+1<H){let S=n._lastChar[W]|n._lastChar[W+1]<<8;if(S>=56320&&S<=57343){C+=String.fromCharCode(F,S),W+=2;continue}}if(N+1<S.length){let n=S[N]|S[N+1]<<8;if(n>=56320&&n<=57343){C+=String.fromCharCode(F,n),N+=2;continue}}else if(N>=S.length)return n._lastChar[0]=n._lastChar[W-2],n._lastChar[1]=n._lastChar[W-1],n._lastNeed=2,n._lastTotal=4,C}C+=String.fromCharCode(F)}n._lastTotal=0}for(;N+1<S.length;){let F=S[N]|S[N+1]<<8;if(N+=2,F>=55296&&F<=56319)if(N+1<S.length){let n=S[N]|S[N+1]<<8;if(n>=56320&&n<=57343){C+=String.fromCharCode(F,n),N+=2;continue}}else if(N<S.length)return C+=String.fromCharCode(F),n._lastChar[0]=S[N],n._lastNeed=1,n._lastTotal=2,C;else return n._lastChar[0]=S[N-2],n._lastChar[1]=S[N-1],n._lastNeed=2,n._lastTotal=4,C;C+=String.fromCharCode(F)}return N<S.length&&(n._lastChar[0]=S[N],n._lastNeed=1,n._lastTotal=2),C}function writeBase64(n,S){let C=0;if(n._lastNeed>0){let N=Math.min(n._lastNeed,S.length);for(let C=0;C<N;C++)n._lastChar[n._lastTotal-n._lastNeed+C]=S[C],n._lastNeed--;if(C=N,n._lastNeed>0)return``}let N=S.length-C,F=N-N%3,I=``;n._lastTotal>0&&n._lastNeed===0&&(I+=base64Encode$1(n._lastChar.subarray(0,n._lastTotal)),n._lastTotal=0),F>0&&(I+=base64Encode$1(S.subarray(C,C+F)));let H=N-F;if(H>0){for(let N=0;N<H;N++)n._lastChar[N]=S[C+F+N];n._lastNeed=3-H,n._lastTotal=3}return I}function decodeAscii(n){let S=``;for(let C=0;C<n.length;C++)S+=String.fromCharCode(n[C]&127);return S}function decodeLatin1(n){let S=``;for(let C=0;C<n.length;C++)S+=String.fromCharCode(n[C]);return S}function decodeHex(n){let S=``;for(let C=0;C<n.length;C++)S+=n[C].toString(16).padStart(2,`0`);return S}var qt,Jt=__esmMin(()=>{lt(),qt=function StringDecoder(n){this.encoding=normalizeAndValidateEncoding(n),this._lastNeed=0,this._lastTotal=0,this._lastLeadByte=0,this.encoding===`utf8`||this.encoding===`utf16le`?this._lastChar=new Uint8Array(4):this.encoding===`base64`?this._lastChar=new Uint8Array(3):this._lastChar=new Uint8Array},qt.prototype.write=function write(n){if(n.length===0)return``;switch(this.encoding){case`utf8`:return writeUtf8(this,n);case`utf16le`:return writeUtf16le(this,n);case`base64`:return writeBase64(this,n);case`ascii`:return decodeAscii(n);case`latin1`:return decodeLatin1(n);case`hex`:return decodeHex(n);default:return decodeAscii(n)}},qt.prototype.end=function end(n){let S=``;if(n&&n.length>0&&(S=this.write(n)),this.encoding===`utf8`&&this._lastNeed>0)S+=`�`,this._lastNeed=0,this._lastTotal=0;else if(this.encoding===`utf16le`&&this._lastNeed>0){let n=this._lastTotal-this._lastNeed;for(let C=0;C+1<n;C+=2)S+=String.fromCharCode(this._lastChar[C]|this._lastChar[C+1]<<8);this._lastNeed=0,this._lastTotal=0}else if(this.encoding===`base64`&&this._lastNeed>0){let n=this._lastChar.subarray(0,this._lastTotal-this._lastNeed);S+=base64Encode$1(n),this._lastNeed=0,this._lastTotal=0}return S}}),Yt,ProcessWriteStream,ProcessReadStream,Xt=__esmMin(()=>{ye(),mt(),kt(),Kt(),Be(),Jt(),Yt=new TextEncoder,ProcessWriteStream=class extends Ft{fd;writable=!0;_outGio=null;constructor(n){super(),this.fd=n;let S=getGioNamespace();if(S){let n=S.UnixOutputStream??S.OutputStream;if(n)try{this._outGio=n.new(this.fd,!1)}catch{}}}write(n){if(this._outGio)try{let S=typeof n==`string`?Yt.encode(n):n;return this._outGio.write_all(S,null),!0}catch{}return this.fd===2?ve.error(n):ve.log(n),!0}get isTTY(){if(Ot)return Ot.Terminal.is_tty(this.fd);try{let n=getGjsGlobal().imports?.gi?.GLib;if(n)return!!n.log_writer_supports_color(this.fd)}catch{}return!1}get columns(){if(Ot){let[n,,S]=Ot.Terminal.get_size(this.fd);if(n&&S>0)return S}try{let n=getGjsGlobal().imports?.gi?.GLib;if(n){let S=parseInt(n.getenv(`COLUMNS`)??`0`,10);if(S>0)return S}}catch{}return 80}end(){}destroy(){}get rows(){if(Ot){let[n,S]=Ot.Terminal.get_size(this.fd);if(n&&S>0)return S}try{let n=getGjsGlobal().imports?.gi?.GLib;if(n){let S=parseInt(n.getenv(`LINES`)??`0`,10);if(S>0)return S}}catch{}return 24}},ProcessReadStream=class extends Ft{fd;isRaw=!1;_gio=null;_stdinGio=null;_reading=!1;_flowing=!1;_sttyCleanupRegistered=!1;_mainLoopHeld=!1;_pendingRead=!1;_decoder=null;constructor(n){super(),this.fd=n,this._gio=getGioNamespace()}get isTTY(){return Ot?Ot.Terminal.is_tty(this.fd):!1}setRawMode(n){return Ot&&Ot.Terminal.set_raw_mode(this.fd,n)?(this.isRaw=n,this):(this._setRawModeViaStty(n),this.isRaw=n,this)}_setRawModeViaStty(n){try{let S=globalThis.imports?.gi,C=S?.Gio??S?.Gio;if(!C)return;let N=C.SubprocessFlags?.STDIN_INHERIT??2,F=n?[`stty`,`-icanon`,`-echo`,`-icrnl`,`-isig`,`min`,`1`,`time`,`0`]:[`stty`,`icanon`,`echo`,`icrnl`,`isig`];if(new C.SubprocessLauncher({flags:N}).spawnv(F).wait(null),n&&!this._sttyCleanupRegistered){this._sttyCleanupRegistered=!0;let n=globalThis.process;n?.once&&typeof n.once==`function`&&n.once(`exit`,()=>this._setRawModeViaStty(!1))}}catch{}}setEncoding(n){return this._decoder=new qt(n),this}_pushData(n){if(this._decoder){let S=this._decoder.write(n);S.length>0&&this.emit(`data`,S)}else this.emit(`data`,n)}on(n,S){let C=n===`data`&&this.listenerCount(`data`)===0;return super.on(n,S),C&&n===`data`&&this.resume(),this}addListener(n,S){return this.on(n,S)}once(n,S){return super.once(n,S),this}removeListener(n,S){return super.removeListener(n,S),n===`data`&&this.listenerCount(`data`)===0&&this.pause(),this}off(n,S){return this.removeListener(n,S)}removeAllListeners(n){let S=n===void 0||n===`data`?this.listenerCount(`data`)>0:!1;return super.removeAllListeners(n),S&&this.listenerCount(`data`)===0&&this.pause(),this}resume(){return this._flowing=!0,this._gio&&this.fd===0&&!this._reading&&this._startReading(),this}pause(){if(this._flowing=!1,this._reading=!1,this._mainLoopHeld){this._mainLoopHeld=!1;let n=globalThis.imports?.gi,S=n?.GLib??n?.GLib;S?.idle_add?S.idle_add(300,()=>(this._mainLoopHeld||quitMainLoop(),!1)):quitMainLoop()}return this}read(){return null}_startReading(){if(!this._gio||this._reading)return;if(this._pendingRead){this._reading=!0,this._mainLoopHeld||(this._mainLoopHeld=!0,ensureMainLoop());return}if(this._reading=!0,this._mainLoopHeld||(this._mainLoopHeld=!0,ensureMainLoop()),!this._stdinGio){let n=this._gio.UnixInputStream??this._gio.InputStream;if(!n){this._reading=!1;return}try{this._stdinGio=n.new(this.fd,!1)}catch{this._reading=!1;return}}let loop=()=>{if(!this._reading){this._pendingRead=!1;return}this._pendingRead=!0,this._stdinGio.read_bytes_async(4096,0,null,(n,S)=>{this._pendingRead=!1;try{let C=n.read_bytes_finish(S)?.get_data?.()??null;if(C&&C.byteLength>0)this._pushData(Buffer.from(C));else if(C!==null&&C.byteLength===0){if(this._reading=!1,this._decoder){let n=this._decoder.end();n.length>0&&this.emit(`data`,n)}this.emit(`end`);return}}catch{this._reading=!1;return}this._reading&&loop()})};loop()}}});function defineLazy(n,S,C){Object.defineProperty(n,S,{configurable:!0,enumerable:!0,get(){let N=C();return Object.defineProperty(n,S,{value:N,configurable:!0,enumerable:!0,writable:!1}),N}})}var Zt,Process,Qt=__esmMin(()=>{ye(),yt(),bt(),xt(),gt(),St(),Tt(),Xt(),Kt(),Zt=Date.now(),Process=class extends Ft{platform;arch;env;argv;argv0;execPath;pid;ppid;version;versions;title;execArgv;config;exitCode;constructor(){super(),defineLazy(this,`platform`,detectPlatform$1),defineLazy(this,`arch`,detectArch),this.env=getEnvProxy(),this.argv=getArgv(),this.argv0=this.argv[0]||`gjs`,this.execPath=getExecPath(),this.execArgv=globalThis.process?.execArgv??[],this.config=globalThis.process?.config??{target_defaults:{},variables:{}},this.pid=getPid$1(),this.ppid=detectPpid();let n=detectVersionInfo();this.version=n.version,this.versions=n.versions,this.title=n.title,this.on(`newListener`,n=>{isDeliverableSignal(n)&&armSignal(n,n=>this.emit(n,n))}),this.on(`removeListener`,n=>{isDeliverableSignal(n)&&this.listenerCount(n)===0&&disarmSignal(n)})}cwd(){return getCwd()}chdir(n){chdir(n)}kill(n,S){return killPid(n,S)}exit(n){return this.exitCode=n??this.exitCode??0,this.emit(`exit`,this.exitCode),exitProcess(this.exitCode)}nextTick(n,...S){typeof queueMicrotask==`function`?queueMicrotask(()=>n(...S)):Promise.resolve().then(()=>n(...S))}hrtime(n){return hrtime(n)}uptime(){return(Date.now()-Zt)/1e3}memoryUsage(){return memoryUsage()}cpuUsage(n){return cpuUsage(n)}stdout=new ProcessWriteStream(1);stderr=new ProcessWriteStream(2);stdin=new ProcessReadStream(0);abort(){this.exit(1)}umask(n){let S=readUmask();return n!==void 0&&!this._umaskWarned&&(this._umaskWarned=!0,this.emitWarning(`process.umask(0${n.toString(8)}) cannot change the file-creation mask under GJS — there is no umask(2) binding, so the mask is UNCHANGED. Pass an explicit \`mode\` to open/mkdir/writeFile instead; the kernel applies it atomically at creation.`,`UnsupportedWarning`)),S}_umaskWarned=!1;emitWarning(n,S){ve.warn(typeof n==`string`?`(${S||`Warning`}): ${n}`:n.message)}},Process.prototype.hrtime.bigint=function(){return hrtimeBigint()}}),$t,en,tn,nn,rn,an,on,sn=__esmMin(()=>{if(gt(),Qt(),kt(),$t=new Process,Ot)try{let n=new Ot.ResizeWatcher;n.connect(`resized`,(n,S,C)=>{$t.stdout.emit(`resize`),$t.stderr.emit(`resize`)}),n.start()}catch{}en=$t.platform,$t.arch,$t.env,$t.argv,$t.argv0,tn=$t.execPath,$t.pid,$t.ppid,$t.version,$t.versions,$t.cwd.bind($t),$t.chdir.bind($t),$t.exit.bind($t),$t.nextTick.bind($t),nn=Object.assign($t.hrtime.bind($t),{bigint:hrtimeBigint}),$t.uptime.bind($t),$t.memoryUsage.bind($t),$t.cpuUsage.bind($t),$t.kill.bind($t),$t.abort.bind($t),$t.umask.bind($t),$t.emitWarning.bind($t),rn=$t.execArgv,$t.config,an=$t.stdout,$t.stderr,on=$t.stdin});Be(),sn(),typeof Promise.withResolvers!=`function`&&(Promise.withResolvers=function(){let n,S;return{promise:new Promise((C,N)=>{n=C,S=N}),resolve:n,reject:S}}),initErrorV8Methods(Error),`global`in globalThis||Object.defineProperty(globalThis,"global",{value:globalThis,writable:!1,enumerable:!1,configurable:!0}),Object.defineProperty(globalThis,"process",{value:$t,enumerable:!1,writable:!0,configurable:!0}),Be(),typeof globalThis.structuredClone!=`function`&&Object.defineProperty(globalThis,"structuredClone",{value:structuredClone$1,enumerable:!0,writable:!0,configurable:!0});function getGLib(){return globalThis.imports?.gi?.GLib}const cn=getGLib()!==void 0;var GjsifyTimeout=class{_id=null;_refed=!0;_callback;_delay;_args;_repeat;constructor(n,S,C,N){this._callback=n,this._delay=S,this._args=C,this._repeat=N,this._schedule()}_schedule(){let n=getGLib();if(!n)return;let S=n.timeout_add.bind(n);this._id=S(n.PRIORITY_DEFAULT,this._delay,()=>{try{this._callback.apply(globalThis,this._args)}catch(n){setTimeout(()=>{throw n},0)}return this._repeat?n.SOURCE_CONTINUE:(this._id=null,n.SOURCE_REMOVE)})}ref(){return this._refed=!0,this}unref(){return this._refed=!1,this}hasRef(){return this._refed}refresh(){return this._cancel(),this._schedule(),this}_cancel(){this._id!==null&&(getGLib()?.Source.remove(this._id),this._id=null)}[Symbol.toPrimitive](){return this._id}[Symbol.dispose](){this._cancel()}};function removeById(n){n instanceof GjsifyTimeout?n._cancel():typeof n==`number`&&getGLib()?.Source.remove(n)}if(cn){let setT=(n,S=0,...C)=>new GjsifyTimeout(n,Math.max(0,S|0),C,!1),setI=(n,S=0,...C)=>new GjsifyTimeout(n,Math.max(0,S|0),C,!0),n=globalThis;n.setTimeout=setT,n.clearTimeout=removeById,n.setInterval=setI,n.clearInterval=removeById}function setImmediate$2(n,...S){return setTimeout(n,0,...S)}__name$1(setImmediate$2,`setImmediate`);function clearImmediate(n){clearTimeout(n)}`setImmediate`in globalThis||Object.defineProperty(globalThis,"setImmediate",{value:setImmediate$2,enumerable:!0,writable:!0,configurable:!0}),`clearImmediate`in globalThis||Object.defineProperty(globalThis,"clearImmediate",{value:clearImmediate,enumerable:!0,writable:!0,configurable:!0});var ln=__exportAll$4({URL:()=>mn,URLSearchParams:()=>fn,default:()=>hn,domainToASCII:()=>domainToASCII,domainToUnicode:()=>domainToUnicode,fileURLToPath:()=>fileURLToPath,format:()=>format$4,parse:()=>parse$4,pathToFileURL:()=>pathToFileURL,resolve:()=>resolve$4});function platformOrShapeIsWindows(n){return hostOs()===void 0?isWindowsPath(n):isWin32()}function decodeComponent(n){try{return decodeURIComponent(n.replace(/\+/g,` `))}catch{return n}}function percentEncodeUtf8(n){let S=``;for(let C of new TextEncoder().encode(n))S+=`%${C.toString(16).toUpperCase().padStart(2,`0`)}`;return S}function encodeComponent(n){let S=``;for(let C of n)C===` `?S+=`+`:/^[A-Za-z0-9*\-._]$/.test(C)?S+=C:S+=percentEncodeUtf8(C);return S}function encodeQuery(n,S){let C=``;for(let N of n){let n=N.codePointAt(0);C+=n<=32||n>126||N===`"`||N===`#`||N===`<`||N===`>`||S&&N===`'`?percentEncodeUtf8(N):N}return C}function parse$4(n,S,C){if(typeof n!=`string`)throw TypeError(`The "url" argument must be of type string. Received type `+typeof n);let N={protocol:null,slashes:null,auth:null,host:null,port:null,hostname:null,hash:null,search:null,query:null,pathname:null,path:null,href:n},F=n.trim(),I=F.indexOf(`#`);I!==-1&&(N.hash=F.slice(I),F=F.slice(0,I));let H=F.indexOf(`?`);H!==-1&&(N.search=F.slice(H),N.query=S?Object.fromEntries(new fn(F.slice(H+1))):F.slice(H+1),F=F.slice(0,H));let W=/^([a-z][a-z0-9.+-]*:)/i.exec(F);if(W&&(N.protocol=W[1].toLowerCase(),F=F.slice(N.protocol.length)),(C||N.protocol)&&F.startsWith(`//`)&&(N.slashes=!0,F=F.slice(2)),N.slashes||N.protocol&&![`javascript:`,`data:`,`mailto:`].includes(N.protocol)){let n=-1;for(let S=0;S<F.length;S++){let C=F[S];if(C===`/`||C===`\\`){n=S;break}}let S=n===-1?F:F.slice(0,n);F=n===-1?``:F.slice(n);let C=S.lastIndexOf(`@`);C===-1?parseHostPort(S,N):(N.auth=decodeURIComponent(S.slice(0,C)),parseHostPort(S.slice(C+1),N))}return N.pathname=F||(N.slashes?`/`:null),(N.pathname!==null||N.search!==null)&&(N.path=(N.pathname||``)+(N.search||``)),N.href=format$4(N),N}function parseHostPort(n,S){if(!n)return;let C=n.indexOf(`[`);if(C!==-1){let N=n.indexOf(`]`,C);if(N!==-1){let F=n.slice(N+1);F.startsWith(`:`)&&(S.port=F.slice(1)),S.hostname=n.slice(C,N+1),S.host=S.hostname+(S.port?`:`+S.port:``);return}}let N=n.lastIndexOf(`:`);if(N!==-1){let C=n.slice(N+1);/^\d*$/.test(C)?(S.port=C||null,S.hostname=n.slice(0,N).toLowerCase()):S.hostname=n.toLowerCase()}else S.hostname=n.toLowerCase();S.host=S.hostname+(S.port?`:`+S.port:``)}function format$4(n){if(typeof n==`string`)return n;if(n instanceof mn)return n.href;let S=n,C=``;if(S.protocol&&(C+=S.protocol),(S.slashes||S.protocol&&![`javascript:`,`data:`,`mailto:`].includes(S.protocol||``))&&(C+=`//`),S.auth&&(C+=encodeURIComponent(S.auth)+`@`),S.host?C+=S.host:(S.hostname&&(C+=S.hostname),S.port&&(C+=`:`+S.port)),S.pathname&&(C+=S.pathname),S.search)C+=S.search;else if(S.query&&typeof S.query==`object`){let n=new fn(S.query).toString();n&&(C+=`?`+n)}return S.hash&&(C+=S.hash),C}function resolve$4(n,S){return new mn(S,new mn(n,`resolve://`)).href.replace(/^resolve:\/\//,``)}function fileURLToPath(n,S){if(typeof n==`string`&&(n=new mn(n)),!(n instanceof mn))throw TypeError(`The "url" argument must be of type string or URL. Received type `+typeof n);if(n.protocol!==`file:`)throw TypeError(`The URL must be of scheme file`);let C=n.pathname,N=S?.windows??platformOrShapeIsWindows(C.slice(1));for(let n=0;n<C.length;n++){if(C[n]!==`%`)continue;let S=C.codePointAt(n+2)|32,F=C[n+1]===`2`&&S===102,I=C[n+1]===`5`&&S===99;if(N&&(F||I))throw TypeError(`File URL path must not include encoded \\ or / characters`);if(F)throw TypeError(`File URL path must not include encoded / characters`)}if(n.hostname!==``&&n.hostname!==`localhost`){if(!N)throw TypeError(`File URL host must be "localhost" or empty on ${hostOs()??`this platform`}`);return`\\\\${n.hostname}${decodeURIComponent(C).replace(/\//g,`\\`)}`}if(N){let n=decodeURIComponent(C);return/^\/[A-Za-z]:/.test(n)?n.slice(1).replace(/\//g,`\\`):n.replace(/\//g,`\\`)}return decodeURIComponent(C)}function pathToFileURL(n,S){let C=S?.windows??platformOrShapeIsWindows(n),N=n;return C&&isWindowsPath(n)||n.startsWith(`/`)||(typeof globalThis.process?.cwd==`function`?N=globalThis.process.cwd()+`/`+n:ft?.get_current_dir&&(N=ft.get_current_dir()+`/`+n)),new mn(pathToFileUrlHref(N,{windows:C}))}function domainToASCII(n){try{return new mn(`http://${n}`).hostname}catch{return``}}function domainToUnicode(n){try{return new mn(`http://${n}`).hostname}catch{return``}}var un,dn,fn,pn,mn,hn,gn=__esmMin(()=>{pt(),Be(),un=ft.UriFlags.HAS_PASSWORD|ft.UriFlags.ENCODED|ft.UriFlags.SCHEME_NORMALIZE,dn=new WeakMap,fn=class URLSearchParams{_entries=[];constructor(n){if(n)if(typeof n==`string`){let S=n.startsWith(`?`)?n.slice(1):n;if(S)for(let n of S.split(`&`)){if(n===``)continue;let S=n.indexOf(`=`);S===-1?this._entries.push([decodeComponent(n),``]):this._entries.push([decodeComponent(n.slice(0,S)),decodeComponent(n.slice(S+1))])}}else if(Array.isArray(n))for(let[S,C]of n)this._entries.push([String(S),String(C)]);else if(n instanceof URLSearchParams)this._entries=n._entries.map(([n,S])=>[n,S]);else for(let S of Object.keys(n))this._entries.push([S,String(n[S])])}get(n){for(let[S,C]of this._entries)if(S===n)return C;return null}getAll(n){return this._entries.filter(([S])=>S===n).map(([,n])=>n)}set(n,S){let C=!1;if(this._entries=this._entries.filter(([S])=>S===n?C?!1:(C=!0,!0):!0),C){for(let C=0;C<this._entries.length;C++)if(this._entries[C][0]===n){this._entries[C][1]=S;break}}else this._entries.push([n,S]);dn.get(this)?.()}has(n,S){return S===void 0?this._entries.some(([S])=>S===n):this._entries.some(([C,N])=>C===n&&N===S)}delete(n,S){this._entries=S===void 0?this._entries.filter(([S])=>S!==n):this._entries.filter(([C,N])=>!(C===n&&N===S)),dn.get(this)?.()}append(n,S){this._entries.push([n,S]),dn.get(this)?.()}sort(){this._entries.sort((n,S)=>n[0]<S[0]?-1:+(n[0]>S[0])),dn.get(this)?.()}toString(){return this._entries.map(([n,S])=>encodeComponent(n)+`=`+encodeComponent(S)).join(`&`)}forEach(n){for(let[S,C]of this._entries)n(C,S,this)}*entries(){yield*this._entries}*keys(){for(let[n]of this._entries)yield n}*values(){for(let[,n]of this._entries)yield n}[Symbol.iterator](){return this.entries()}get size(){return this._entries.length}},pn=new Set([`http:`,`https:`,`ws:`,`wss:`,`ftp:`,`file:`]),mn=class URL{#e;#t;#n;constructor(n,S){let C=n instanceof URL?n.href:String(n);try{if(S!==void 0){let n=S instanceof URL?S.href:String(S),N=ft.Uri.parse(n,un);this.#e=N.parse_relative(C,un)}else this.#e=ft.Uri.parse(C,un)}catch{throw TypeError(`Invalid URL: ${C}`)}if(!this.#e)throw TypeError(`Invalid URL: ${C}`);this.#n=this.#e.get_query()??null,this.#t=new fn(this.#n||``),dn.set(this.#t,()=>{let n=this.#t.toString();this.#n=n===``?null:n})}get protocol(){return this.#e.get_scheme()+`:`}get hostname(){return(this.#e.get_host()||``).toLowerCase()}get port(){let n=this.#e.get_port();if(n===-1)return``;let S=this.#e.get_scheme();return(S===`http`||S===`ws`)&&n===80||(S===`https`||S===`wss`)&&n===443||S===`ftp`&&n===21?``:String(n)}get host(){let n=this.hostname,S=this.port;return S?`${n}:${S}`:n}get pathname(){return this.#e.get_path()||`/`}get search(){return this.#n?`?`+this.#n:``}set search(n){let S=String(n).replace(/[\t\n\r]/g,``);if(S===``){this.#n=null,this.#t._entries=[];return}let C=S.startsWith(`?`)?S.slice(1):S;this.#n=encodeQuery(C,pn.has(this.protocol)),this.#t._entries=new fn(C)._entries}get hash(){let n=this.#e.get_fragment();return n?`#`+n:``}get origin(){let n=this.protocol;return n===`http:`||n===`https:`||n===`ftp:`?`${n}//${this.host}`:`null`}get username(){return this.#e.get_user()||``}get password(){return this.#e.get_password()||``}get href(){let n=this.protocol,S=this.#e.get_scheme();(S===`http`||S===`https`||S===`ftp`||S===`file`||S===`ws`||S===`wss`||this.hostname)&&(n+=`//`);let C=this.username,N=this.password;C&&(n+=C,N&&(n+=`:`+N),n+=`@`),n+=this.hostname,this.port&&(n+=`:`+this.port);let F=this.pathname;return n+=F,n+=this.#n===null?``:`?${this.#n}`,n+=this.hash,n}get searchParams(){return this.#t}toString(){return this.href}toJSON(){return this.href}static _objectURLPaths=new Map;static _objectURLCounter=0;static createObjectURL(n){let S=n?._tmpPath;if(typeof S==`string`&&S.length>0){let n=`file://${S}`;return URL._objectURLPaths.set(n,S),n}return`file:///dev/null`}static revokeObjectURL(n){let S=URL._objectURLPaths.get(n);S&&(ft.unlink(S),URL._objectURLPaths.delete(n))}},__name$1(parse$4,`parse`),__name$1(format$4,`format`),__name$1(resolve$4,`resolve`),hn={URL:mn,URLSearchParams:fn,parse:parse$4,format:format$4,resolve:resolve$4,fileURLToPath,pathToFileURL,domainToASCII,domainToUnicode}});gn(),typeof globalThis.URL!=`function`&&Object.defineProperty(globalThis,"URL",{value:mn,enumerable:!1,writable:!0,configurable:!0}),typeof globalThis.URLSearchParams!=`function`&&Object.defineProperty(globalThis,"URLSearchParams",{value:fn,enumerable:!1,writable:!0,configurable:!0});var _n=__exportAll$4({PerformanceEntry:()=>xn,PerformanceMark:()=>Cn,PerformanceMeasure:()=>wn,PerformanceObserver:()=>bn,PerformanceObserverEntryList:()=>Sn,default:()=>Tn,eventLoopUtilization:()=>eventLoopUtilization,monitorEventLoopDelay:()=>monitorEventLoopDelay,performance:()=>vn,timerify:()=>timerify});function eventLoopUtilization(n,S){return{idle:0,active:0,utilization:0}}function timerify(n){let wrapped=function(...S){let C=vn.now(),N=n.apply(this,S);return vn.now()-C,N};return Object.defineProperty(wrapped,"name",{value:n.name}),wrapped}function monitorEventLoopDelay(n){let S=new Map;return{enable(){},disable(){},reset(){},percentile(n){return 0},get min(){return 0},get max(){return 0},get mean(){return 0},get stddev(){return 0},get percentiles(){return S}}}var vn,PerformanceObserverStub,PerformanceEntryStub,PerformanceObserverEntryListStub,yn,bn,xn,Sn,Cn,wn,Tn,En=__esmMin(()=>{if(globalThis.performance)vn=globalThis.performance;else{let n,_now;try{let S=globalThis.imports?.gi?.GLib;if(!S)throw Error(`GJS imports.gi.GLib not available`);n=S.get_monotonic_time(),_now=()=>(S.get_monotonic_time()-n)/1e3}catch{let S=Date.now();n=0,_now=()=>Date.now()-S}let S=[],C=Date.now()-_now();vn={timeOrigin:C,now:_now,mark(n){let C={name:n,entryType:`mark`,startTime:_now(),duration:0};return S.push(C),C},measure(n,C,N){let F=0,I=_now();if(C){let n=S.find(n=>n.entryType===`mark`&&n.name===C);n&&(F=n.startTime)}if(N){let n=S.find(n=>n.entryType===`mark`&&n.name===N);n&&(I=n.startTime)}let H={name:n,entryType:`measure`,startTime:F,duration:I-F};return S.push(H),H},getEntries(){return[...S]},getEntriesByName(n){return S.filter(S=>S.name===n)},getEntriesByType(n){return S.filter(S=>S.entryType===n)},clearMarks(n){for(let C=S.length-1;C>=0;C--)S[C].entryType===`mark`&&(!n||S[C].name===n)&&S.splice(C,1)},clearMeasures(n){for(let C=S.length-1;C>=0;C--)S[C].entryType===`measure`&&(!n||S[C].name===n)&&S.splice(C,1)},clearResourceTimings(){},setResourceTimingBufferSize(){},toJSON(){return{timeOrigin:C}}}}PerformanceObserverStub=class{_callback;constructor(n){this._callback=n}observe(n){}disconnect(){}takeRecords(){return[]}},PerformanceEntryStub=class{name=``;entryType=``;startTime=0;duration=0;toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration}}},PerformanceObserverEntryListStub=class{getEntries(){return[]}getEntriesByName(n){return[]}getEntriesByType(n){return[]}},yn=globalThis,bn=yn.PerformanceObserver||PerformanceObserverStub,xn=yn.PerformanceEntry||PerformanceEntryStub,Sn=yn.PerformanceObserverEntryList||PerformanceObserverEntryListStub,Cn=yn.PerformanceMark||class PerformanceMark extends PerformanceEntryStub{},wn=yn.PerformanceMeasure||class PerformanceMeasure extends PerformanceEntryStub{},Tn={performance:vn,PerformanceObserver:bn,PerformanceEntry:xn,PerformanceObserverEntryList:Sn,PerformanceMark:Cn,PerformanceMeasure:wn,eventLoopUtilization,timerify,monitorEventLoopDelay}});En();const Dn=globalThis;globalThis.performance===void 0&&(Dn.performance=vn),typeof Dn.PerformanceObserver!=`function`&&(Dn.PerformanceObserver=bn);const $={IndexSizeError:1,HierarchyRequestError:3,WrongDocumentError:4,InvalidCharacterError:5,NoModificationAllowedError:7,NotFoundError:8,NotSupportedError:9,InUseAttributeError:10,InvalidStateError:11,SyntaxError:12,InvalidModificationError:13,NamespaceError:14,InvalidAccessError:15,TypeMismatchError:17,SecurityError:18,NetworkError:19,AbortError:20,URLMismatchError:21,QuotaExceededError:22,TimeoutError:23,InvalidNodeTypeError:24,DataCloneError:25};var _DOMExceptionPolyfill=class extends Error{code;constructor(n,S){super(n),this.name=S||`Error`,this.code=Object.hasOwn($,this.name)?$[this.name]:0}};const On=globalThis.DOMException===void 0?_DOMExceptionPolyfill:globalThis.DOMException;ye();const kn=Symbol(`type`),An=Symbol(`bubbles`),jn=Symbol(`cancelable`),Mn=Symbol(`composed`),Nn=Symbol(`target`),Pn=Symbol(`currentTarget`),Fn=Symbol(`eventPhase`),In=Symbol(`defaultPrevented`),Ln=Symbol(`isTrusted`),Rn=Symbol(`timeStamp`),zn=Symbol(`stop`),Bn=Symbol(`immediateStop`),Vn=Symbol(`dispatching`),Hn=Symbol(`inPassiveListener`);var Event=class{[kn];[An];[jn];[Mn];[Nn]=null;[Pn]=null;[Fn]=0;[In]=!1;[Ln]=!1;[Rn];[zn]=!1;[Bn]=!1;[Vn]=!1;[Hn]=!1;get type(){return this[kn]}get bubbles(){return this[An]}get cancelable(){return this[jn]}get composed(){return this[Mn]}get target(){return this[Nn]}get currentTarget(){return this[Pn]}get eventPhase(){return this[Fn]}get defaultPrevented(){return this[In]}get timeStamp(){return this[Rn]}get cancelBubble(){return this[zn]}set cancelBubble(n){n&&this.stopPropagation()}get returnValue(){return!this[In]}set returnValue(n){n||this.preventDefault()}get srcElement(){return this[Nn]}static NONE=0;static CAPTURING_PHASE=1;static AT_TARGET=2;static BUBBLING_PHASE=3;get[Symbol.toStringTag](){return`Event`}constructor(n,S){this[kn]=n,this[An]=S?.bubbles??!1,this[jn]=S?.cancelable??!1,this[Mn]=S?.composed??!1,this[Rn]=Date.now(),Object.defineProperty(this,"isTrusted",{get:()=>this[Ln],enumerable:!0,configurable:!1})}composedPath(){return this[Pn]?[this[Pn]]:[]}preventDefault(){this[jn]&&!this[Hn]&&(this[In]=!0)}stopPropagation(){this[zn]=!0}stopImmediatePropagation(){this[zn]=!0,this[Bn]=!0}},EventTarget=class{#e=new Map;get[Symbol.toStringTag](){return`EventTarget`}addEventListener(n,S,C){if(S===null)return;let N=typeof C==`boolean`?C:C?.capture??!1,F=typeof C==`object`?C?.once??!1:!1,I=typeof C==`object`?C?.passive??!1:!1,H=this.#e.get(n);H||(H=[],this.#e.set(n,H));for(let n of H)if(n.listener===S&&n.capture===N)return;let W={listener:S,capture:N,once:F,passive:I,removed:!1};H.push(W),typeof C==`object`&&C?.signal&&C.signal.addEventListener(`abort`,()=>{this.removeEventListener(n,S,{capture:N})},{once:!0})}removeEventListener(n,S,C){if(S===null)return;let N=typeof C==`boolean`?C:C?.capture??!1,F=this.#e.get(n);if(!F)return;let I=F.findIndex(n=>n.listener===S&&n.capture===N);I!==-1&&(F[I].removed=!0,F.splice(I,1),F.length===0&&this.#e.delete(n))}dispatchEvent(n){let S=n;if(S[Vn])throw new On(`The event is already being dispatched.`,`InvalidStateError`);S[Vn]=!0,S[Nn]=this,S[Pn]=this,S[Fn]=Event.AT_TARGET;try{let C=this.#e.get(n.type);if(C){let N=[...C];for(let C of N)if(!C.removed){if(S[Bn]||S[zn])break;C.once&&this.removeEventListener(n.type,C.listener,{capture:C.capture});try{C.passive&&(S[Hn]=!0),typeof C.listener==`function`?C.listener.call(this,n):typeof C.listener.handleEvent==`function`&&C.listener.handleEvent.call(C.listener,n)}catch(n){reportListenerException(n)}finally{S[Hn]=!1}}}}finally{S[Fn]=Event.NONE,S[Pn]=null,S[Vn]=!1}return!n.defaultPrevented}};function reportListenerException(n){try{let S=globalThis;if(typeof S.reportError==`function`)S.reportError(n);else if(n instanceof Error){let S=`${n.name}: ${n.message}`;ve.error(n.stack?`${S}\n${n.stack}`:S)}else ve.error(String(n))}catch{}}for(let[n,S]of[[`NONE`,0],[`CAPTURING_PHASE`,1],[`AT_TARGET`,2],[`BUBBLING_PHASE`,3]])Object.defineProperty(Event.prototype,n,{value:S,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(Event,n,{value:S,writable:!1,enumerable:!0,configurable:!1});const Un=Symbol(`abort`),Wn=Symbol(`internal`);var Gn=class AbortSignal extends EventTarget{#e=!1;#t=void 0;onabort=null;constructor(n){if(super(),n!==Wn)throw TypeError(`Illegal constructor.`)}get aborted(){if(!(this instanceof AbortSignal))throw TypeError(`'get aborted' called on an object that is not a valid instance of AbortSignal.`);return this.#e}get reason(){return this.#t}get[Symbol.toStringTag](){return`AbortSignal`}throwIfAborted(){if(this.#e)throw this.#t}[Un](n){if(this.#e)return;this.#e=!0,this.#t=n??new On(`The operation was aborted.`,`AbortError`);let S=new Event(`abort`);typeof this.onabort==`function`&&this.onabort.call(this,S),this.dispatchEvent(S)}static abort(n){let S=new AbortSignal(Wn);return S[Un](n),S}static timeout(n){let S=new AbortSignal(Wn);return setTimeout(()=>{S[Un](new On(`The operation timed out.`,`TimeoutError`))},n),S}static any(n){let S=new AbortSignal(Wn);for(let C of n)if(C.aborted)return S[Un](C.reason),S;let onAbort=()=>{if(!S.aborted){let C=n.find(n=>n.aborted);S[Un](C?.reason)}};for(let S of n)S.addEventListener(`abort`,onAbort,{once:!0});return S}},Kn=class AbortController{signal;constructor(){this.signal=new Gn(Wn)}get[Symbol.toStringTag](){return`AbortController`}abort(n){if(!(this instanceof AbortController))throw TypeError(`'abort' called on an object that is not a valid instance of AbortController.`);this.signal[Un](n)}};const qn=globalThis;globalThis.AbortController===void 0&&(qn.AbortController=Kn),globalThis.AbortSignal===void 0&&(qn.AbortSignal=Gn);const Jn=Symbol(`kState`),Yn=Symbol(`kType`);function isBrandCheck(n){return S=>typeof S==`object`&&!!S&&S[Jn]!==void 0&&S[Yn]===n}function dequeueValue(n){let S=n[Jn].queue.shift();if(S===void 0)throw Error(`dequeueValue called on an empty queue`);let{value:C,size:N}=S;return n[Jn].queueTotalSize=Math.max(0,n[Jn].queueTotalSize-N),C}function resetQueue(n){n[Jn].queue=[],n[Jn].queueTotalSize=0}function peekQueueValue(n){return n[Jn].queue[0].value}function enqueueValueWithSize(n,S,C){if(C=+C,typeof C!=`number`||C<0||Number.isNaN(C)||C===1/0)throw RangeError(`Invalid size: ${C}`);n[Jn].queue.push({value:S,size:C}),n[Jn].queueTotalSize+=C}function extractHighWaterMark(n,S){if(n===void 0)return S;if(n=+n,typeof n!=`number`||Number.isNaN(n)||n<0)throw RangeError(`Invalid highWaterMark: ${n}`);return n}function extractSizeAlgorithm(n){if(n===void 0)return()=>1;if(typeof n!=`function`)throw TypeError(`strategy.size must be a function`);return n}function transferArrayBuffer(n){return typeof ArrayBuffer.prototype.transfer==`function`?n.transfer():n.slice(0)}function isDetachedBuffer(n){if(typeof SharedArrayBuffer<`u`&&n instanceof SharedArrayBuffer||n.byteLength!==0)return!1;try{return n.slice(0,0),!1}catch{return!0}}function typedArrayConstructorByTag(n){switch(n){case`Int8Array`:return Int8Array;case`Uint8Array`:return Uint8Array;case`Uint8ClampedArray`:return Uint8ClampedArray;case`Int16Array`:return Int16Array;case`Uint16Array`:return Uint16Array;case`Int32Array`:return Int32Array;case`Uint32Array`:return Uint32Array;case`Float32Array`:return Float32Array;case`Float64Array`:return Float64Array;case`BigInt64Array`:return typeof BigInt64Array<`u`?BigInt64Array:void 0;case`BigUint64Array`:return typeof BigUint64Array<`u`?BigUint64Array:void 0;default:return}}function elementSizeByTag(n){switch(n){case`Int8Array`:case`Uint8Array`:case`Uint8ClampedArray`:return 1;case`Int16Array`:case`Uint16Array`:return 2;case`Int32Array`:case`Uint32Array`:case`Float32Array`:return 4;case`Float64Array`:case`BigInt64Array`:case`BigUint64Array`:return 8;default:return 1}}function setPromiseHandled(n){n.then(()=>{},()=>{})}function createPromiseCallback(n,S,C){if(typeof S!=`function`)throw TypeError(`${n} must be a function`);return async(...n)=>S.call(C,...n)}async function nonOpFlush(){}function nonOpStart(){}async function nonOpPull(){}async function nonOpCancel(){}async function nonOpWrite(){}const Xn={__proto__:Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),next:void 0,return:void 0};function createAsyncFromSyncIterator(n){let S={[Symbol.iterator]:()=>n.iterator},C=(async function*(){return yield*S})();return{iterator:C,nextMethod:C.next,done:!1}}function getIterator(n,S=`sync`,C){if(C===void 0)if(S===`async`){if(C=n[Symbol.asyncIterator],C==null){let S=n[Symbol.iterator];if(S===void 0)throw TypeError(`Object is not iterable`);return createAsyncFromSyncIterator(getIterator(n,`sync`,S))}}else C=n[Symbol.iterator];if(C===void 0)throw TypeError(`Object is not iterable`);let N=C.call(n);if(typeof N!=`object`||!N)throw TypeError(`The iterator method must return an object`);return{iterator:N,nextMethod:N.next,done:!1}}function iteratorNext(n,S){let C;if(C=S===void 0?n.nextMethod.call(n.iterator):n.nextMethod.call(n.iterator,S),typeof C!=`object`||!C)throw TypeError(`The iterator.next() method must return an object`);return C}const Zn=typeof globalThis.AbortController==`function`?globalThis.AbortController:class AbortControllerShim{signal={aborted:!1,reason:void 0,addEventListener(){},removeEventListener(){}};abort(n){this.signal.aborted=!0,this.signal.reason=n}},Qn=Symbol(`kAbort`),$n=Symbol(`kCloseSentinel`),er=Symbol(`kError`),tr=Symbol(`kSkipThrow`);var WritableStream=class{[Yn]=`WritableStream`;[Jn];constructor(n={},S={}){if(n!=null&&typeof n!=`object`)throw TypeError(`sink must be an object`);if(S!=null&&typeof S!=`object`)throw TypeError(`strategy must be an object`);let C=n?.type;if(C!==void 0)throw RangeError(`Invalid type: ${C}`);this[Jn]=createWritableStreamState();let N=extractSizeAlgorithm(S?.size),F=extractHighWaterMark(S?.highWaterMark,1);setupWritableStreamDefaultControllerFromSink(this,n,F,N)}get locked(){if(!nr(this))throw TypeError(`Invalid this`);return isWritableStreamLocked(this)}abort(n){return nr(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamAbort(this,n):Promise.reject(TypeError(`Invalid this`))}close(){return nr(this)?isWritableStreamLocked(this)?Promise.reject(TypeError(`WritableStream is locked`)):writableStreamCloseQueuedOrInFlight(this)?Promise.reject(TypeError(`Failure closing WritableStream`)):writableStreamClose(this):Promise.reject(TypeError(`Invalid this`))}getWriter(){if(!nr(this))throw TypeError(`Invalid this`);return new WritableStreamDefaultWriter(this)}get[Symbol.toStringTag](){return`WritableStream`}},WritableStreamDefaultWriter=class{[Yn]=`WritableStreamDefaultWriter`;[Jn];constructor(n){if(!nr(n))throw TypeError(`Expected a WritableStream`);this[Jn]={stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0},ready:{promise:void 0,resolve:void 0,reject:void 0}},setupWritableStreamDefaultWriter(this,n)}get closed(){return rr(this)?this[Jn].close.promise:Promise.reject(TypeError(`Invalid this`))}get desiredSize(){if(!rr(this))throw TypeError(`Invalid this`);if(this[Jn].stream===void 0)throw TypeError(`Writer is not bound to a WritableStream`);return writableStreamDefaultWriterGetDesiredSize(this)}get ready(){return rr(this)?this[Jn].ready.promise:Promise.reject(TypeError(`Invalid this`))}abort(n){return rr(this)?this[Jn].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterAbort(this,n):Promise.reject(TypeError(`Invalid this`))}close(){if(!rr(this))return Promise.reject(TypeError(`Invalid this`));let{stream:n}=this[Jn];return n===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamCloseQueuedOrInFlight(n)?Promise.reject(TypeError(`Failure to close WritableStream`)):writableStreamDefaultWriterClose(this)}releaseLock(){if(!rr(this))throw TypeError(`Invalid this`);let{stream:n}=this[Jn];n!==void 0&&writableStreamDefaultWriterRelease(this)}write(n){return rr(this)?this[Jn].stream===void 0?Promise.reject(TypeError(`Writer is not bound to a WritableStream`)):writableStreamDefaultWriterWrite(this,n):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`WritableStreamDefaultWriter`}},WritableStreamDefaultController=class{[Yn]=`WritableStreamDefaultController`;[Jn];constructor(n){if(n!==tr)throw TypeError(`Illegal constructor`)}[Qn](n){let S=this[Jn].abortAlgorithm(n);return writableStreamDefaultControllerClearAlgorithms(this),S}[er](){resetQueue(this)}get signal(){if(!ir(this))throw TypeError(`Invalid this`);return this[Jn].abortController.signal}error(n){if(!ir(this))throw TypeError(`Invalid this`);this[Jn].stream[Jn].state===`writable`&&writableStreamDefaultControllerError(this,n)}get[Symbol.toStringTag](){return`WritableStreamDefaultController`}};const nr=isBrandCheck(`WritableStream`),rr=isBrandCheck(`WritableStreamDefaultWriter`),ir=isBrandCheck(`WritableStreamDefaultController`);function createEmptyPromiseRecord(){return{promise:void 0,resolve:void 0,reject:void 0}}function createWritableStreamState(){return{close:Promise.withResolvers(),closeRequest:createEmptyPromiseRecord(),inFlightWriteRequest:createEmptyPromiseRecord(),inFlightCloseRequest:createEmptyPromiseRecord(),pendingAbortRequest:{abort:createEmptyPromiseRecord(),reason:void 0,wasAlreadyErroring:!1},backpressure:!1,controller:void 0,state:`writable`,storedError:void 0,writeRequests:[],writer:void 0}}function isWritableStreamLocked(n){return n[Jn].writer!==void 0}function setupWritableStreamDefaultWriter(n,S){if(isWritableStreamLocked(S))throw TypeError(`WritableStream is locked`);switch(n[Jn].stream=S,S[Jn].writer=n,S[Jn].state){case`writable`:!writableStreamCloseQueuedOrInFlight(S)&&S[Jn].backpressure?n[Jn].ready=Promise.withResolvers():n[Jn].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},n[Jn].close=Promise.withResolvers();break;case`erroring`:n[Jn].ready={promise:Promise.reject(S[Jn].storedError),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].ready.promise),n[Jn].close=Promise.withResolvers();break;case`closed`:n[Jn].ready={promise:Promise.resolve(),resolve:void 0,reject:void 0},n[Jn].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;default:n[Jn].ready={promise:Promise.reject(S[Jn].storedError),resolve:void 0,reject:void 0},n[Jn].close={promise:Promise.reject(S[Jn].storedError),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].ready.promise),setPromiseHandled(n[Jn].close.promise)}}function writableStreamAbort(n,S){let{state:C,controller:N}=n[Jn];if(C===`closed`||C===`errored`)return Promise.resolve();if(N[Jn].abortController.abort(S),n[Jn].pendingAbortRequest.abort.promise!==void 0)return n[Jn].pendingAbortRequest.abort.promise;let F=!1;C===`erroring`&&(F=!0,S=void 0);let I=Promise.withResolvers();return n[Jn].pendingAbortRequest={abort:I,reason:S,wasAlreadyErroring:F},F||writableStreamStartErroring(n,S),I.promise}function writableStreamClose(n){let{state:S,writer:C,backpressure:N,controller:F}=n[Jn];if(S===`closed`||S===`errored`)return Promise.reject(TypeError(`WritableStream is closed`));n[Jn].closeRequest=Promise.withResolvers();let{promise:I}=n[Jn].closeRequest;return C!==void 0&&N&&S===`writable`&&C[Jn].ready.resolve?.(),writableStreamDefaultControllerClose(F),I}function writableStreamUpdateBackpressure(n,S){let{writer:C}=n[Jn];C!==void 0&&n[Jn].backpressure!==S&&(S?C[Jn].ready=Promise.withResolvers():C[Jn].ready.resolve?.()),n[Jn].backpressure=S}function writableStreamStartErroring(n,S){let{controller:C,writer:N}=n[Jn];n[Jn].state=`erroring`,n[Jn].storedError=S,N!==void 0&&writableStreamDefaultWriterEnsureReadyPromiseRejected(N,S),!writableStreamHasOperationMarkedInFlight(n)&&C[Jn].started&&writableStreamFinishErroring(n)}function writableStreamRejectCloseAndClosedPromiseIfNeeded(n){n[Jn].closeRequest.promise!==void 0&&(n[Jn].closeRequest.reject?.(n[Jn].storedError),n[Jn].closeRequest={promise:void 0,resolve:void 0,reject:void 0}),setPromiseHandled(n[Jn].close.promise),n[Jn].close.reject?.(n[Jn].storedError);let{writer:S}=n[Jn];S!==void 0&&(setPromiseHandled(S[Jn].close.promise),S[Jn].close.reject?.(n[Jn].storedError))}function writableStreamMarkFirstWriteRequestInFlight(n){let S=n[Jn].writeRequests.shift();n[Jn].inFlightWriteRequest=S}function writableStreamMarkCloseRequestInFlight(n){n[Jn].inFlightCloseRequest=n[Jn].closeRequest,n[Jn].closeRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamHasOperationMarkedInFlight(n){return n[Jn].inFlightWriteRequest.promise!==void 0||n[Jn].inFlightCloseRequest.promise!==void 0}function writableStreamFinishInFlightWriteWithError(n,S){n[Jn].inFlightWriteRequest.reject?.(S),n[Jn].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0},writableStreamDealWithRejection(n,S)}function writableStreamFinishInFlightWrite(n){n[Jn].inFlightWriteRequest.resolve?.(),n[Jn].inFlightWriteRequest={promise:void 0,resolve:void 0,reject:void 0}}function writableStreamFinishInFlightCloseWithError(n,S){n[Jn].inFlightCloseRequest.reject?.(S),n[Jn].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},n[Jn].pendingAbortRequest.abort.promise!==void 0&&(n[Jn].pendingAbortRequest.abort.reject?.(S),n[Jn].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1}),writableStreamDealWithRejection(n,S)}function writableStreamFinishInFlightClose(n){n[Jn].inFlightCloseRequest.resolve?.(),n[Jn].inFlightCloseRequest={promise:void 0,resolve:void 0,reject:void 0},n[Jn].state===`erroring`&&(n[Jn].storedError=void 0,n[Jn].pendingAbortRequest.abort.promise!==void 0&&(n[Jn].pendingAbortRequest.abort.resolve?.(),n[Jn].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1})),n[Jn].state=`closed`,n[Jn].writer!==void 0&&n[Jn].writer[Jn].close.resolve?.(),n[Jn].close.resolve?.()}function writableStreamFinishErroring(n){n[Jn].state=`errored`,n[Jn].controller[er]();let S=n[Jn].storedError;for(let C of n[Jn].writeRequests)C.reject?.(S);if(n[Jn].writeRequests=[],n[Jn].pendingAbortRequest.abort.promise===void 0){writableStreamRejectCloseAndClosedPromiseIfNeeded(n);return}let C=n[Jn].pendingAbortRequest;if(n[Jn].pendingAbortRequest={abort:{promise:void 0,resolve:void 0,reject:void 0},reason:void 0,wasAlreadyErroring:!1},C.wasAlreadyErroring){C.abort.reject?.(S),writableStreamRejectCloseAndClosedPromiseIfNeeded(n);return}n[Jn].controller[Qn](C.reason).then(()=>{C.abort.resolve?.(),writableStreamRejectCloseAndClosedPromiseIfNeeded(n)},S=>{C.abort.reject?.(S),writableStreamRejectCloseAndClosedPromiseIfNeeded(n)})}function writableStreamDealWithRejection(n,S){if(n[Jn].state===`writable`){writableStreamStartErroring(n,S);return}writableStreamFinishErroring(n)}function writableStreamCloseQueuedOrInFlight(n){return n[Jn].closeRequest.promise!==void 0||n[Jn].inFlightCloseRequest.promise!==void 0}function writableStreamAddWriteRequest(n){let{promise:S,resolve:C,reject:N}=Promise.withResolvers();return n[Jn].writeRequests.push({promise:S,resolve:C,reject:N}),S}function writableStreamDefaultWriterWrite(n,S){let{stream:C}=n[Jn],{controller:N}=C[Jn],F=writableStreamDefaultControllerGetChunkSize(N,S);if(C!==n[Jn].stream)return Promise.reject(TypeError(`Mismatched WritableStreams`));let{state:I}=C[Jn];if(I===`errored`)return Promise.reject(C[Jn].storedError);if(writableStreamCloseQueuedOrInFlight(C)||I===`closed`)return Promise.reject(TypeError(`WritableStream is closed`));if(I===`erroring`)return Promise.reject(C[Jn].storedError);let H=writableStreamAddWriteRequest(C);return writableStreamDefaultControllerWrite(N,S,F),H}function writableStreamDefaultWriterRelease(n){let{stream:S}=n[Jn],C=TypeError(`Writer has been released`);writableStreamDefaultWriterEnsureReadyPromiseRejected(n,C),writableStreamDefaultWriterEnsureClosedPromiseRejected(n,C),S[Jn].writer=void 0,n[Jn].stream=void 0}function writableStreamDefaultWriterGetDesiredSize(n){let{stream:S}=n[Jn];switch(S[Jn].state){case`errored`:case`erroring`:return null;case`closed`:return 0}return writableStreamDefaultControllerGetDesiredSize(S[Jn].controller)}function writableStreamDefaultWriterEnsureReadyPromiseRejected(n,S){n[Jn].ready.reject?(n[Jn].ready.reject(S),n[Jn].ready.resolve=void 0,n[Jn].ready.reject=void 0):n[Jn].ready={promise:Promise.reject(S),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].ready.promise)}function writableStreamDefaultWriterEnsureClosedPromiseRejected(n,S){n[Jn].close.reject?(n[Jn].close.reject(S),n[Jn].close.resolve=void 0,n[Jn].close.reject=void 0):n[Jn].close={promise:Promise.reject(S),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].close.promise)}function writableStreamDefaultWriterCloseWithErrorPropagation(n){let{stream:S}=n[Jn],{state:C}=S[Jn];return writableStreamCloseQueuedOrInFlight(S)||C===`closed`?Promise.resolve():C===`errored`?Promise.reject(S[Jn].storedError):writableStreamDefaultWriterClose(n)}function writableStreamDefaultWriterClose(n){return writableStreamClose(n[Jn].stream)}function writableStreamDefaultWriterAbort(n,S){return writableStreamAbort(n[Jn].stream,S)}function writableStreamDefaultControllerWrite(n,S,C){try{enqueueValueWithSize(n,S,C)}catch(S){writableStreamDefaultControllerErrorIfNeeded(n,S);return}let{stream:N}=n[Jn];!writableStreamCloseQueuedOrInFlight(N)&&N[Jn].state===`writable`&&writableStreamUpdateBackpressure(N,writableStreamDefaultControllerGetBackpressure(n)),writableStreamDefaultControllerAdvanceQueueIfNeeded(n)}function writableStreamDefaultControllerProcessWrite(n,S){let{stream:C,writeAlgorithm:N}=n[Jn];writableStreamMarkFirstWriteRequestInFlight(C),N(S,n).then(()=>{writableStreamFinishInFlightWrite(C);let{state:S}=C[Jn];dequeueValue(n),!writableStreamCloseQueuedOrInFlight(C)&&S===`writable`&&writableStreamUpdateBackpressure(C,writableStreamDefaultControllerGetBackpressure(n)),writableStreamDefaultControllerAdvanceQueueIfNeeded(n)},S=>{C[Jn].state===`writable`&&writableStreamDefaultControllerClearAlgorithms(n),writableStreamFinishInFlightWriteWithError(C,S)})}function writableStreamDefaultControllerProcessClose(n){let{closeAlgorithm:S,stream:C}=n[Jn];writableStreamMarkCloseRequestInFlight(C),dequeueValue(n);let N=S();writableStreamDefaultControllerClearAlgorithms(n),N.then(()=>writableStreamFinishInFlightClose(C),n=>writableStreamFinishInFlightCloseWithError(C,n))}function writableStreamDefaultControllerGetDesiredSize(n){return n[Jn].highWaterMark-n[Jn].queueTotalSize}function writableStreamDefaultControllerGetChunkSize(n,S){let{sizeAlgorithm:C}=n[Jn];if(C===void 0)return 1;try{return C(S)}catch(S){return writableStreamDefaultControllerErrorIfNeeded(n,S),1}}function writableStreamDefaultControllerErrorIfNeeded(n,S){n[Jn].stream[Jn].state===`writable`&&writableStreamDefaultControllerError(n,S)}function writableStreamDefaultControllerError(n,S){writableStreamDefaultControllerClearAlgorithms(n),writableStreamStartErroring(n[Jn].stream,S)}function writableStreamDefaultControllerClose(n){enqueueValueWithSize(n,$n,0),writableStreamDefaultControllerAdvanceQueueIfNeeded(n)}function writableStreamDefaultControllerClearAlgorithms(n){n[Jn].writeAlgorithm=void 0,n[Jn].closeAlgorithm=void 0,n[Jn].abortAlgorithm=void 0,n[Jn].sizeAlgorithm=void 0}function writableStreamDefaultControllerGetBackpressure(n){return writableStreamDefaultControllerGetDesiredSize(n)<=0}function writableStreamDefaultControllerAdvanceQueueIfNeeded(n){let{queue:S,started:C,stream:N}=n[Jn];if(!C||N[Jn].inFlightWriteRequest.promise!==void 0)return;if(N[Jn].state===`erroring`){writableStreamFinishErroring(N);return}if(!S.length)return;let F=peekQueueValue(n);F===$n?writableStreamDefaultControllerProcessClose(n):writableStreamDefaultControllerProcessWrite(n,F)}function setupWritableStreamDefaultControllerFromSink(n,S,C,N){let F=new WritableStreamDefaultController(tr),I=S?.start,H=S?.write,W=S?.close,q=S?.abort;setupWritableStreamDefaultController(n,F,I?I.bind(S,F):nonOpStart,H?createPromiseCallback(`sink.write`,H,S):nonOpWrite,W?createPromiseCallback(`sink.close`,W,S):nonOpCancel,q?createPromiseCallback(`sink.abort`,q,S):nonOpCancel,C,N)}function setupWritableStreamDefaultController(n,S,C,N,F,I,H,W){S[Jn]={abortAlgorithm:I,closeAlgorithm:F,highWaterMark:H,queue:[],queueTotalSize:0,abortController:new Zn,sizeAlgorithm:W,started:!1,stream:n,writeAlgorithm:N},n[Jn].controller=S,writableStreamUpdateBackpressure(n,writableStreamDefaultControllerGetBackpressure(S));let q=C();new Promise(n=>n(q)).then(()=>{S[Jn].started=!0,writableStreamDefaultControllerAdvanceQueueIfNeeded(S)},C=>{S[Jn].started=!0,writableStreamDealWithRejection(n,C)})}function createWritableStream(n,S,C,N,F=1,I=()=>1){let H=Object.create(WritableStream.prototype);return H[Yn]=`WritableStream`,H[Jn]=createWritableStreamState(),setupWritableStreamDefaultController(H,new WritableStreamDefaultController(tr),n,S,C,N,F,I),H}Be();const ar=Symbol(`kCancel`),sr=Symbol(`kClose`),cr=Symbol(`kChunk`),lr=Symbol(`kError`),ur=Symbol(`kPull`),dr=Symbol(`kRelease`),fr=Symbol(`kSkipThrow`);let pr,mr;function lazyReadableReleasedError(){return pr||(pr=TypeError(`Reader released`),pr)}function lazyReadableReleasingError(){return mr||(mr=TypeError(`Releasing reader`),mr)}function createAbortError$1(){if(typeof globalThis.DOMException==`function`)return new DOMException(`The operation was aborted`,`AbortError`);let n=Error(`The operation was aborted`);return n.name=`AbortError`,n}__name$1(createAbortError$1,`createAbortError`);function createReadableStreamState(){return{disturbed:!1,reader:void 0,state:`readable`,storedError:void 0,controller:void 0,closedPromise:Promise.withResolvers()}}var ReadableStream$1=class{static{__name$1(this,`ReadableStream`)}[Yn]=`ReadableStream`;[Jn];constructor(n={},S={}){if(n!=null&&typeof n!=`object`)throw TypeError(`source must be an object`);if(S!=null&&typeof S!=`object`)throw TypeError(`strategy must be an object`);this[Jn]=createReadableStreamState();let C=S?.size,N=S?.highWaterMark,F=n?.type;if(F!==void 0){if(`${F}`==`bytes`){if(C!==void 0)throw RangeError(`strategy.size must not be set for a byte stream`);setupReadableByteStreamControllerFromSource(this,n,extractHighWaterMark(N,0));return}throw RangeError(`Invalid type: ${F}`)}setupReadableStreamDefaultControllerFromSource(this,n,extractHighWaterMark(N,1),extractSizeAlgorithm(C))}get locked(){if(!hr(this))throw TypeError(`Invalid this`);return isReadableStreamLocked(this)}static from(n){return readableStreamFromIterable(n)}cancel(n=void 0){return hr(this)?isReadableStreamLocked(this)?Promise.reject(TypeError(`ReadableStream is locked`)):readableStreamCancel(this,n):Promise.reject(TypeError(`Invalid this`))}getReader(n={}){if(!hr(this))throw TypeError(`Invalid this`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let S=n?.mode;if(S===void 0)return new ReadableStreamDefaultReader(this);if(`${S}`==`byob`)return new ReadableStreamBYOBReader(this);throw RangeError(`Invalid mode: ${S}`)}pipeThrough(n,S={}){if(!hr(this))throw TypeError(`Invalid this`);let C=n?.readable;if(!hr(C))throw TypeError(`transform.readable must be a ReadableStream`);let N=n?.writable;if(!nr(N))throw TypeError(`transform.writable must be a WritableStream`);if(S!=null&&typeof S!=`object`)throw TypeError(`options must be an object`);let F=S?.preventAbort,I=S?.preventCancel,H=S?.preventClose,W=S?.signal;if(W!==void 0&&!(W instanceof Object&&`aborted`in W))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(N))throw TypeError(`The WritableStream is locked`);return setPromiseHandled(readableStreamPipeTo(this,N,!!H,!!F,!!I,W)),C}pipeTo(n,S={}){try{if(!hr(this))throw TypeError(`Invalid this`);if(!nr(n))throw TypeError(`destination must be a WritableStream`);if(S!=null&&typeof S!=`object`)throw TypeError(`options must be an object`);let C=S?.preventAbort,N=S?.preventCancel,F=S?.preventClose,I=S?.signal;if(I!==void 0&&!(I instanceof Object&&`aborted`in I))throw TypeError(`options.signal must be an AbortSignal`);if(isReadableStreamLocked(this))throw TypeError(`The ReadableStream is locked`);if(isWritableStreamLocked(n))throw TypeError(`The WritableStream is locked`);return readableStreamPipeTo(this,n,!!F,!!C,!!N,I)}catch(n){return Promise.reject(n)}}tee(){if(!hr(this))throw TypeError(`Invalid this`);let n=this[Jn].controller;return vr(n)?readableByteStreamTee(this):readableStreamDefaultTee(this,!1)}values(n={}){if(!hr(this))throw TypeError(`Invalid this`);if(n!=null&&typeof n!=`object`)throw TypeError(`options must be an object`);let S=!!n?.preventCancel,C=new ReadableStreamDefaultReader(this),N={done:!1,current:void 0},F=!1;function nextSteps(){if(N.done)return Promise.resolve({done:!0,value:void 0});if(C[Jn].stream===void 0)return Promise.reject(TypeError(`The reader is not bound to a ReadableStream`));let{promise:n,resolve:S,reject:F}=Promise.withResolvers();return readableStreamDefaultReaderRead(C,{[cr](n){N.current=void 0,S({value:n,done:!1})},[sr](){N.current=void 0,N.done=!0,readableStreamReaderGenericRelease(C),S({done:!0,value:void 0})},[lr](n){N.current=void 0,N.done=!0,readableStreamReaderGenericRelease(C),F(n)}}),n}async function returnSteps(n){if(N.done)return{done:!0,value:n};if(N.done=!0,C[Jn].stream===void 0)throw TypeError(`The reader is not bound to a ReadableStream`);if(!S){let S=readableStreamReaderGenericCancel(C,n);return readableStreamReaderGenericRelease(C),await S,{done:!0,value:n}}return readableStreamReaderGenericRelease(C),{done:!0,value:n}}return Object.setPrototypeOf({next(){return F||=(N.current=Promise.resolve(),!0),N.current=N.current===void 0?nextSteps():N.current.then(nextSteps,nextSteps),N.current},return(n){return F=!0,N.current=N.current===void 0?returnSteps(n):N.current.then(()=>returnSteps(n),()=>returnSteps(n)),N.current},[Symbol.asyncIterator](){return this}},Xn)}[Symbol.asyncIterator](){return this.values()}get[Symbol.toStringTag](){return`ReadableStream`}},DefaultReadRequest=class{[Jn];constructor(){this[Jn]=Promise.withResolvers()}[cr](n){this[Jn].resolve?.({value:n,done:!1})}[sr](){this[Jn].resolve?.({value:void 0,done:!0})}[lr](n){this[Jn].reject?.(n)}get promise(){return this[Jn].promise}},ReadableStreamDefaultReader=class{[Yn]=`ReadableStreamDefaultReader`;[Jn];constructor(n){if(!hr(n))throw TypeError(`Expected a ReadableStream`);this[Jn]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamDefaultReader(this,n)}read(){if(!_r(this))return Promise.reject(TypeError(`Invalid this`));if(this[Jn].stream===void 0)return Promise.reject(TypeError(`The reader is not attached to a stream`));let n=this[Jn].stream,S=n[Jn].controller;if(n[Jn].state===`readable`&&gr(S)&&S[Jn].queue.length>0){n[Jn].disturbed=!0;let C=dequeueValue(S);return S[Jn].closeRequested&&!S[Jn].queue.length?(readableStreamDefaultControllerClearAlgorithms(S),readableStreamClose(n)):readableStreamDefaultControllerCallPullIfNeeded(S),Promise.resolve({value:C,done:!1})}let C=new DefaultReadRequest;return readableStreamDefaultReaderRead(this,C),C.promise}releaseLock(){if(!_r(this))throw TypeError(`Invalid this`);this[Jn].stream!==void 0&&readableStreamDefaultReaderRelease(this)}get closed(){return _r(this)?this[Jn].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(n=void 0){return _r(this)?this[Jn].stream===void 0?Promise.reject(TypeError(`The reader is not attached to a stream`)):readableStreamReaderGenericCancel(this,n):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamDefaultReader`}},ReadableStreamDefaultController=class{[Yn]=`ReadableStreamDefaultController`;[Jn];constructor(n){if(n!==fr)throw TypeError(`Illegal constructor`)}get desiredSize(){return readableStreamDefaultControllerGetDesiredSize(this)}close(){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerClose(this)}enqueue(n=void 0){if(!readableStreamDefaultControllerCanCloseOrEnqueue(this))throw TypeError(`Controller is already closed`);readableStreamDefaultControllerEnqueue(this,n)}error(n=void 0){readableStreamDefaultControllerError(this,n)}[ar](n){return readableStreamDefaultControllerCancelSteps(this,n)}[ur](n){readableStreamDefaultControllerPullSteps(this,n)}[dr](){}get[Symbol.toStringTag](){return`ReadableStreamDefaultController`}};const hr=isBrandCheck(`ReadableStream`),gr=isBrandCheck(`ReadableStreamDefaultController`),_r=isBrandCheck(`ReadableStreamDefaultReader`);function isReadableStreamLocked(n){return n[Jn].reader!==void 0}function readableStreamCancel(n,S){switch(n[Jn].disturbed=!0,n[Jn].state){case`closed`:return Promise.resolve();case`errored`:return Promise.reject(n[Jn].storedError)}readableStreamClose(n);let C=n[Jn].reader;if(C!==void 0&&readableStreamHasBYOBReader(n)){let n=C[Jn].readIntoRequests;C[Jn].readIntoRequests=[];for(let S=0;S<n.length;S++)n[S][sr](void 0)}return n[Jn].controller[ar](S).then(()=>{})}function readableStreamClose(n){n[Jn].state=`closed`,n[Jn].closedPromise.resolve();let{reader:S}=n[Jn];if(S!==void 0&&(S[Jn].close.resolve?.(),readableStreamHasDefaultReader(n))){for(let n=0;n<S[Jn].readRequests.length;n++)S[Jn].readRequests[n][sr]();S[Jn].readRequests=[]}}function readableStreamError(n,S){n[Jn].state=`errored`,n[Jn].storedError=S,setPromiseHandled(n[Jn].closedPromise.promise),n[Jn].closedPromise.reject(S);let{reader:C}=n[Jn];if(C!==void 0){if(setPromiseHandled(C[Jn].close.promise),C[Jn].close.reject?.(S),readableStreamHasDefaultReader(n)){for(let n=0;n<C[Jn].readRequests.length;n++)C[Jn].readRequests[n][lr](S);C[Jn].readRequests=[]}else if(readableStreamHasBYOBReader(n)){for(let n=0;n<C[Jn].readIntoRequests.length;n++)C[Jn].readIntoRequests[n][lr](S);C[Jn].readIntoRequests=[]}}}function readableStreamHasDefaultReader(n){let{reader:S}=n[Jn];return S===void 0?!1:S[Jn]!==void 0&&S[Yn]===`ReadableStreamDefaultReader`}function readableStreamGetNumReadRequests(n){return n[Jn].reader[Jn].readRequests.length}function readableStreamFulfillReadRequest(n,S,C){let{reader:N}=n[Jn],F=N[Jn].readRequests.shift();C?F[sr]():F[cr](S)}function readableStreamAddReadRequest(n,S){n[Jn].reader[Jn].readRequests.push(S)}function readableStreamReaderGenericCancel(n,S){let{stream:C}=n[Jn];return readableStreamCancel(C,S)}function readableStreamReaderGenericInitialize(n,S){switch(n[Jn].stream=S,S[Jn].reader=n,S[Jn].state){case`readable`:n[Jn].close=Promise.withResolvers();break;case`closed`:n[Jn].close={promise:Promise.resolve(),resolve:void 0,reject:void 0};break;case`errored`:n[Jn].close={promise:Promise.reject(S[Jn].storedError),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].close.promise);break}}function readableStreamReaderGenericRelease(n){let{stream:S}=n[Jn],C=lazyReadableReleasedError();S[Jn].state===`readable`?n[Jn].close.reject?.(C):n[Jn].close={promise:Promise.reject(C),resolve:void 0,reject:void 0},setPromiseHandled(n[Jn].close.promise),S[Jn].controller[dr](),S[Jn].reader=void 0,n[Jn].stream=void 0}function readableStreamDefaultReaderRelease(n){readableStreamReaderGenericRelease(n),readableStreamDefaultReaderErrorReadRequests(n,lazyReadableReleasingError())}function readableStreamDefaultReaderErrorReadRequests(n,S){for(let C=0;C<n[Jn].readRequests.length;++C)n[Jn].readRequests[C][lr](S);n[Jn].readRequests=[]}function readableStreamDefaultReaderRead(n,S){let{stream:C}=n[Jn];switch(C[Jn].disturbed=!0,C[Jn].state){case`closed`:S[sr]();break;case`errored`:S[lr](C[Jn].storedError);break;case`readable`:C[Jn].controller[ur](S);break}}function setupReadableStreamDefaultReader(n,S){if(isReadableStreamLocked(S))throw TypeError(`ReadableStream is locked`);readableStreamReaderGenericInitialize(n,S),n[Jn].readRequests=[]}function readableStreamDefaultControllerClose(n){readableStreamDefaultControllerCanCloseOrEnqueue(n)&&(n[Jn].closeRequested=!0,n[Jn].queue.length||(readableStreamDefaultControllerClearAlgorithms(n),readableStreamClose(n[Jn].stream)))}function readableStreamDefaultControllerEnqueue(n,S){if(!readableStreamDefaultControllerCanCloseOrEnqueue(n))return;let{stream:C}=n[Jn];if(isReadableStreamLocked(C)&&readableStreamGetNumReadRequests(C))readableStreamFulfillReadRequest(C,S,!1);else try{enqueueValueWithSize(n,S,n[Jn].sizeAlgorithm(S))}catch(S){throw readableStreamDefaultControllerError(n,S),S}readableStreamDefaultControllerCallPullIfNeeded(n)}function readableStreamDefaultControllerCanCloseOrEnqueue(n){let{stream:S}=n[Jn];return!n[Jn].closeRequested&&S[Jn].state===`readable`}function readableStreamDefaultControllerGetDesiredSize(n){let{stream:S,highWaterMark:C,queueTotalSize:N}=n[Jn];switch(S[Jn].state){case`errored`:return null;case`closed`:return 0;default:return C-N}}function readableStreamDefaultControllerHasBackpressure(n){return!readableStreamDefaultControllerShouldCallPull(n)}function readableStreamDefaultControllerShouldCallPull(n){let{stream:S}=n[Jn];if(!readableStreamDefaultControllerCanCloseOrEnqueue(n)||!n[Jn].started)return!1;if(isReadableStreamLocked(S)&&readableStreamGetNumReadRequests(S))return!0;let C=readableStreamDefaultControllerGetDesiredSize(n);return C!==null&&C>0}function readableStreamDefaultControllerCallPullIfNeeded(n){if(readableStreamDefaultControllerShouldCallPull(n)){if(n[Jn].pulling){n[Jn].pullAgain=!0;return}n[Jn].pulling=!0,n[Jn].pullAlgorithm(n).then(()=>{n[Jn].pulling=!1,n[Jn].pullAgain&&(n[Jn].pullAgain=!1,readableStreamDefaultControllerCallPullIfNeeded(n))},S=>readableStreamDefaultControllerError(n,S))}}function readableStreamDefaultControllerClearAlgorithms(n){n[Jn].pullAlgorithm=void 0,n[Jn].cancelAlgorithm=void 0,n[Jn].sizeAlgorithm=void 0}function readableStreamDefaultControllerError(n,S){let{stream:C}=n[Jn];C[Jn].state===`readable`&&(resetQueue(n),readableStreamDefaultControllerClearAlgorithms(n),readableStreamError(C,S))}function readableStreamDefaultControllerCancelSteps(n,S){resetQueue(n);let C=n[Jn].cancelAlgorithm?.(S)??Promise.resolve();return readableStreamDefaultControllerClearAlgorithms(n),C}function readableStreamDefaultControllerPullSteps(n,S){let{stream:C,queue:N}=n[Jn];if(N.length){let F=dequeueValue(n);n[Jn].closeRequested&&!N.length?(readableStreamDefaultControllerClearAlgorithms(n),readableStreamClose(C)):readableStreamDefaultControllerCallPullIfNeeded(n),S[cr](F);return}readableStreamAddReadRequest(C,S),readableStreamDefaultControllerCallPullIfNeeded(n)}function setupReadableStreamDefaultController(n,S,C,N,F,I,H){S[Jn]={cancelAlgorithm:F,closeRequested:!1,highWaterMark:I,pullAgain:!1,pullAlgorithm:N,pulling:!1,queue:[],queueTotalSize:0,started:!1,sizeAlgorithm:H,stream:n},n[Jn].controller=S;let W=C();new Promise(n=>n(W)).then(()=>{S[Jn].started=!0,readableStreamDefaultControllerCallPullIfNeeded(S)},n=>readableStreamDefaultControllerError(S,n))}function setupReadableStreamDefaultControllerFromSource(n,S,C,N){let F=new ReadableStreamDefaultController(fr),I=S?.start,H=S?.pull,W=S?.cancel;setupReadableStreamDefaultController(n,F,I?I.bind(S,F):nonOpStart,H?createPromiseCallback(`source.pull`,H,S):nonOpPull,W?createPromiseCallback(`source.cancel`,W,S):nonOpCancel,C,N)}function createReadableStream(n,S,C,N=1,F=()=>1){let I=Object.create(ReadableStream$1.prototype);return I[Yn]=`ReadableStream`,I[Jn]=createReadableStreamState(),setupReadableStreamDefaultController(I,new ReadableStreamDefaultController(fr),n,S,C,N,F),I}function readableStreamFromIterable(n){let S,C=getIterator(n,`async`),N=nonOpStart;async function pullAlgorithm(){let n=iteratorNext(C);return Promise.resolve(n).then(n=>{if(typeof n!=`object`||!n)throw TypeError(`The promise returned by the iterator.next() method must fulfill with an object`);n.done?readableStreamDefaultControllerClose(S[Jn].controller):readableStreamDefaultControllerEnqueue(S[Jn].controller,n.value)})}async function cancelAlgorithm(n){let S=C.iterator,N=S.return;if(N===void 0)return Promise.resolve();let F=N.call(S,n);return Promise.resolve(F).then(n=>{if(typeof n!=`object`||!n)throw TypeError(`The promise returned by the iterator.return() method must fulfill with an object`)})}return S=createReadableStream(N,pullAlgorithm,cancelAlgorithm,0),S}function readableStreamPipeTo(n,S,C,N,F,I){let H,W;try{H=new ReadableStreamDefaultReader(n),W=new WritableStreamDefaultWriter(S)}catch(n){return Promise.reject(n)}n[Jn].disturbed=!0;let q=!1,{promise:Y,resolve:X,reject:Z}=Promise.withResolvers(),te={currentWrite:Promise.resolve()},ne;function finalize(n,S){writableStreamDefaultWriterRelease(W),readableStreamReaderGenericRelease(H),I!==void 0&&ne&&(I.removeEventListener(`abort`,ne),ne=void 0),n?Z(S):X()}async function waitForCurrentWrite(){let n=te.currentWrite;await n,n!==te.currentWrite&&await waitForCurrentWrite()}function shutdownWithAnAction(n,C,N){if(q)return;if(q=!0,S[Jn].state===`writable`&&!writableStreamCloseQueuedOrInFlight(S)){waitForCurrentWrite().then(complete,n=>finalize(!0,n));return}complete();function complete(){n().then(()=>finalize(!!C,N),n=>finalize(!0,n))}}function shutdown(n,C){if(!q){if(q=!0,S[Jn].state===`writable`&&!writableStreamCloseQueuedOrInFlight(S)){waitForCurrentWrite().then(()=>finalize(!!n,C),n=>finalize(!0,n));return}finalize(!!n,C)}}function abortAlgorithm(){let C;C=I.reason&&I.reason.name===`AbortError`?createAbortError$1():I.reason;let H=[];N||H.push(()=>S[Jn].state===`writable`?writableStreamAbort(S,C):Promise.resolve()),F||H.push(()=>n[Jn].state===`readable`?readableStreamCancel(n,C):Promise.resolve()),shutdownWithAnAction(()=>Promise.all(H.map(n=>n())).then(()=>void 0),!0,C)}function watchErrored(n,S,C){n[Jn].state===`errored`?C(n[Jn].storedError):S.then(void 0,C)}function watchClosed(n,S,C){n[Jn].state===`closed`?C():S.then(C,()=>{})}class PipeToReadRequest{[cr](n){be(()=>{te.currentWrite=writableStreamDefaultWriterWrite(W,n),setPromiseHandled(te.currentWrite),re.resolve(!1)})}[sr](){re.resolve(!0)}[lr](n){re.reject(n)}}let re={resolve:null,reject:null};async function step(){if(q||S[Jn].backpressure&&(await W[Jn].ready.promise,q))return!0;let C=n[Jn].controller;if(n[Jn].state===`readable`&&gr(C)&&C[Jn].queue.length>0){for(;C[Jn].queue.length>0;){if(q)return!0;let N=dequeueValue(C);if(C[Jn].closeRequested&&!C[Jn].queue.length&&(readableStreamDefaultControllerClearAlgorithms(C),readableStreamClose(n)),te.currentWrite=writableStreamDefaultWriterWrite(W,N),setPromiseHandled(te.currentWrite),S[Jn].backpressure||S[Jn].state!==`writable`||writableStreamCloseQueuedOrInFlight(S))break}return readableStreamDefaultControllerCallPullIfNeeded(C),n[Jn].state===`closed`}let{promise:N,resolve:F,reject:I}=Promise.withResolvers();return re={resolve:F,reject:I},readableStreamDefaultReaderRead(H,new PipeToReadRequest),N}async function run(){for(;!await step(););}if(I!==void 0){if(I.aborted)return abortAlgorithm(),Y;ne=abortAlgorithm,I.addEventListener(`abort`,ne,{once:!0})}if(setPromiseHandled(run()),watchErrored(n,H[Jn].close.promise,n=>{if(!N)return shutdownWithAnAction(()=>writableStreamAbort(S,n),!0,n);shutdown(!0,n)}),watchErrored(S,W[Jn].close.promise,S=>{if(!F)return shutdownWithAnAction(()=>readableStreamCancel(n,S),!0,S);shutdown(!0,S)}),watchClosed(n,H[Jn].close.promise,()=>{if(!C)return shutdownWithAnAction(()=>writableStreamDefaultWriterCloseWithErrorPropagation(W));shutdown()}),writableStreamCloseQueuedOrInFlight(S)||S[Jn].state===`closed`){let S=TypeError(`Destination WritableStream is closed`);F?shutdown(!0,S):shutdownWithAnAction(()=>readableStreamCancel(n,S),!0,S)}return Y}function readableStreamDefaultTee(n,S){let C=new ReadableStreamDefaultReader(n),N=!1,F=!1,I=!1,H,W,q,Y,X=Promise.withResolvers();async function pullAlgorithm(){N||(N=!0,readableStreamDefaultReaderRead(C,{[cr](n){be(()=>{N=!1;let C=n,H=n;if(!I&&S)try{H=structuredClone(H)}catch{}F||readableStreamDefaultControllerEnqueue(q[Jn].controller,C),I||readableStreamDefaultControllerEnqueue(Y[Jn].controller,H)})},[sr](){be(()=>{N=!1,F||readableStreamDefaultControllerClose(q[Jn].controller),I||readableStreamDefaultControllerClose(Y[Jn].controller),(!F||!I)&&X.resolve(void 0)})},[lr](){N=!1}}))}function cancel1Algorithm(S){if(F=!0,H=S,I){let S=[H,W];X.resolve(readableStreamCancel(n,S))}return X.promise}function cancel2Algorithm(S){if(I=!0,W=S,F){let S=[H,W];X.resolve(readableStreamCancel(n,S))}return X.promise}return q=createReadableStream(nonOpStart,pullAlgorithm,cancel1Algorithm),Y=createReadableStream(nonOpStart,pullAlgorithm,cancel2Algorithm),C[Jn].close.promise.then(void 0,n=>{readableStreamDefaultControllerError(q[Jn].controller,n),readableStreamDefaultControllerError(Y[Jn].controller,n),(!F||!I)&&X.resolve(void 0)}),[q,Y]}var BYOBReadIntoRequest=class{[Jn];constructor(){this[Jn]=Promise.withResolvers()}[cr](n){this[Jn].resolve?.({value:n,done:!1})}[sr](n){this[Jn].resolve?.({value:n,done:!0})}[lr](n){this[Jn].reject?.(n)}get promise(){return this[Jn].promise}},ReadableStreamBYOBReader=class{[Yn]=`ReadableStreamBYOBReader`;[Jn];constructor(n){if(!hr(n))throw TypeError(`Expected a ReadableStream`);this[Jn]={readRequests:[],readIntoRequests:[],stream:void 0,close:{promise:void 0,resolve:void 0,reject:void 0}},setupReadableStreamBYOBReader(this,n)}read(n,S={}){if(!yr(this))return Promise.reject(TypeError(`Invalid this`));if(typeof n!=`object`||!n||!ArrayBuffer.isView(n))return Promise.reject(TypeError(`view must be an ArrayBufferView`));let C=n.buffer,N=n.byteLength;if(N===0)return Promise.reject(TypeError(`view must have non-zero byteLength`));if(C.byteLength===0)return isDetachedBuffer(C)?Promise.reject(TypeError(`view's buffer has been detached`)):Promise.reject(TypeError(`view's buffer must have non-zero byteLength`));let F=S?.min??1;if(typeof F!=`number`||F<1||!Number.isInteger(F)||Number.isNaN(F))return Promise.reject(TypeError(`options.min must be a positive integer`));let I=n[Symbol.toStringTag];if(I!==void 0&&I!==`DataView`){if(F>n.length)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`))}else if(F>N)return Promise.reject(RangeError(`options.min must be smaller or equal to view size`));if(this[Jn].stream===void 0)return Promise.reject(TypeError(`Reader has no associated stream`));let H=new BYOBReadIntoRequest;return readableStreamBYOBReaderRead(this,n,F,H),H.promise}releaseLock(){if(!yr(this))throw TypeError(`Invalid this`);this[Jn].stream!==void 0&&readableStreamBYOBReaderRelease(this)}get closed(){return yr(this)?this[Jn].close.promise:Promise.reject(TypeError(`Invalid this`))}cancel(n=void 0){return yr(this)?this[Jn].stream===void 0?Promise.reject(TypeError(`Reader has no associated stream`)):readableStreamReaderGenericCancel(this,n):Promise.reject(TypeError(`Invalid this`))}get[Symbol.toStringTag](){return`ReadableStreamBYOBReader`}},ReadableStreamBYOBRequest=class{[Yn]=`ReadableStreamBYOBRequest`;[Jn];constructor(n){if(n!==fr)throw TypeError(`Illegal constructor`)}get view(){if(!br(this))throw TypeError(`Invalid this`);return this[Jn].view}respond(n){if(!br(this))throw TypeError(`Invalid this`);if(this[Jn].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(n=+n,!Number.isInteger(n)||n<0||!Number.isFinite(n))throw RangeError(`bytesWritten must be a non-negative integer`);let S=this[Jn].view;if(isDetachedBuffer(S.buffer))throw TypeError(`The BYOB request's buffer has been detached`);readableByteStreamControllerRespond(this[Jn].controller,n)}respondWithNewView(n){if(!br(this))throw TypeError(`Invalid this`);if(this[Jn].controller===void 0)throw TypeError(`BYOB request has been invalidated`);if(typeof n!=`object`||!n||!ArrayBuffer.isView(n))throw TypeError(`view must be an ArrayBufferView`);if(isDetachedBuffer(n.buffer))throw TypeError(`The given view's buffer has been detached`);readableByteStreamControllerRespondWithNewView(this[Jn].controller,n)}get[Symbol.toStringTag](){return`ReadableStreamBYOBRequest`}},ReadableByteStreamController=class{[Yn]=`ReadableByteStreamController`;[Jn];constructor(n){if(n!==fr)throw TypeError(`Illegal constructor`)}get byobRequest(){if(!vr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetBYOBRequest(this)}get desiredSize(){if(!vr(this))throw TypeError(`Invalid this`);return readableByteStreamControllerGetDesiredSize(this)}close(){if(!vr(this))throw TypeError(`Invalid this`);if(this[Jn].closeRequested)throw TypeError(`Close already requested`);if(this[Jn].stream[Jn].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerClose(this)}enqueue(n){if(!vr(this))throw TypeError(`Invalid this`);if(typeof n!=`object`||!n||!ArrayBuffer.isView(n))throw TypeError(`chunk must be an ArrayBufferView`);if(n.byteLength===0)throw TypeError(`chunk length must be non-zero`);if(n.buffer.byteLength===0)throw TypeError(`chunk's buffer length must be non-zero`);if(this[Jn].closeRequested)throw TypeError(`Cannot enqueue after close has been requested`);if(this[Jn].stream[Jn].state!==`readable`)throw TypeError(`Stream is not in a readable state`);readableByteStreamControllerEnqueue(this,n)}error(n=void 0){if(!vr(this))throw TypeError(`Invalid this`);readableByteStreamControllerError(this,n)}[ar](n){return readableByteStreamControllerCancelSteps(this,n)}[ur](n){readableByteStreamControllerPullSteps(this,n)}[dr](){if(this[Jn].pendingPullIntos.length>0){let n=this[Jn].pendingPullIntos[0];n.readerType=`none`,this[Jn].pendingPullIntos=[n]}}get[Symbol.toStringTag](){return`ReadableByteStreamController`}};const vr=isBrandCheck(`ReadableByteStreamController`),yr=isBrandCheck(`ReadableStreamBYOBReader`),br=isBrandCheck(`ReadableStreamBYOBRequest`);function readableStreamHasBYOBReader(n){let{reader:S}=n[Jn];return S===void 0?!1:S[Jn]!==void 0&&S[Yn]===`ReadableStreamBYOBReader`}function readableStreamGetNumReadIntoRequests(n){return n[Jn].reader[Jn].readIntoRequests.length}function readableStreamAddReadIntoRequest(n,S){n[Jn].reader[Jn].readIntoRequests.push(S)}function readableStreamFulfillReadIntoRequest(n,S,C){let{reader:N}=n[Jn],F=N[Jn].readIntoRequests.shift();C?F[sr](S):F[cr](S)}function setupReadableStreamBYOBReader(n,S){if(isReadableStreamLocked(S))throw TypeError(`ReadableStream is locked`);if(!vr(S[Jn].controller))throw TypeError(`Cannot use a BYOB reader with a non-byte stream`);readableStreamReaderGenericInitialize(n,S),n[Jn].readIntoRequests=[]}function readableStreamBYOBReaderRead(n,S,C,N){let{stream:F}=n[Jn];F[Jn].disturbed=!0,F[Jn].state===`errored`?N[lr](F[Jn].storedError):readableByteStreamControllerPullInto(F[Jn].controller,S,C,N)}function readableStreamBYOBReaderRelease(n){readableStreamReaderGenericRelease(n);let S=TypeError(`Reader was released`);for(let C=0;C<n[Jn].readIntoRequests.length;C++)n[Jn].readIntoRequests[C][lr](S);n[Jn].readIntoRequests=[]}function readableByteStreamControllerClearAlgorithms(n){n[Jn].pullAlgorithm=void 0,n[Jn].cancelAlgorithm=void 0}function readableByteStreamControllerClearPendingPullIntos(n){readableByteStreamControllerInvalidateBYOBRequest(n),n[Jn].pendingPullIntos=[]}function readableByteStreamControllerInvalidateBYOBRequest(n){let S=n[Jn].byobRequest;S!=null&&(S[Jn].controller=void 0,S[Jn].view=null,n[Jn].byobRequest=null)}function readableByteStreamControllerError(n,S){let{stream:C}=n[Jn];C[Jn].state===`readable`&&(readableByteStreamControllerClearPendingPullIntos(n),resetQueue(n),readableByteStreamControllerClearAlgorithms(n),readableStreamError(C,S))}function readableByteStreamControllerGetDesiredSize(n){let S=n[Jn].stream[Jn].state;return S===`errored`?null:S===`closed`?0:n[Jn].highWaterMark-n[Jn].queueTotalSize}function readableByteStreamControllerShouldCallPull(n){let{stream:S}=n[Jn];if(S[Jn].state!==`readable`||n[Jn].closeRequested||!n[Jn].started)return!1;if(readableStreamHasDefaultReader(S)&&readableStreamGetNumReadRequests(S)>0||readableStreamHasBYOBReader(S)&&readableStreamGetNumReadIntoRequests(S)>0)return!0;let C=readableByteStreamControllerGetDesiredSize(n);return C!==null&&C>0}function readableByteStreamControllerCallPullIfNeeded(n){if(readableByteStreamControllerShouldCallPull(n)){if(n[Jn].pulling){n[Jn].pullAgain=!0;return}n[Jn].pulling=!0,n[Jn].pullAlgorithm(n).then(()=>{n[Jn].pulling=!1,n[Jn].pullAgain&&(n[Jn].pullAgain=!1,readableByteStreamControllerCallPullIfNeeded(n))},S=>readableByteStreamControllerError(n,S))}}function readableByteStreamControllerHandleQueueDrain(n){n[Jn].queueTotalSize===0&&n[Jn].closeRequested?(readableByteStreamControllerClearAlgorithms(n),readableStreamClose(n[Jn].stream)):readableByteStreamControllerCallPullIfNeeded(n)}function readableByteStreamControllerEnqueueChunkToQueue(n,S,C,N){n[Jn].queue.push({buffer:S,byteOffset:C,byteLength:N}),n[Jn].queueTotalSize+=N}function readableByteStreamControllerEnqueueClonedChunkToQueue(n,S,C,N){let F;try{F=S.slice(C,C+N)}catch(S){readableByteStreamControllerError(n,S);return}readableByteStreamControllerEnqueueChunkToQueue(n,F,0,N)}function readableByteStreamControllerEnqueueDetachedPullIntoToQueue(n,S){S.bytesFilled>0&&readableByteStreamControllerEnqueueClonedChunkToQueue(n,S.buffer,S.byteOffset,S.bytesFilled),readableByteStreamControllerShiftPendingPullInto(n)}function readableByteStreamControllerShiftPendingPullInto(n){return n[Jn].pendingPullIntos.shift()}function readableByteStreamControllerFillHeadPullIntoDescriptor(n,S,C){C.bytesFilled+=S}function readableByteStreamControllerConvertPullIntoDescriptor(n){let S=n.bytesFilled,C=n.elementSize,N=transferArrayBuffer(n.buffer);return n.buffer=N,new n.viewConstructor(N,n.byteOffset,S/C)}function readableByteStreamControllerCommitPullIntoDescriptor(n,S){let C=!1;n[Jn].state===`closed`&&(C=!0);let N=readableByteStreamControllerConvertPullIntoDescriptor(S);S.readerType==="default"?readableStreamFulfillReadRequest(n,N,C):readableStreamFulfillReadIntoRequest(n,N,C)}function readableByteStreamControllerFillPullIntoDescriptorFromQueue(n,S){let C=Math.min(n[Jn].queueTotalSize,S.byteLength-S.bytesFilled),N=S.bytesFilled+C,F=C,I=!1,H=N-N%S.elementSize;H>=S.minimumFill&&(F=H-S.bytesFilled,I=!0);let W=n[Jn].queue;for(;F>0;){let C=W[0],N=Math.min(F,C.byteLength),I=S.byteOffset+S.bytesFilled,H=new Uint8Array(S.buffer,I,N),q=new Uint8Array(C.buffer,C.byteOffset,N);H.set(q),C.byteLength===N?W.shift():(C.byteOffset+=N,C.byteLength-=N),n[Jn].queueTotalSize-=N,readableByteStreamControllerFillHeadPullIntoDescriptor(n,N,S),F-=N}return I}function readableByteStreamControllerFillReadRequestFromQueue(n,S){let C=n[Jn].queue.shift();n[Jn].queueTotalSize-=C.byteLength,readableByteStreamControllerHandleQueueDrain(n);let N=new Uint8Array(C.buffer,C.byteOffset,C.byteLength);S[cr](N)}function readableByteStreamControllerProcessReadRequestsUsingQueue(n){let S=n[Jn].stream[Jn].reader;for(;S[Jn].readRequests.length!==0;){if(n[Jn].queueTotalSize===0)return;readableByteStreamControllerFillReadRequestFromQueue(n,S[Jn].readRequests.shift())}}function readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(n){for(;n[Jn].pendingPullIntos.length!==0;){if(n[Jn].queueTotalSize===0)return;let S=n[Jn].pendingPullIntos[0];readableByteStreamControllerFillPullIntoDescriptorFromQueue(n,S)&&(readableByteStreamControllerShiftPendingPullInto(n),readableByteStreamControllerCommitPullIntoDescriptor(n[Jn].stream,S))}}function readableByteStreamControllerGetBYOBRequest(n){if(n[Jn].byobRequest===null&&n[Jn].pendingPullIntos.length!==0){let S=n[Jn].pendingPullIntos[0],C=new Uint8Array(S.buffer,S.byteOffset+S.bytesFilled,S.byteLength-S.bytesFilled),N=new ReadableStreamBYOBRequest(fr);N[Jn]={controller:n,view:C},n[Jn].byobRequest=N}return n[Jn].byobRequest}function readableByteStreamControllerEnqueue(n,S){let{stream:C}=n[Jn];if(n[Jn].closeRequested||C[Jn].state!==`readable`)return;let N=S.buffer,F=S.byteLength,I=S.byteOffset;if(isDetachedBuffer(N))throw TypeError(`chunk's buffer is detached`);let H=transferArrayBuffer(N);if(n[Jn].pendingPullIntos.length!==0){let S=n[Jn].pendingPullIntos[0];if(isDetachedBuffer(S.buffer))throw TypeError(`BYOB request's buffer has been detached`);readableByteStreamControllerInvalidateBYOBRequest(n),S.buffer=transferArrayBuffer(S.buffer),S.readerType===`none`&&readableByteStreamControllerEnqueueDetachedPullIntoToQueue(n,S)}readableStreamHasDefaultReader(C)?(readableByteStreamControllerProcessReadRequestsUsingQueue(n),readableStreamGetNumReadRequests(C)===0?readableByteStreamControllerEnqueueChunkToQueue(n,H,I,F):(n[Jn].pendingPullIntos.length!==0&&readableByteStreamControllerShiftPendingPullInto(n),readableStreamFulfillReadRequest(C,new Uint8Array(H,I,F),!1))):readableStreamHasBYOBReader(C)?(readableByteStreamControllerEnqueueChunkToQueue(n,H,I,F),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(n)):readableByteStreamControllerEnqueueChunkToQueue(n,H,I,F),readableByteStreamControllerCallPullIfNeeded(n)}function readableByteStreamControllerClose(n){let{stream:S}=n[Jn];if(!(n[Jn].closeRequested||S[Jn].state!==`readable`)){if(n[Jn].queueTotalSize>0){n[Jn].closeRequested=!0;return}if(n[Jn].pendingPullIntos.length!==0){let S=n[Jn].pendingPullIntos[0];if(S.bytesFilled%S.elementSize!==0){let S=TypeError(`Insufficient bytes to fill elements in the given buffer`);throw readableByteStreamControllerError(n,S),S}}readableByteStreamControllerClearAlgorithms(n),readableStreamClose(S)}}function readableByteStreamControllerPullInto(n,S,C,N){let F=n[Jn].stream,I=S[Symbol.toStringTag],H,W;if(I===void 0||I===`DataView`)H=DataView,W=1;else{let n=typedArrayConstructorByTag(I);if(!n){N[lr](TypeError(`Unsupported typed array: ${I}`));return}H=n,W=elementSizeByTag(I)}let q=S.buffer,Y=S.byteLength,X=S.byteOffset,Z=C*W,te;try{te=transferArrayBuffer(q)}catch(n){N[lr](n);return}let ne={buffer:te,bufferByteLength:te.byteLength,byteOffset:X,byteLength:Y,bytesFilled:0,minimumFill:Z,elementSize:W,viewConstructor:H,readerType:`byob`};if(n[Jn].pendingPullIntos.length!==0){n[Jn].pendingPullIntos.push(ne),readableStreamAddReadIntoRequest(F,N);return}if(F[Jn].state===`closed`){let n=new H(ne.buffer,ne.byteOffset,0);N[sr](n);return}if(n[Jn].queueTotalSize>0){if(readableByteStreamControllerFillPullIntoDescriptorFromQueue(n,ne)){let S=readableByteStreamControllerConvertPullIntoDescriptor(ne);readableByteStreamControllerHandleQueueDrain(n),N[cr](S);return}if(n[Jn].closeRequested){let S=TypeError(`Insufficient bytes to fill elements in the given buffer`);readableByteStreamControllerError(n,S),N[lr](S);return}}n[Jn].pendingPullIntos.push(ne),readableStreamAddReadIntoRequest(F,N),readableByteStreamControllerCallPullIfNeeded(n)}function readableByteStreamControllerRespond(n,S){let C=n[Jn].pendingPullIntos[0];if(n[Jn].stream[Jn].state===`closed`){if(S!==0)throw TypeError(`bytesWritten must be 0 when calling respond() on a closed stream`)}else{if(S===0)throw TypeError(`bytesWritten must be greater than 0 when calling respond() on a readable stream`);if(C.bytesFilled+S>C.byteLength)throw RangeError(`bytesWritten out of range`)}C.buffer=transferArrayBuffer(C.buffer),readableByteStreamControllerRespondInternal(n,S)}function readableByteStreamControllerRespondWithNewView(n,S){let C=n[Jn].pendingPullIntos[0],N=n[Jn].stream[Jn].state,F=S.byteLength,I=S.byteOffset,H=S.buffer;if(N===`closed`){if(F!==0)throw TypeError(`view's length must be 0 when calling respondWithNewView() on a closed stream`)}else if(F===0)throw TypeError(`view's length must be greater than 0 when calling respondWithNewView() on a readable stream`);if(C.byteOffset+C.bytesFilled!==I)throw RangeError(`The region specified by view does not match byobRequest`);if(C.bufferByteLength!==H.byteLength)throw RangeError(`The buffer of view has different capacity than byobRequest`);if(C.bytesFilled+F>C.byteLength)throw RangeError(`The region specified by view is larger than byobRequest`);C.buffer=transferArrayBuffer(H),readableByteStreamControllerRespondInternal(n,F)}function readableByteStreamControllerRespondInternal(n,S){let C=n[Jn].pendingPullIntos[0];readableByteStreamControllerInvalidateBYOBRequest(n),n[Jn].stream[Jn].state===`closed`?readableByteStreamControllerRespondInClosedState(n,C):readableByteStreamControllerRespondInReadableState(n,S,C),readableByteStreamControllerCallPullIfNeeded(n)}function readableByteStreamControllerRespondInClosedState(n,S){S.readerType===`none`&&readableByteStreamControllerShiftPendingPullInto(n);let C=n[Jn].stream;if(readableStreamHasBYOBReader(C))for(;readableStreamGetNumReadIntoRequests(C)>0;)readableByteStreamControllerCommitPullIntoDescriptor(C,readableByteStreamControllerShiftPendingPullInto(n))}function readableByteStreamControllerRespondInReadableState(n,S,C){if(readableByteStreamControllerFillHeadPullIntoDescriptor(n,S,C),C.readerType===`none`){readableByteStreamControllerEnqueueDetachedPullIntoToQueue(n,C),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(n);return}if(C.bytesFilled<C.minimumFill)return;readableByteStreamControllerShiftPendingPullInto(n);let N=C.bytesFilled%C.elementSize;if(N>0){let S=C.byteOffset+C.bytesFilled;readableByteStreamControllerEnqueueClonedChunkToQueue(n,C.buffer,S-N,N)}C.bytesFilled-=N,readableByteStreamControllerCommitPullIntoDescriptor(n[Jn].stream,C),readableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(n)}function readableByteStreamControllerCancelSteps(n,S){readableByteStreamControllerClearPendingPullIntos(n),resetQueue(n);let C=n[Jn].cancelAlgorithm?.(S)??Promise.resolve();return readableByteStreamControllerClearAlgorithms(n),C}function readableByteStreamControllerPullSteps(n,S){let C=n[Jn].stream;if(n[Jn].queueTotalSize>0){readableByteStreamControllerFillReadRequestFromQueue(n,S);return}let N=n[Jn].autoAllocateChunkSize;if(N!==void 0){let C;try{C=new ArrayBuffer(N)}catch(n){S[lr](n);return}let F={buffer:C,bufferByteLength:N,byteOffset:0,byteLength:N,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:`default`};n[Jn].pendingPullIntos.push(F)}readableStreamAddReadRequest(C,S),readableByteStreamControllerCallPullIfNeeded(n)}function setupReadableByteStreamController(n,S,C,N,F,I,H){S[Jn]={cancelAlgorithm:F,closeRequested:!1,highWaterMark:I,pullAgain:!1,pullAlgorithm:N,pulling:!1,queue:[],queueTotalSize:0,started:!1,stream:n,byobRequest:null,pendingPullIntos:[],autoAllocateChunkSize:H},n[Jn].controller=S;let W=C();new Promise(n=>n(W)).then(()=>{S[Jn].started=!0,readableByteStreamControllerCallPullIfNeeded(S)},n=>readableByteStreamControllerError(S,n))}function setupReadableByteStreamControllerFromSource(n,S,C){let N=new ReadableByteStreamController(fr),F=S?.start,I=S?.pull,H=S?.cancel,W=S?.autoAllocateChunkSize;if(W!==void 0&&(W===0||!Number.isInteger(W)||W<0))throw TypeError(`autoAllocateChunkSize must be a positive integer`);setupReadableByteStreamController(n,N,F?F.bind(S,N):nonOpStart,I?createPromiseCallback(`source.pull`,I,S):nonOpPull,H?createPromiseCallback(`source.cancel`,H,S):nonOpCancel,C,W)}function readableByteStreamTee(n){let S=new ReadableStreamDefaultReader(n),C=!1,N=!1,F=!1,I,H,W=Promise.withResolvers(),q,Y,X,Z;function pullAlgorithm(){return C?Promise.resolve():(C=!0,S.read().then(n=>{if(C=!1,n.done){N||X.close(),F||Z.close();return}let S=n.value,I=new Uint8Array(S.buffer.slice(S.byteOffset,S.byteOffset+S.byteLength));N||X.enqueue(I),F||Z.enqueue(new Uint8Array(I))},()=>{}),Promise.resolve())}return q=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(S){if(N=!0,I=S,F){let S=readableStreamCancel(n,[I,H]);return W.resolve(),S}return W.promise}}),Y=new ReadableStream$1({type:`bytes`,pull:pullAlgorithm,cancel(S){if(F=!0,H=S,N){let S=readableStreamCancel(n,[I,H]);return W.resolve(),S}return W.promise}}),X=q[Jn].controller,Z=Y[Jn].controller,S.closed.catch(n=>{X.error(n),Z.error(n),(!N||!F)&&W.resolve()}),[q,Y]}const Sr=Symbol(`kSkipThrow`);var TransformStream=class{[Yn]=`TransformStream`;[Jn];constructor(n={},S={},C={}){if(n!=null&&typeof n!=`object`)throw TypeError(`transformer must be an object`);if(S!=null&&typeof S!=`object`)throw TypeError(`writableStrategy must be an object`);if(C!=null&&typeof C!=`object`)throw TypeError(`readableStrategy must be an object`);let N=n?.readableType,F=n?.writableType,I=n?.start;if(N!==void 0)throw RangeError(`Invalid readableType: ${N}`);if(F!==void 0)throw RangeError(`Invalid writableType: ${F}`);let H=extractHighWaterMark(C?.highWaterMark,0),W=extractSizeAlgorithm(C?.size),q=extractHighWaterMark(S?.highWaterMark,1),Y=extractSizeAlgorithm(S?.size),X=Promise.withResolvers();initializeTransformStream(this,X,q,Y,H,W),setupTransformStreamDefaultControllerFromTransformer(this,n),I===void 0?X.resolve():X.resolve(I.call(n,this[Jn].controller))}get readable(){if(!Cr(this))throw TypeError(`Invalid this`);return this[Jn].readable}get writable(){if(!Cr(this))throw TypeError(`Invalid this`);return this[Jn].writable}get[Symbol.toStringTag](){return`TransformStream`}},TransformStreamDefaultController=class{[Yn]=`TransformStreamDefaultController`;[Jn];constructor(n){if(n!==Sr)throw TypeError(`Illegal constructor`)}get desiredSize(){if(!wr(this))throw TypeError(`Invalid this`);let{stream:n}=this[Jn],{readable:S}=n[Jn],C=S[Jn].controller;return readableStreamDefaultControllerGetDesiredSize(C)}enqueue(n){if(!wr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerEnqueue(this,n)}error(n){if(!wr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerError(this,n)}terminate(){if(!wr(this))throw TypeError(`Invalid this`);transformStreamDefaultControllerTerminate(this)}get[Symbol.toStringTag](){return`TransformStreamDefaultController`}};const Cr=isBrandCheck(`TransformStream`),wr=isBrandCheck(`TransformStreamDefaultController`);async function defaultTransformAlgorithm(n,S){transformStreamDefaultControllerEnqueue(S,n)}function initializeTransformStream(n,S,C,N,F,I){let startAlgorithm=()=>S.promise,H=createWritableStream(startAlgorithm,S=>transformStreamDefaultSinkWriteAlgorithm(n,S),()=>transformStreamDefaultSinkCloseAlgorithm(n),S=>transformStreamDefaultSinkAbortAlgorithm(n,S),C,N);n[Jn]={readable:createReadableStream(startAlgorithm,()=>transformStreamDefaultSourcePullAlgorithm(n),S=>transformStreamDefaultSourceCancelAlgorithm(n,S),F,I),writable:H,controller:void 0,backpressure:void 0,backpressureChange:{promise:void 0,resolve:void 0,reject:void 0}},transformStreamSetBackpressure(n,!0)}function transformStreamError(n,S){let{readable:C}=n[Jn];readableStreamDefaultControllerError(C[Jn].controller,S),transformStreamErrorWritableAndUnblockWrite(n,S)}function transformStreamErrorWritableAndUnblockWrite(n,S){let{controller:C,writable:N}=n[Jn];transformStreamDefaultControllerClearAlgorithms(C),writableStreamDefaultControllerErrorIfNeeded(N[Jn].controller,S),transformStreamUnblockWrite(n)}function transformStreamUnblockWrite(n){n[Jn].backpressure&&transformStreamSetBackpressure(n,!1)}function transformStreamSetBackpressure(n,S){n[Jn].backpressureChange.promise!==void 0&&n[Jn].backpressureChange.resolve?.(),n[Jn].backpressureChange=Promise.withResolvers(),n[Jn].backpressure=S}function setupTransformStreamDefaultController(n,S,C,N,F){S[Jn]={stream:n,transformAlgorithm:C,flushAlgorithm:N,cancelAlgorithm:F,finishPromise:void 0},n[Jn].controller=S}function setupTransformStreamDefaultControllerFromTransformer(n,S){let C=new TransformStreamDefaultController(Sr),N=S?.transform,F=S?.flush,I=S?.cancel;setupTransformStreamDefaultController(n,C,N?createPromiseCallback(`transformer.transform`,N,S):defaultTransformAlgorithm,F?createPromiseCallback(`transformer.flush`,F,S):nonOpFlush,I?createPromiseCallback(`transformer.cancel`,I,S):nonOpCancel)}function transformStreamDefaultControllerClearAlgorithms(n){n[Jn].transformAlgorithm=void 0,n[Jn].flushAlgorithm=void 0,n[Jn].cancelAlgorithm=void 0}function transformStreamDefaultControllerEnqueue(n,S){let{stream:C}=n[Jn],{readable:N}=C[Jn],F=N[Jn].controller;if(!readableStreamDefaultControllerCanCloseOrEnqueue(F))throw TypeError(`Unable to enqueue`);try{readableStreamDefaultControllerEnqueue(F,S)}catch(n){throw transformStreamErrorWritableAndUnblockWrite(C,n),N[Jn].storedError}readableStreamDefaultControllerHasBackpressure(F)!==C[Jn].backpressure&&transformStreamSetBackpressure(C,!0)}function transformStreamDefaultControllerError(n,S){transformStreamError(n[Jn].stream,S)}async function transformStreamDefaultControllerPerformTransform(n,S){try{let C=n[Jn].transformAlgorithm;if(C===void 0)return;await C(S,n)}catch(S){throw transformStreamError(n[Jn].stream,S),S}}function transformStreamDefaultControllerTerminate(n){let{stream:S}=n[Jn],{readable:C}=S[Jn];readableStreamDefaultControllerClose(C[Jn].controller),transformStreamErrorWritableAndUnblockWrite(S,TypeError(`TransformStream has been terminated`))}function transformStreamDefaultSinkWriteAlgorithm(n,S){let{controller:C}=n[Jn];return n[Jn].backpressure?n[Jn].backpressureChange.promise.then(()=>{let{writable:N}=n[Jn];if(N[Jn].state===`erroring`)throw N[Jn].storedError;return transformStreamDefaultControllerPerformTransform(C,S)}):transformStreamDefaultControllerPerformTransform(C,S)}async function transformStreamDefaultSinkAbortAlgorithm(n,S){let{controller:C,readable:N}=n[Jn];if(C[Jn].finishPromise!==void 0)return C[Jn].finishPromise;let{promise:F,resolve:I,reject:H}=Promise.withResolvers();C[Jn].finishPromise=F;let W=C[Jn].cancelAlgorithm(S);return transformStreamDefaultControllerClearAlgorithms(C),W.then(()=>{N[Jn].state===`errored`?H(N[Jn].storedError):(readableStreamDefaultControllerError(N[Jn].controller,S),I())},n=>{readableStreamDefaultControllerError(N[Jn].controller,n),H(n)}),C[Jn].finishPromise}function transformStreamDefaultSinkCloseAlgorithm(n){let{readable:S,controller:C}=n[Jn];if(C[Jn].finishPromise!==void 0)return C[Jn].finishPromise;let{promise:N,resolve:F,reject:I}=Promise.withResolvers();C[Jn].finishPromise=N;let H=C[Jn].flushAlgorithm(C);return transformStreamDefaultControllerClearAlgorithms(C),H.then(()=>{S[Jn].state===`errored`?I(S[Jn].storedError):(readableStreamDefaultControllerClose(S[Jn].controller),F())},n=>{readableStreamDefaultControllerError(S[Jn].controller,n),I(n)}),C[Jn].finishPromise}function transformStreamDefaultSourcePullAlgorithm(n){return transformStreamSetBackpressure(n,!1),n[Jn].backpressureChange.promise}function transformStreamDefaultSourceCancelAlgorithm(n,S){let{controller:C,writable:N}=n[Jn];if(C[Jn].finishPromise!==void 0)return C[Jn].finishPromise;let{promise:F,resolve:I,reject:H}=Promise.withResolvers();C[Jn].finishPromise=F;let W=C[Jn].cancelAlgorithm(S);return transformStreamDefaultControllerClearAlgorithms(C),W.then(()=>{N[Jn].state===`errored`?H(N[Jn].storedError):(writableStreamDefaultControllerErrorIfNeeded(N[Jn].controller,S),transformStreamUnblockWrite(n),I())},S=>{writableStreamDefaultControllerErrorIfNeeded(N[Jn].controller,S),transformStreamUnblockWrite(n),H(S)}),C[Jn].finishPromise}const Tr=Object.defineProperty(n=>n.byteLength,"name",{value:`size`}),Er=Object.defineProperty(()=>1,"name",{value:`size`});var ByteLengthQueuingStrategy=class{#e;constructor(n){if(typeof n!=`object`||!n)throw TypeError(`init must be an object`);if(n.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+n.highWaterMark}get highWaterMark(){return this.#e}get size(){return Tr}get[Symbol.toStringTag](){return`ByteLengthQueuingStrategy`}},CountQueuingStrategy=class{#e;constructor(n){if(typeof n!=`object`||!n)throw TypeError(`init must be an object`);if(n.highWaterMark===void 0)throw TypeError(`init.highWaterMark is required`);this.#e=+n.highWaterMark}get highWaterMark(){return this.#e}get size(){return Er}get[Symbol.toStringTag](){return`CountQueuingStrategy`}},TextEncoderStream=class{#e=null;#t=new TextEncoder;#n;constructor(){this.#n=new TransformStream({transform:(n,S)=>{if(n=String(n),n===``)return;this.#e!==null&&(n=this.#e+n);let C=n.charCodeAt(n.length-1);55296<=C&&C<=56319?(this.#e=n.slice(-1),n=n.slice(0,-1)):this.#e=null,n&&S.enqueue(this.#t.encode(n))},flush:n=>{this.#e!==null&&n.enqueue(new Uint8Array([239,191,189]))}})}get encoding(){return`utf-8`}get readable(){return this.#n.readable}get writable(){return this.#n.writable}};function hasStreamingSupport(){try{return new TextDecoder().decode(new Uint8Array([195]),{stream:!0}),!0}catch{return!1}}const Dr=hasStreamingSupport();function incompleteUtf8Tail$1(n){let S=n.length;if(S===0)return 0;for(let C=1;C<=Math.min(3,S);C++){let N=n[S-C];if(!(N&128))return 0;if((N&192)!=128){let n;if((N&224)==192)n=2;else if((N&240)==224)n=3;else if((N&248)==240)n=4;else return 0;return C<n?C:0}}return 0}__name$1(incompleteUtf8Tail$1,`incompleteUtf8Tail`);var TextDecoderStream=class{#e;#t;constructor(n,S){if(this.#e=new TextDecoder(n,S),Dr)this.#t=new TransformStream({transform:(n,S)=>{let C=toUint8Array$3(n),N=this.#e.decode(C,{stream:!0});N&&S.enqueue(N)},flush:n=>{let S=this.#e.decode();S&&n.enqueue(S)},cancel:()=>{this.#e.decode()}});else{let n=new Uint8Array;this.#t=new TransformStream({transform:(S,C)=>{let N=toUint8Array$3(S),F;n.length>0?(F=new Uint8Array(n.length+N.length),F.set(n,0),F.set(N,n.length)):F=N;let I=incompleteUtf8Tail$1(F),H;if(I>0?(H=F.slice(0,F.length-I),n=F.slice(F.length-I)):(H=F,n=new Uint8Array),H.length>0){let n=this.#e.decode(H);n&&C.enqueue(n)}},flush:S=>{if(n.length>0){let C=this.#e.decode(n);C&&S.enqueue(C),n=new Uint8Array}},cancel:()=>{n=new Uint8Array}})}}get encoding(){return this.#e.encoding}get fatal(){return this.#e.fatal}get ignoreBOM(){return this.#e.ignoreBOM}get readable(){return this.#t.readable}get writable(){return this.#t.writable}};function toUint8Array$3(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);throw TypeError(`chunk must be a BufferSource`)}__name$1(toUint8Array$3,`toUint8Array`);function isNativeStreamUsable$3(n,S){try{return typeof n==`function`?typeof n.prototype?.[S]==`function`:!1}catch{return!1}}__name$1(isNativeStreamUsable$3,`isNativeStreamUsable`);const Or=isNativeStreamUsable$3(globalThis.ReadableStream,`getReader`)?globalThis.ReadableStream:ReadableStream$1,kr=isNativeStreamUsable$3(globalThis.WritableStream,`getWriter`)?globalThis.WritableStream:WritableStream,Ar=isNativeStreamUsable$3(globalThis.TransformStream,`readable`)?globalThis.TransformStream:TransformStream,jr=typeof globalThis.ByteLengthQueuingStrategy==`function`?globalThis.ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,Mr=typeof globalThis.CountQueuingStrategy==`function`?globalThis.CountQueuingStrategy:CountQueuingStrategy,Nr=typeof globalThis.TextEncoderStream==`function`?globalThis.TextEncoderStream:TextEncoderStream,Pr=typeof globalThis.TextDecoderStream==`function`?globalThis.TextDecoderStream:TextDecoderStream;var Fr,Ir=__esmMin(()=>{Fr=S}),Lr,Rr=__esmMin(()=>{Ir(),Lr=Fr});function getGioFormat(n){switch(n){case`gzip`:return Lr.ZlibCompressorFormat.GZIP;case`deflate`:return Lr.ZlibCompressorFormat.ZLIB;case`deflate-raw`:return Lr.ZlibCompressorFormat.RAW}}function concat$2(n){let S=n.reduce((n,S)=>n+S.length,0),C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}function compressWithGio(n,S){let C=new Lr.ZlibCompressor({format:getGioFormat(S)}),N=new Lr.ConverterOutputStream({base_stream:Lr.MemoryOutputStream.new_resizable(),converter:C});N.write_bytes(new ft.Bytes(n),null),N.close(null);let F=N.get_base_stream().steal_as_bytes();return new Uint8Array(F.get_data()??[])}function decompressStreamWithGio(n,S){let C=new Lr.ZlibDecompressor({format:getGioFormat(S)}),N=Lr.MemoryInputStream.new_from_bytes(new ft.Bytes(n)),F=new Lr.ConverterInputStream({base_stream:N,converter:C}),I=[];for(;;){let n=F.read_bytes(Br,null);if(n.get_size()===0)break;I.push(new Uint8Array(n.get_data()))}return F.close(null),concat$2(I)}function findGzipMemberEnd(n){let S=new Lr.ZlibDecompressor({format:Lr.ZlibCompressorFormat.GZIP}),C=new Uint8Array(262144),N=0;for(;;){let F=n.subarray(N,N+zr);try{let[n,I,H]=S.convert(F,C,Lr.ConverterFlags.NONE);if(N+=I,n===Lr.ConverterResult.FINISHED||I===0&&H===0)return N}catch{return N}}}function gunzipWithGio(n){let S=[],C=0;for(;C<n.length&&!(n.length-C<2||n[C]!==31||n[C+1]!==139);){let N=n.subarray(C),F=findGzipMemberEnd(N);if(F<=0)break;S.push(decompressStreamWithGio(N.subarray(0,F),`gzip`)),C+=F}return S.length===0?decompressStreamWithGio(n,`gzip`):concat$2(S)}var zr,Br,Vr=__esmMin(()=>{Rr(),pt(),zr=256*1024,Br=1024*1024,__name$1(concat$2,`concat`)}),Hr=__esmMin(()=>{Be()});function _setPipeImpl(n){Ur=n}var Ur,Stream_,Wr=__esmMin(()=>{Kt(),Stream_=class extends Ft{constructor(n){super(n)}pipe(n,S){return Ur(this,n,S)}}});function finished$1(n,S,C){let N;N=typeof S==`function`?S:C;let F=!1;function done(n){F||(F=!0,N(n))}let onFinish=()=>done(),onEnd=()=>done(),onError=n=>done(n),onClose=()=>{let S=n,C=n;!S.writableFinished&&!C.readableEnded&&done(Error(`premature close`))};n.on(`finish`,onFinish),n.on(`end`,onEnd),n.on(`error`,onError),n.on(`close`,onClose);let I=n,H=typeof n.write==`function`,W=typeof n.read==`function`,q=I.writableFinished===!0,Y=I.readableEnded===!0;if(I.destroyed===!0){let n=I._err;be(n?()=>done(n):H&&q||W&&Y?()=>done():()=>done(Error(`premature close`)))}else(H&&!W&&q||!H&&W&&Y||H&&W&&q&&Y)&&be(()=>done());return function cleanup(){n.removeListener(`finish`,onFinish),n.removeListener(`end`,onEnd),n.removeListener(`error`,onError),n.removeListener(`close`,onClose)}}function addAbortSignal(n,S){if(!(n instanceof AbortSignal))throw TypeError(`The first argument must be an AbortSignal`);if(!(S instanceof Stream_))throw TypeError(`The second argument must be a Stream`);let C=S;if(n.aborted)C.destroy(Error(`The operation was aborted`));else{let onAbort=()=>{C.destroy(Error(`The operation was aborted`))};n.addEventListener(`abort`,onAbort,{once:!0}),S.once(`close`,()=>{n.removeEventListener(`abort`,onAbort)})}return S}function isReadable(n){if(n==null)return!1;let S=n;return typeof S.readable!=`boolean`||typeof S.read!=`function`||S.destroyed===!0||S.readableEnded===!0?!1:S.readable===!0}function isWritable(n){if(n==null)return!1;let S=n;return typeof S.writable!=`boolean`||typeof S.write!=`function`||S.destroyed===!0||S.writableEnded===!0?!1:S.writable===!0}function isDestroyed(n){return n==null?!1:n.destroyed===!0}function isDisturbed(n){if(n==null)return!1;let S=n;return S.readableDidRead===!0||S.readableFlowing!==null&&S.readableFlowing!==void 0}function isErrored(n){if(n==null)return!1;let S=n;return S.destroyed===!0&&typeof S.readable==`boolean`&&S.readable===!1||S.destroyed===!0&&typeof S.writable==`boolean`&&S.writable===!1}var Gr=__esmMin(()=>{Wr(),Be(),__name$1(finished$1,`finished`)});function getDefaultHighWaterMark(n){return n?qr:Kr}function setDefaultHighWaterMark(n,S){if(typeof S!=`number`||S<0||Number.isNaN(S))throw TypeError(`Invalid highWaterMark: ${S}`);n?qr=S:Kr=S}function validateHighWaterMark(n,S){if(S!==void 0&&(typeof S!=`number`||Number.isNaN(S))){let C=TypeError(`The value of "${n}" is invalid. Received ${S}`);throw C.code=`ERR_INVALID_ARG_VALUE`,C}}var Kr,qr,Jr=__esmMin(()=>{Kr=16384,qr=16});function createAbortError(){let n=Error(`The operation was aborted`);return n.name=`AbortError`,n.code=`ABORT_ERR`,n}async function streamAsyncDispose(n,S){let C;n.destroyed||(C=S?void 0:createAbortError(),n.destroy(C)),await new Promise((S,N)=>{finished$1(n,n=>{n&&n!==C?N(n):S()})})}var Yr,Xr=__esmMin(()=>{Gr(),Yr=Symbol.asyncDispose??Symbol.for(`Symbol.asyncDispose`)});function chunkLength(n){if(n==null)return 1;let S=n.length;return typeof S==`number`?S:1}function sliceChunk(n,S,C){if(typeof n==`string`)return C===void 0?n.slice(S):n.slice(S,C);let N=n.slice;return typeof N==`function`?N.call(n,S,C):n}var Zr,Qr=__esmMin(()=>{Wr(),Xr(),Jr(),Be(),Zr=class Readable_ extends Stream_{readable=!0;readableFlowing=null;readableLength=0;readableHighWaterMark;readableEncoding;readableObjectMode;readableEnded=!1;readableAborted=!1;destroyed=!1;_pipeDests=[];_buffer=[];_readableState={ended:!1,endEmitted:!1,reading:!1,constructed:!0,highWaterMark:0,objectMode:!1,pipes:[]};_err;_readablePending=!1;_readImpl;_destroyImpl;_constructImpl;constructor(n){super(n),this.readableHighWaterMark=n?.highWaterMark??getDefaultHighWaterMark(n?.objectMode??!1),this.readableEncoding=n?.encoding??null,this.readableObjectMode=n?.objectMode??!1,this._readableState.highWaterMark=this.readableHighWaterMark,this._readableState.objectMode=this.readableObjectMode,n?.read&&(this._readImpl=n.read),n?.destroy&&(this._destroyImpl=n.destroy),n?.construct&&(this._constructImpl=n.construct),(this._constructImpl||this._construct!==Readable_.prototype._construct)&&(this._readableState.constructed=!1,nextTick(()=>{this._construct(n=>{this._readableState.constructed=!0,n?this.destroy(n):this.readableFlowing===!0&&this._flow()})}))}_construct(n){this._constructImpl?this._constructImpl.call(this,n):n()}_read(n){this._readImpl&&this._readImpl.call(this,n)}read(n){if(!this._readableState.constructed)return null;if(this._buffer.length===0){if(this._readableState.ended)return null;this._readableState.reading=!0,this._read(n??this.readableHighWaterMark),this._readableState.reading=!1}if(this._buffer.length===0||n===0)return null;if(this.readableObjectMode){if(n===void 0){let n=this._buffer.shift();return--this.readableLength,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),n}if(n>this.readableLength)return null;let S=this._buffer.shift();return--this.readableLength,S}if(n!=null)return n>this.readableLength?null:this._readBytes(n);let S=this._buffer.splice(0);if(this.readableLength=0,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),S.length===1)return S[0];if(S.length===0)return null;if(typeof S[0]==`string`)return S.join(``);let C=globalThis.Buffer;return C?.concat?C.concat(S):S}_readBytes(n){let S=0,C=[];for(;S<n&&this._buffer.length>0;){let N=this._buffer[0],F=chunkLength(N);if(S+F<=n)C.push(this._buffer.shift()),S+=F,this.readableLength-=F;else{let F=n-S;C.push(sliceChunk(N,0,F)),this._buffer[0]=sliceChunk(N,F),this.readableLength-=F,S+=F}}if(C.length===1)return C[0];let N=globalThis.Buffer;return N?.concat?N.concat(C):C}push(n,S){if(n===null)return this._readableState.ended=!0,this.readableEnded=!0,this._buffer.length===0&&!this._readableState.endEmitted&&nextTick(()=>this._emitEnd()),this._scheduleReadable(),!1;if(!this.readableObjectMode&&!(typeof n==`string`||ArrayBuffer.isView(n))){let S=Object.assign(TypeError(`Invalid non-string/buffer chunk type: ${typeof n}`),{code:`ERR_INVALID_ARG_TYPE`});return nextTick(()=>this.emit(`error`,S)),!1}return this._buffer.push(n),this.readableLength+=this.readableObjectMode?1:chunkLength(n),this.readableFlowing&&!this._flowing&&nextTick(()=>this._flow()),this.readableFlowing!==!0&&this._scheduleReadable(),this.readableLength<this.readableHighWaterMark}_emitEnd(){this._readableState.endEmitted||(this._readableState.endEmitted=!0,this.emit(`end`),nextTick(()=>this._autoClose()))}_autoClose(){this.emit(`close`)}_scheduleReadable(){this._readablePending||this.listenerCount(`readable`)===0||(this._readablePending=!0,nextTick(()=>{this._readablePending=!1,this.destroyed||this.emit(`readable`)}))}on(n,S){return super.on(n,S),n===`data`&&this.readableFlowing!==!1&&this.resume(),n===`readable`&&(this._buffer.length>0||this._readableState.ended)&&this._scheduleReadable(),this}unshift(n){this._buffer.unshift(n),this.readableLength+=this.readableObjectMode?1:chunkLength(n)}setEncoding(n){return this.readableEncoding=n,this}pause(){return this.readableFlowing=!1,this.emit(`pause`),this}resume(){return this.readableFlowing!==!0&&(this.readableFlowing=!0,this.emit(`resume`),this._readableState.constructed&&this._flow()),this}_flowing=!1;_flow(){if(!(this.readableFlowing!==!0||this._flowing||this.destroyed)&&this._readableState.constructed){this._flowing=!0;try{for(;this._buffer.length>0&&this.readableFlowing&&!this.destroyed;){let n=this._buffer.shift();if(this.readableLength-=this.readableObjectMode?1:chunkLength(n),this.readableEncoding&&typeof n!=`string`){let S=globalThis.Buffer;S?.isBuffer&&S.isBuffer(n)?n=n.toString(this.readableEncoding):n instanceof Uint8Array&&(n=new TextDecoder(this.readableEncoding).decode(n))}this.emit(`data`,n)}if(this.destroyed)return;if(this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted){nextTick(()=>this._emitEnd());return}!this._readableState.ended&&!this._readableState.reading&&!this.destroyed&&(this._readableState.reading=!0,this._read(this.readableHighWaterMark),this._readableState.reading=!1)}finally{this._flowing=!1}this._buffer.length>0&&this.readableFlowing&&!this.destroyed&&nextTick(()=>this._flow())}}isPaused(){return this.readableFlowing===!1}unpipe(n){if(n){let S=this._pipeDests.findIndex(S=>S.dest===n);if(S!==-1){this._pipeDests[S].cleanup(),this._pipeDests.splice(S,1);let C=this._readableState.pipes.indexOf(n);C!==-1&&this._readableState.pipes.splice(C,1),n.emit(`unpipe`,this),this._pipeDests.length===0&&(this.readableFlowing=!1)}}else{for(let n of this._pipeDests)n.cleanup(),n.dest.emit(`unpipe`,this);this._pipeDests=[],this._readableState.pipes=[],this.readableFlowing=!1}return this}_destroy(n,S){this._destroyImpl?this._destroyImpl.call(this,n,S):S(n??void 0)}destroy(n){if(this.destroyed)return this;this.destroyed=!0,this.readable=!1,this.readableAborted=!this.readableEnded,n&&(this._err=n);let cb=n=>{n&&nextTick(()=>this.emit(`error`,n)),nextTick(()=>this.emit(`close`))};return Object.prototype.hasOwnProperty.call(this,`_destroy`)?this._destroy(n??null,cb):this._destroyImpl?this._destroyImpl.call(this,n??null,cb):cb(n),this}static toWeb(n){return new ReadableStream({start(S){n.on(`data`,n=>{typeof n==`string`?S.enqueue(new TextEncoder().encode(n)):n instanceof Uint8Array?S.enqueue(n):n&&typeof n.length==`number`&&S.enqueue(new Uint8Array(n))}),n.on(`end`,()=>{S.close()}),n.on(`error`,n=>{S.error(n)})},cancel(){n.destroy()}})}static fromWeb(n,S){let C=n.getReader();return new Readable_({...S,read(){C.read().then(({done:n,value:S})=>{n?this.push(null):this.push(S)},n=>{this.destroy(n)})},destroy(n,S){C.cancel(n?.message).then(()=>S(null),S)}})}[Symbol.asyncIterator](){let n=this,S=[],C=!1,N=null,F=null,I=null;return n.on(`data`,n=>{if(F){let S=F;F=null,I=null,S({value:n,done:!1})}else S.push(n)}),n.on(`end`,()=>{if(C=!0,F){let n=F;F=null,I=null,n({value:void 0,done:!0})}}),n.on(`error`,n=>{if(N=n,C=!0,I){let S=I;F=null,I=null,S(n)}}),{next(){return N?Promise.reject(N):S.length>0?Promise.resolve({value:S.shift(),done:!1}):C?Promise.resolve({value:void 0,done:!0}):new Promise((n,S)=>{F=n,I=S})},return(){return n.destroy(),Promise.resolve({value:void 0,done:!0})},[Symbol.asyncIterator](){return this}}}static from(n,S){let C=new Readable_({objectMode:!0,...S,read(){}});return typeof n==`string`||ArrayBuffer.isView(n)?(C.push(n),C.push(null),C):((async()=>{try{for await(let S of n)C.push(S)||await new Promise(n=>C.once(`drain`,n));C.push(null)}catch(n){C.destroy(n)}})(),C)}},Zr.prototype[Yr]=function(){return streamAsyncDispose(this,this.readableEnded)}});function chunkLen$1(n){if(n==null)return 1;let S=n.length;return typeof S==`number`?S:1}var Duplex_,$r=__esmMin(()=>{Jr(),Qr(),Be(),Duplex_=class extends Zr{writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;allowHalfOpen;_decodeStrings;_writableState={highWaterMark:0,objectMode:!1};_duplexCorkedBuffer=[];_duplexWriting=!1;_duplexWriteQueue=[];_writeImpl;_finalImpl;_defaultEncoding=`utf8`;_pendingWrites=0;_pendingEndCb=null;constructor(n){super(n),validateHighWaterMark(`writableHighWaterMark`,n?.writableHighWaterMark),validateHighWaterMark(`readableHighWaterMark`,n?.readableHighWaterMark),this.writableObjectMode=n?.writableObjectMode??n?.objectMode??!1,this.writableHighWaterMark=n?.highWaterMark??n?.writableHighWaterMark??getDefaultHighWaterMark(this.writableObjectMode),this._writableState.highWaterMark=this.writableHighWaterMark,this._writableState.objectMode=this.writableObjectMode,n?.highWaterMark===void 0&&n?.readableHighWaterMark!==void 0&&(this.readableHighWaterMark=n.readableHighWaterMark,this._readableState.highWaterMark=n.readableHighWaterMark),n?.readableObjectMode!==void 0&&(this.readableObjectMode=n.readableObjectMode,this._readableState.objectMode=n.readableObjectMode,n?.readableHighWaterMark===void 0&&n?.highWaterMark===void 0&&(this.readableHighWaterMark=getDefaultHighWaterMark(n.readableObjectMode),this._readableState.highWaterMark=this.readableHighWaterMark)),this.allowHalfOpen=n?.allowHalfOpen!==!1,this._decodeStrings=n?.decodeStrings!==!1,n?.write&&(this._writeImpl=n.write),n?.final&&(this._finalImpl=n.final),this.allowHalfOpen||this.once(`end`,()=>{this.writableEnded||nextTick(()=>this.end())})}_write(n,S,C){this._writeImpl?this._writeImpl.call(this,n,S,C):C()}_final(n){this._finalImpl?this._finalImpl.call(this,n):n()}destroy(n){return this.destroyed?this:(this.writable=!1,super.destroy(n))}write(n,S,C){let N,F;if(typeof S==`function`?(N=S,F=this._defaultEncoding):(F=S??this._defaultEncoding,N=C??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof n==`string`){let S=globalThis.Buffer;S&&(n=S.from(n,F),F=`buffer`)}if(typeof n!=`string`&&!this.writableObjectMode){let S=globalThis.Buffer;(S&&S.isBuffer(n)||n instanceof Uint8Array)&&(F=`buffer`)}if(this.writableEnded){let n=Error(`write after end`);return nextTick(()=>{N(n),this.emit(`error`,n)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen$1(n),this.writableCorked>0)return this._duplexCorkedBuffer.push({chunk:n,encoding:F,callback:N}),this.writableLength<this.writableHighWaterMark;let I=this.writableLength<this.writableHighWaterMark;return I||(this.writableNeedDrain=!0),this._duplexDoWrite(n,F,N),I}_duplexDoWrite(n,S,C){if(this._duplexWriting){this._duplexWriteQueue.push({chunk:n,encoding:S,callback:C});return}this._duplexWriting=!0,this._duplexStartWrite(n,S,C)}_duplexStartWrite(n,S,C){this._pendingWrites++,this._write(n,S,S=>{this._pendingWrites--,this.writableLength-=this.writableObjectMode?1:chunkLen$1(n),nextTick(S?()=>{if(C(S),this._duplexWriting=!1,this.emit(`error`,S),this._duplexWriteQueue.length>0){let n=this._duplexWriteQueue.shift();this._duplexWriting=!0,this._duplexStartWrite(n.chunk,n.encoding,n.callback)}}:()=>{if(C(),this._duplexWriteQueue.length>0){let n=this._duplexWriteQueue.shift();this._duplexStartWrite(n.chunk,n.encoding,n.callback);return}if(this._duplexWriting=!1,this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._pendingWrites===0&&this._pendingEndCb){let n=this._pendingEndCb;this._pendingEndCb=null,n()}})})}end(n,S,C){typeof n==`function`&&(C=n,n=void 0),typeof S==`function`&&(C=S,S=void 0),n!=null&&this.write(n,S),this.writableEnded=!0;let doFinal=()=>{this._final(n=>{this.writableFinished=!0,this._doPrefinishHooks(()=>{nextTick(()=>{n&&this.emit(`error`,n),this.emit(`finish`),nextTick(()=>this.emit(`close`)),C&&C()})})})};return this._pendingWrites>0||this._duplexWriting||this._duplexWriteQueue.length>0?this._pendingEndCb=doFinal:doFinal(),this}_doPrefinishHooks(n){n()}cork(){this.writableCorked++}uncork(){if(this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._duplexCorkedBuffer.length>0)){let n=this._duplexCorkedBuffer.splice(0);for(let{chunk:S,encoding:C,callback:N}of n)this._write(S,C,n=>{this.writableLength-=this.writableObjectMode?1:chunkLen$1(S),n?(N(n),this.emit(`error`,n)):N()});this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,nextTick(()=>this.emit(`drain`)))}}setDefaultEncoding(n){return this._defaultEncoding=n,this}},__name$1(chunkLen$1,`chunkLen`)});function pipe(n,S,C){let N=n,F=C?.end!==!1,I=!1,ondrain=()=>{I=!1,S.removeListener(`drain`,ondrain);let n=N;typeof n.resume==`function`&&n.resume()},ondata=n=>{if(S.writable){let C=N;S.write(n)===!1&&typeof C.pause==`function`&&(C.pause(),I||(I=!0,S.on(`drain`,ondrain)))}};N.on(`data`,ondata);let H=!1,onend=()=>{H||(H=!0,F&&S.end())},onclose=()=>{if(!H&&(H=!0,F&&!(N instanceof Zr))){let n=S;typeof n.destroy==`function`&&n.destroy()}};F&&(N.on(`end`,onend),N.on(`close`,onclose));let cleanup=()=>{N.removeListener(`data`,ondata),I&&S.removeListener(`drain`,ondrain),N.removeListener(`end`,onend),N.removeListener(`close`,onclose),N.removeListener(`end`,cleanup),N.removeListener(`close`,cleanup),S.removeListener(`close`,cleanup)};return N.on(`end`,cleanup),N.on(`close`,cleanup),S.on(`close`,cleanup),N instanceof Zr&&(N._pipeDests.push({dest:S,cleanup}),N._readableState.pipes.push(S)),S.emit(`pipe`,N),S}var ei=__esmMin(()=>{Wr(),Qr(),_setPipeImpl(pipe)});function chunkLen(n){if(n==null)return 1;let S=n.length;return typeof S==`number`?S:1}var ti,ni=__esmMin(()=>{Wr(),Xr(),Jr(),Be(),ti=class Writable_ extends Stream_{static[Symbol.hasInstance](n){let S=this;return S.prototype!==void 0&&Object.prototype.isPrototypeOf.call(S.prototype,n)?!0:S.prototype!==Writable_.prototype||n==null?!1:typeof n.writableHighWaterMark==`number`}writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;destroyed=!1;_err;_writableState={ended:!1,finished:!1,constructed:!0,writing:!1};_corkedBuffer=[];_writeBuffer=[];_pendingConstruct=[];_ending=!1;_endCallback;_pendingEnd=null;_writeImpl;_writev;_finalImpl;_destroyImpl;_constructImpl;_decodeStrings;_defaultEncoding=`utf8`;_autoDestroy;constructor(n){super(n),this.writableHighWaterMark=n?.highWaterMark??getDefaultHighWaterMark(n?.objectMode??!1),this.writableObjectMode=n?.objectMode??!1,this._decodeStrings=n?.decodeStrings!==!1,this._autoDestroy=n?.autoDestroy!==!1,n?.write&&(this._writeImpl=n.write),n?.writev&&(this._writev=n.writev),n?.final&&(this._finalImpl=n.final),n?.destroy&&(this._destroyImpl=n.destroy),n?.construct&&(this._constructImpl=n.construct),(this._constructImpl||this._construct!==Writable_.prototype._construct)&&(this._writableState.constructed=!1,nextTick(()=>{this._construct(n=>{this._writableState.constructed=!0,n?this.destroy(n):this._maybeFlush()})}))}_construct(n){this._constructImpl?this._constructImpl.call(this,n):n()}_write(n,S,C){this._writeImpl?this._writeImpl.call(this,n,S,C):C()}_final(n){this._finalImpl?this._finalImpl.call(this,n):n()}_destroy(n,S){this._destroyImpl?this._destroyImpl.call(this,n,S):S(n)}_maybeFlush(){let n=this._pendingConstruct.splice(0);if(n.length>0){let[S,...C]=n;this._writeBuffer.push(...C),this._doWrite(S.chunk,S.encoding,S.callback)}if(this._pendingEnd){let{chunk:n,encoding:S,callback:C}=this._pendingEnd;this._pendingEnd=null,this._doEnd(n,S,C)}}_doWrite(n,S,C){this._writableState.writing=!0;let N=!0;this._write(n,S,S=>{if(this.writableLength-=this.writableObjectMode?1:chunkLen(n),N){nextTick(()=>{if(S){C(S),this.emit(`error`,S);return}C(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}),S||this._drainWriteBuffer();return}nextTick(S?()=>{C(S),this.emit(`error`,S),this._drainWriteBuffer()}:()=>{C(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._drainWriteBuffer()})}),N=!1}_drainWriteBuffer(){if(this._writeBuffer.length>0){let n=this._writeBuffer.shift();this._doWrite(n.chunk,n.encoding,n.callback)}else this._writableState.writing=!1,this._maybeFinish()}_maybeFinish(){!this._ending||this._writableState.finished||this._writableState.writing||this._writeBuffer.length>0||(this._ending=!1,this._final(n=>{this.writableFinished=!0,this._writableState.finished=!0,nextTick(()=>{n&&this.emit(`error`,n),this.emit(`finish`),this._autoDestroy?this.destroy():nextTick(()=>this.emit(`close`)),this._endCallback&&this._endCallback()})}))}write(n,S,C){let N,F;if(typeof S==`function`?(N=S,F=this._defaultEncoding):(F=S??this._defaultEncoding,N=C??(()=>{})),this._decodeStrings&&!this.writableObjectMode&&typeof n==`string`){let S=globalThis.Buffer;S&&(n=S.from(n,F),F=`buffer`)}if(typeof n!=`string`&&!this.writableObjectMode){let S=globalThis.Buffer;(S&&S.isBuffer(n)||n instanceof Uint8Array)&&(F=`buffer`)}if(this.writableEnded){let n=Error(`write after end`);return nextTick(()=>{N(n),this.emit(`error`,n)}),!1}if(this.writableLength+=this.writableObjectMode?1:chunkLen(n),this.writableCorked>0)return this._corkedBuffer.push({chunk:n,encoding:F,callback:N}),this.writableLength<this.writableHighWaterMark;if(!this._writableState.constructed)return this._pendingConstruct.push({chunk:n,encoding:F,callback:N}),this.writableLength<this.writableHighWaterMark;let I=this.writableLength<this.writableHighWaterMark;return I||(this.writableNeedDrain=!0),this._writableState.writing?this._writeBuffer.push({chunk:n,encoding:F,callback:N}):this._doWrite(n,F,N),I}_doEnd(n,S,C){n!=null&&this.write(n,S),this.writableEnded=!0,this._writableState.ended=!0,this._ending=!0,this._endCallback=C,this._maybeFinish()}end(n,S,C){return typeof n==`function`&&(C=n,n=void 0),typeof S==`function`&&(C=S,S=void 0),this.writableEnded?(C&&nextTick(C),this):this._writableState.constructed?(this._doEnd(n,S,C),this):(this._pendingEnd={chunk:n,encoding:S,callback:C},this)}cork(){this.writableCorked++}uncork(){this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._corkedBuffer.length>0&&this._flushCorkedBuffer())}_flushCorkedBuffer(){if(this._writev&&this._corkedBuffer.length>1){let n=this._corkedBuffer.splice(0),S=n.map(n=>({chunk:n.chunk,encoding:n.encoding}));this._writev.call(this,S,S=>{for(let S of n)this.writableLength-=this.writableObjectMode?1:chunkLen(S.chunk);if(S){for(let C of n)C.callback(S);this.emit(`error`,S)}else{for(let S of n)S.callback();this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}})}else{let n=this._corkedBuffer.splice(0);if(n.length>0){let[S,...C]=n;this._writeBuffer.push(...C),this._doWrite(S.chunk,S.encoding,S.callback)}}}setDefaultEncoding(n){return this._defaultEncoding=n,this}destroy(n){if(this.destroyed)return this;this.destroyed=!0,this.writable=!1,n&&(this._err=n);let cb=n=>{n&&nextTick(()=>this.emit(`error`,n)),nextTick(()=>this.emit(`close`))};return this._destroy(n??null,cb),this}},ti.prototype[Yr]=function(){return streamAsyncDispose(this,this.writableFinished)}}),ri,ii=__esmMin(()=>{$r(),Be(),ri=class Transform_ extends Duplex_{constructor(n){super({...n,write:void 0,final:void 0});let S=this;n?.transform&&(S._transform=n.transform),n?.flush&&(S._flush=n.flush),n?.final&&(S._final=n.final)}_transform(n,S,C){throw Object.assign(Error(`The _transform() method is not implemented`),{code:`ERR_METHOD_NOT_IMPLEMENTED`})}_flush(n){n()}_write(n,S,C){let N=!1;try{this._transform(n,S,(n,S)=>{if(N){let n=Object.assign(Error(`Callback called multiple times`),{code:`ERR_MULTIPLE_CALLBACK`});nextTick(()=>this.emit(`error`,n));return}if(N=!0,n){C(n);return}S!=null&&this.push(S),C()})}catch(n){if(n?.code===`ERR_METHOD_NOT_IMPLEMENTED`)throw n;C(n)}}_final(n){this._flush((S,C)=>{if(S){n(S);return}C!=null&&this.push(C),this.push(null),n()})}_doPrefinishHooks(n){let S=Transform_.prototype._final;this._final===S?n():S.call(this,n)}}}),PassThrough_,ai=__esmMin(()=>{ii(),PassThrough_=class extends ri{constructor(n){super({...n,transform(n,S,C){C(null,n)}})}}});function pipeline(...n){let S=n,C=typeof S[S.length-1]==`function`?S.pop():void 0,N=S;if(N.length<2)throw Error(`pipeline requires at least 2 streams`);let F=null;function onError(n){if(!F){F=n;for(let n of N)typeof n.destroy==`function`&&n.destroy();C&&C(n)}}let I=N[0];for(let n=1;n<N.length;n++){let S=N[n];I.pipe(S),I.on(`error`,onError),I=S}let H=N[N.length-1];return H.on(`error`,onError),H.on(`finish`,()=>{C&&!F&&C(null)}),H}var oi=__esmMin(()=>{}),si=__exportAll$4({Duplex:()=>fi,PassThrough:()=>mi,Readable:()=>li,Stream:()=>ci,Transform:()=>pi,Writable:()=>di,addAbortSignal:()=>addAbortSignal,default:()=>hi,finished:()=>finished$1,getDefaultHighWaterMark:()=>getDefaultHighWaterMark,isDestroyed:()=>isDestroyed,isDisturbed:()=>isDisturbed,isErrored:()=>isErrored,isReadable:()=>isReadable,isWritable:()=>isWritable,"module.exports":()=>hi,pipeline:()=>pipeline,setDefaultHighWaterMark:()=>setDefaultHighWaterMark}),ci,li,di,fi,pi,mi,hi,gi=__esmMin(()=>{Hr(),Wr(),Gr(),Jr(),Qr(),$r(),ei(),ni(),ii(),ai(),oi(),ci=makeCallable(Stream_),li=makeCallable(Zr),di=makeCallable(ti),fi=makeCallable(Duplex_),pi=makeCallable(ri),mi=makeCallable(PassThrough_),hi=Object.assign(ci,{Stream:ci,Readable:li,Writable:di,Duplex:fi,Transform:pi,PassThrough:mi,pipeline,finished:finished$1,addAbortSignal,isReadable,isWritable,isDestroyed,isDisturbed,isErrored,getDefaultHighWaterMark,setDefaultHighWaterMark})});function toUint8Array$2(n){return typeof n==`string`?new TextEncoder().encode(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function concat$1(n){let S=n.reduce((n,S)=>n+S.length,0),C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}function createGzip(n){return new Gzip(n)}function createGunzip(n){return new Gunzip(n)}function createDeflate(n){return new Deflate(n)}function createInflate(n){return new Inflate(n)}function createDeflateRaw(n){return new DeflateRaw(n)}function createInflateRaw(n){return new InflateRaw(n)}function createUnzip(n){return new Unzip(n)}function createBrotliCompress(n){throw Error(`createBrotliCompress is not supported on GJS (no Brotli in GLib)`)}function createBrotliDecompress(n){throw Error(`createBrotliDecompress is not supported on GJS (no Brotli in GLib)`)}function createZstdCompress(n){let S=Error(`createZstdCompress is not supported on GJS (no Zstd in GLib)`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}function createZstdDecompress(n){let S=Error(`createZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw S.code=`ERR_UNSUPPORTED_OPERATION`,S}var ZlibBase,Gzip,Gunzip,Deflate,Inflate,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress,ZstdCompress,ZstdDecompress,_i=__esmMin(()=>{Vr(),gi(),__name$1(toUint8Array$2,`toUint8Array`),__name$1(concat$1,`concat`),ZlibBase=class extends pi{_mode;_chunks=[];constructor(n,S){super(S),this._mode=n}_transform(n,S,C){this._chunks.push(toUint8Array$2(n)),C()}_flush(n){let S=concat$1(this._chunks);this._chunks=[];try{this.push(Buffer.from(this._run(S))),n()}catch(S){n(S instanceof Error?S:Error(String(S)))}}_run(n){let S=this._mode;switch(S.kind){case`compress`:return compressWithGio(n,S.format);case`decompress`:return decompressStreamWithGio(n,S.format);case`gunzip`:return gunzipWithGio(n);case`unzip`:return n.length>=2&&n[0]===31&&n[1]===139?gunzipWithGio(n):decompressStreamWithGio(n,`deflate`)}}},Gzip=class extends ZlibBase{constructor(n){super({kind:`compress`,format:`gzip`},n)}},Gunzip=class extends ZlibBase{constructor(n){super({kind:`gunzip`},n)}},Deflate=class extends ZlibBase{constructor(n){super({kind:`compress`,format:`deflate`},n)}},Inflate=class extends ZlibBase{constructor(n){super({kind:`decompress`,format:`deflate`},n)}},DeflateRaw=class extends ZlibBase{constructor(n){super({kind:`compress`,format:`deflate-raw`},n)}},InflateRaw=class extends ZlibBase{constructor(n){super({kind:`decompress`,format:`deflate-raw`},n)}},Unzip=class extends ZlibBase{constructor(n){super({kind:`unzip`},n)}},BrotliCompress=class extends pi{constructor(){throw super(),Error(`BrotliCompress is not supported on GJS (no Brotli in GLib)`)}},BrotliDecompress=class extends pi{constructor(){throw super(),Error(`BrotliDecompress is not supported on GJS (no Brotli in GLib)`)}},ZstdCompress=class extends pi{constructor(){super();let n=Error(`ZstdCompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}},ZstdDecompress=class extends pi{constructor(){super();let n=Error(`ZstdDecompress is not supported on GJS (no Zstd in GLib)`);throw n.code=`ERR_UNSUPPORTED_OPERATION`,n}}}),vi=__exportAll$4({BrotliCompress:()=>BrotliCompress,BrotliDecompress:()=>BrotliDecompress,Deflate:()=>Deflate,DeflateRaw:()=>DeflateRaw,Gunzip:()=>Gunzip,Gzip:()=>Gzip,Inflate:()=>Inflate,InflateRaw:()=>InflateRaw,Unzip:()=>Unzip,ZlibTransform:()=>ZlibBase,ZstdCompress:()=>ZstdCompress,ZstdDecompress:()=>ZstdDecompress,brotliCompress:()=>brotliCompress,brotliCompressSync:()=>brotliCompressSync,brotliDecompress:()=>brotliDecompress,brotliDecompressSync:()=>brotliDecompressSync,constants:()=>bi,createBrotliCompress:()=>createBrotliCompress,createBrotliDecompress:()=>createBrotliDecompress,createDeflate:()=>createDeflate,createDeflateRaw:()=>createDeflateRaw,createGunzip:()=>createGunzip,createGzip:()=>createGzip,createInflate:()=>createInflate,createInflateRaw:()=>createInflateRaw,createUnzip:()=>createUnzip,createZstdCompress:()=>createZstdCompress,createZstdDecompress:()=>createZstdDecompress,default:()=>xi,deflate:()=>deflate,deflateRaw:()=>deflateRaw,deflateRawSync:()=>deflateRawSync,deflateSync:()=>deflateSync,gunzip:()=>gunzip$1,gunzipSync:()=>gunzipSync,gzip:()=>gzip$1,gzipSync:()=>gzipSync,inflate:()=>inflate,inflateRaw:()=>inflateRaw,inflateRawSync:()=>inflateRawSync,inflateSync:()=>inflateSync,zstdCompress:()=>zstdCompress,zstdCompressSync:()=>zstdCompressSync,zstdDecompress:()=>zstdDecompress,zstdDecompressSync:()=>zstdDecompressSync});function decompressWithGio(n,S){return S===`gzip`?gunzipWithGio(n):decompressStreamWithGio(n,S)}async function runWebTransform(n,S){let C=new ReadableStream({start(S){S.enqueue(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),S.close()}}),N=[],F=C.pipeThrough(S).getReader();for(;;){let{done:n,value:S}=await F.read();if(n)break;N.push(S)}let I=N.reduce((n,S)=>n+S.length,0),H=new Uint8Array(I),W=0;for(let n of N)H.set(n,W),W+=n.length;return H}async function compressWithWeb(n,S){return runWebTransform(n,new CompressionStream(S))}async function decompressWithWeb(n,S){return runWebTransform(n,new DecompressionStream(S))}async function compress(n,S){return hasWebCompression()?compressWithWeb(n,S):compressWithGio(n,S)}async function decompress(n,S){if(hasWebCompression())try{return await decompressWithWeb(n,S)}catch(C){if(S!==`gzip`)throw C;return decompressWithGio(n,S)}return decompressWithGio(n,S)}function toUint8Array$1(n){return typeof n==`string`?new TextEncoder().encode(n):n instanceof ArrayBuffer?new Uint8Array(n):n}function gzip$1(n,S,C){let N=typeof S==`function`?S:C;compress(toUint8Array$1(n),`gzip`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function gunzip$1(n,S,C){let N=typeof S==`function`?S:C;decompress(toUint8Array$1(n),`gzip`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function deflate(n,S,C){let N=typeof S==`function`?S:C;compress(toUint8Array$1(n),`deflate`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function inflate(n,S,C){let N=typeof S==`function`?S:C;decompress(toUint8Array$1(n),`deflate`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function deflateRaw(n,S,C){let N=typeof S==`function`?S:C;compress(toUint8Array$1(n),`deflate-raw`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function inflateRaw(n,S,C){let N=typeof S==`function`?S:C;decompress(toUint8Array$1(n),`deflate-raw`).then(n=>N(null,n),n=>N(n instanceof Error?n:Error(String(n)),new Uint8Array))}function gzipSync(n,S){return compressWithGio(toUint8Array$1(n),`gzip`)}function gunzipSync(n,S){return decompressWithGio(toUint8Array$1(n),`gzip`)}function deflateSync(n,S){return compressWithGio(toUint8Array$1(n),`deflate`)}function inflateSync(n,S){return decompressWithGio(toUint8Array$1(n),`deflate`)}function deflateRawSync(n,S){return compressWithGio(toUint8Array$1(n),`deflate-raw`)}function inflateRawSync(n,S){return decompressWithGio(toUint8Array$1(n),`deflate-raw`)}function brotliCompress(n,S,C){(typeof S==`function`?S:C)(Error(`brotliCompress: Brotli is not supported in this environment`),yi)}function brotliDecompress(n,S,C){(typeof S==`function`?S:C)(Error(`brotliDecompress: Brotli is not supported in this environment`),yi)}function brotliCompressSync(n,S){throw Error(`brotliCompressSync: Brotli is not supported in this environment`)}function brotliDecompressSync(n,S){throw Error(`brotliDecompressSync: Brotli is not supported in this environment`)}function zstdCompress(n,S,C){let N=typeof S==`function`?S:C,F=Error(`zstdCompress: Zstd is not supported in this environment`);F.code=`ERR_UNSUPPORTED_OPERATION`,N(F,yi)}function zstdDecompress(n,S,C){let N=typeof S==`function`?S:C,F=Error(`zstdDecompress: Zstd is not supported in this environment`);F.code=`ERR_UNSUPPORTED_OPERATION`,N(F,yi)}function zstdCompressSync(n,S){let C=Error(`zstdCompressSync: Zstd is not supported in this environment`);throw C.code=`ERR_UNSUPPORTED_OPERATION`,C}function zstdDecompressSync(n,S){let C=Error(`zstdDecompressSync: Zstd is not supported in this environment`);throw C.code=`ERR_UNSUPPORTED_OPERATION`,C}var hasWebCompression,yi,bi,xi,Si=__esmMin(()=>{Vr(),_i(),hasWebCompression=()=>globalThis.CompressionStream!==void 0,__name$1(toUint8Array$1,`toUint8Array`),__name$1(gzip$1,`gzip`),__name$1(gunzip$1,`gunzip`),yi=new Uint8Array,bi={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_DEFLATED:8},xi={gzip:gzip$1,gunzip:gunzip$1,deflate,inflate,deflateRaw,inflateRaw,gzipSync,gunzipSync,deflateSync,inflateSync,deflateRawSync,inflateRawSync,brotliCompress,brotliDecompress,brotliCompressSync,brotliDecompressSync,zstdCompress,zstdDecompress,zstdCompressSync,zstdDecompressSync,Gzip,Gunzip,Deflate,Inflate,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress,ZstdCompress,ZstdDecompress,createGzip,createGunzip,createDeflate,createInflate,createDeflateRaw,createInflateRaw,createUnzip,createBrotliCompress,createBrotliDecompress,createZstdCompress,createZstdDecompress,constants:bi}});const Ci=new Set([`gzip`,`deflate`,`deflate-raw`]);function validateFormat(n){if(!Ci.has(n))throw TypeError(`Unsupported compression format: '${n}'. Supported formats: 'gzip', 'deflate', 'deflate-raw'.`);return n}const wi=typeof globalThis.CompressionStream==`function`&&typeof globalThis.DecompressionStream==`function`;let Ti=!1,Ei,Di,Oi,ki,Ai,ji;async function loadZlib(){if(Ti)return;let n=await Promise.resolve().then(()=>(Si(),vi));Ei=n.gzipSync,Di=n.gunzipSync,Oi=n.deflateSync,ki=n.inflateSync,Ai=n.deflateRawSync,ji=n.inflateRawSync,Ti=!0}function getCompressFn(n){switch(n){case`gzip`:return n=>Ei(n);case`deflate`:return n=>Oi(n);case`deflate-raw`:return n=>Ai(n)}}function getDecompressFn(n){switch(n){case`gzip`:return n=>Di(n);case`deflate`:return n=>ki(n);case`deflate-raw`:return n=>ji(n)}}function concatChunks$1(n){if(n.length===1)return n[0];let S=0;for(let C of n)S+=C.length;let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}__name$1(concatChunks$1,`concatChunks`);let Mi,Ni;if(wi)Mi=globalThis.CompressionStream,Ni=globalThis.DecompressionStream;else{let n=loadZlib();Mi=class CompressionStream{readable;writable;constructor(S){let C=validateFormat(S),N=[],F=new Ar({transform(n){N.push(n)},async flush(S){try{await n;let F=getCompressFn(C)(concatChunks$1(N));F.length>0&&S.enqueue(F)}catch(n){S.error(n)}}});this.readable=F.readable,this.writable=F.writable}},Ni=class DecompressionStream{readable;writable;constructor(S){let C=validateFormat(S),N=[],F=new Ar({transform(n){N.push(n)},async flush(S){try{await n;let F=getDecompressFn(C)(concatChunks$1(N));F.length>0&&S.enqueue(F)}catch(n){S.error(n)}}});this.readable=F.readable,this.writable=F.writable}}}const Pi=globalThis;globalThis.CompressionStream===void 0&&(Pi.CompressionStream=Mi),globalThis.DecompressionStream===void 0&&(Pi.DecompressionStream=Ni);const Fi=globalThis;globalThis.DOMException===void 0&&(Fi.DOMException=On);var Ii,__name,Li=__esmMin(()=>{Ii=Object.defineProperty,__name=(n,S)=>Ii(n,`name`,{value:S,configurable:!0})});function validateHeaderName(n){if(typeof n!=`string`||!/^[\^`\-\w!#$%&'*+.|~]+$/.test(n)){let S=TypeError(`Header name must be a valid HTTP token ["${n}"]`);throw Object.defineProperty(S,"code",{value:`ERR_INVALID_HTTP_TOKEN`}),S}}function validateHeaderValue(n,S){if(S===void 0){let S=TypeError(`Header "${n}" value must not be undefined`);throw Object.defineProperty(S,"code",{value:`ERR_HTTP_INVALID_HEADER_VALUE`}),S}if(typeof S==`string`&&/[^\t -~-ÿ]/.test(S)){let S=TypeError(`Invalid character in header content ["${n}"]`);throw Object.defineProperty(S,"code",{value:`ERR_INVALID_CHAR`}),S}}const Ri=Symbol(`Headers.headers`);function isBoxedPrimitive$2(n){return n instanceof String||n instanceof Number||n instanceof Boolean||typeof Symbol<`u`&&n instanceof Symbol||typeof BigInt<`u`&&n instanceof BigInt}__name$1(isBoxedPrimitive$2,`isBoxedPrimitive`);var zi=class Headers{[Ri];constructor(n){if(this[Ri]=new Map,n!=null){if(n instanceof Headers){for(let[S,C]of n[Ri])this[Ri].set(S,[...C]);return}if(typeof n==`object`&&!isBoxedPrimitive$2(n)){let S=n[Symbol.iterator];if(S==null)for(let[S,C]of Object.entries(n))validateHeaderName(S),validateHeaderValue(S,String(C)),this.append(S,String(C));else{if(typeof S!=`function`)throw TypeError(`Header pairs must be iterable`);for(let S of n){if(typeof S!=`object`||isBoxedPrimitive$2(S))throw TypeError(`Each header pair must be an iterable object`);let n=[...S];if(n.length!==2)throw TypeError(`Each header pair must be a name/value tuple`);validateHeaderName(n[0]),validateHeaderValue(n[0],String(n[1])),this.append(n[0],String(n[1]))}}}else throw TypeError(`Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'`)}}append(n,S){validateHeaderName(n),validateHeaderValue(n,S);let C=String(n).toLowerCase(),N=String(S),F=this[Ri].get(C);F?F.push(N):this[Ri].set(C,[N])}set(n,S){validateHeaderName(n),validateHeaderValue(n,S);let C=String(n).toLowerCase();this[Ri].set(C,[String(S)])}delete(n){this[Ri].delete(String(n).toLowerCase())}has(n){return this[Ri].has(String(n).toLowerCase())}get(n){let S=this[Ri].get(String(n).toLowerCase());if(!S||S.length===0)return null;let C=S.join(`, `);return/^content-encoding$/i.test(n)&&(C=C.toLowerCase()),C}getAll(n){return this[Ri].get(String(n).toLowerCase())??[]}getSetCookie(){return this[Ri].get(`set-cookie`)??[]}forEach(n,S){for(let C of this.keys())Reflect.apply(n,S,[this.get(C),C,this])}*keys(){let n=[...this[Ri].keys()].sort(),S=new Set;for(let C of n)S.has(C)||(S.add(C),yield C)}*values(){for(let n of this.keys())yield this.get(n)}*entries(){for(let n of this.keys())yield[n,this.get(n)]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`Headers`}toString(){return Object.prototype.toString.call(this)}raw(){let n={};for(let S of this.keys())n[S]=this.getAll(S);return n}_appendToSoupMessage(n,S,C=n.MessageHeadersType.REQUEST){let N=S?S.get_request_headers():new n.MessageHeaders(C);for(let[n,S]of this.entries())N.append(n,S);return N}static _newFromSoupMessage(n,S,C=n.MessageHeadersType.RESPONSE){let N=new Headers,F;return F=C===n.MessageHeadersType.RESPONSE?S.get_response_headers():S.get_request_headers(),F.foreach((n,S)=>{N.append(n,S)}),N}[Symbol.for(`nodejs.util.inspect.custom`)](){let n={};for(let S of this.keys()){let C=this.getAll(S);S===`host`?n[S]=C[0]:n[S]=C.length>1?C:C[0]}return n}};Object.defineProperties(zi.prototype,[`get`,`entries`,`forEach`,`values`].reduce((n,S)=>(n[S]={enumerable:!0},n),{}));var Bi=__esmMin(()=>{lt()});Bi();var FetchBaseError=class extends Error{type;constructor(n,S){super(n),typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,this.constructor),this.type=S}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}},FetchError=class extends FetchBaseError{code;errno;erroredSysCall;constructor(n,S,C){super(n,S),C&&(this.code=this.errno=C.code,this.erroredSysCall=C.syscall)}};gn();const Vi=Symbol.toStringTag,isURLSearchParameters=n=>typeof n==`object`&&typeof n.append==`function`&&typeof n.delete==`function`&&typeof n.get==`function`&&typeof n.getAll==`function`&&typeof n.has==`function`&&typeof n.set==`function`&&typeof n.sort==`function`&&n[Vi]===`URLSearchParams`,isBlob=n=>{if(!n||typeof n!=`object`)return!1;let S=n;return typeof S.arrayBuffer==`function`&&typeof S.type==`string`&&typeof S.stream==`function`&&typeof S.constructor==`function`&&/^(Blob|File)$/.test(S[Vi])},isAbortSignal=n=>{if(typeof n!=`object`||!n)return!1;let S=n;return S[Vi]===`AbortSignal`||S[Vi]===`EventTarget`},isDomainOrSubdomain=(n,S)=>{let C=new mn(S).hostname,N=new mn(n).hostname;return C===N||C.endsWith(`.${N}`)},isSameProtocol=(n,S)=>new mn(S).protocol===new mn(n).protocol;var Hi,Ui,File,Wi=__esmMin(()=>{Hi=Symbol(`File.name`),Ui=Symbol(`File.lastModified`),File=class extends Blob{[Hi];[Ui];webkitRelativePath=``;constructor(n,S,C){super(n,C),this[Hi]=String(S),this[Ui]=C?.lastModified??Date.now()}get name(){return this[Hi]}get lastModified(){return this[Ui]}get[Symbol.toStringTag](){return`File`}}});function generateBoundary(){let n=`----formdata-`;for(let S=0;S<24;S++)n+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*62));return n}function escape(n){return n.replace(/\n/g,`%0A`).replace(/\r/g,`%0D`).replace(/"/g,`%22`)}function formDataToBlob(n,S){S??=generateBoundary();let C=[],N=`--${S}\r\nContent-Disposition: form-data; name="`;for(let[S,F]of n.entries())if(typeof F==`string`)C.push(`${N}${escape(S)}"\r\n\r\n${F.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
|
|
11
11
|
`)}\r\n`);else{let n=F instanceof File?F:new File([F],`blob`,{type:F.type});C.push(`${N}${escape(S)}"; filename="${escape(n.name)}"\r\nContent-Type: ${n.type||`application/octet-stream`}\r\n\r\n`),C.push(n),C.push(`\r
|
|
12
12
|
`)}return C.push(`--${S}--`),new Blob(C,{type:`multipart/form-data; boundary=${S}`})}var Gi=__esmMin(()=>{Wi()});function normalizeValue(n,S,C){return typeof S==`string`?S:(S instanceof Blob&&!(S instanceof File)&&(S=new File([S],C??`blob`,{type:S.type})),S instanceof File&&C!==void 0&&(S=new File([S],C,{type:S.type,lastModified:S.lastModified})),S)}var Ki,FormData,qi=__esmMin(()=>{Wi(),Ki=Symbol(`FormData.entries`),FormData=class{[Ki]=[];constructor(){}append(n,S,C){this[Ki].push({name:String(n),value:normalizeValue(n,S,C)})}delete(n){let S=String(n);this[Ki]=this[Ki].filter(n=>n.name!==S)}get(n){let S=String(n),C=this[Ki].find(n=>n.name===S);return C?C.value:null}getAll(n){let S=String(n);return this[Ki].filter(n=>n.name===S).map(n=>n.value)}has(n){let S=String(n);return this[Ki].some(n=>n.name===S)}set(n,S,C){let N=String(n),F=normalizeValue(N,S,C),I=!1;this[Ki]=this[Ki].filter(n=>n.name===N?I?!1:(I=!0,n.value=F,!0):!0),I||this[Ki].push({name:N,value:F})}forEach(n,S){for(let C of this[Ki])n.call(S,C.value,C.name,this)}*entries(){for(let n of this[Ki])yield[n.name,n.value]}*keys(){for(let n of this[Ki])yield n.name}*values(){for(let n of this[Ki])yield n.value}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return`FormData`}}}),Ji=__esmMin(()=>{Gi(),qi()}),Yi=__exportAll$4({toFormData:()=>toFormData});function _fileName(n){let S=n.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!S)return;let C=S[2]||S[3]||``,N=C.slice(C.lastIndexOf(`\\`)+1);return N=N.replace(/%22/g,`"`),N=N.replace(/&#(\d{4});/g,(n,S)=>String.fromCharCode(S)),N}async function toFormData(n,S){if(!/multipart/i.test(S))throw TypeError(`Failed to fetch`);let C=S.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!C)throw TypeError(`no or bad content-type header, no multipart boundary`);let N=new MultipartParser(C[1]||C[2]),F,I,H,W,q,Y,X=[],Z=new FormData,onPartData=n=>{H+=te.decode(n,{stream:!0})},appendToFile=n=>{X.push(n)},appendFileToFormData=()=>{let n=new re(X,Y,{type:q});Z.append(W,n)},appendEntryToFormData=()=>{Z.append(W,H)},te=new TextDecoder(`utf-8`);te.decode(),N.onPartBegin=function(){N.onPartData=onPartData,N.onPartEnd=appendEntryToFormData,F=``,I=``,H=``,W=``,q=``,Y=null,X.length=0},N.onHeaderField=function(n){F+=te.decode(n,{stream:!0})},N.onHeaderValue=function(n){I+=te.decode(n,{stream:!0})},N.onHeaderEnd=function(){if(I+=te.decode(),F=F.toLowerCase(),F===`content-disposition`){let n=I.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);n&&(W=n[2]||n[3]||``),Y=_fileName(I),Y&&(N.onPartData=appendToFile,N.onPartEnd=appendFileToFormData)}else F===`content-type`&&(q=I);I=``,F=``};for await(let S of n)N.write(S);return N.end(),Z}var Xi,Zi,lower,Qi,MultipartParser,$i=__esmMin(()=>{Ji(),Xi=1,Zi={PART_BOUNDARY:Xi,LAST_BOUNDARY:Xi*=2},lower=n=>n|32,Qi=__name$1((...n)=>{},`noop`),MultipartParser=class{index=0;flags=0;boundary;lookbehind;state=0;onHeaderEnd=Qi;onHeaderField=Qi;onHeadersEnd=Qi;onHeaderValue=Qi;onPartBegin=Qi;onPartData=Qi;onPartEnd=Qi;boundaryChars={};constructor(n){n=`\r
|
|
13
13
|
--`+n;let S=new Uint8Array(n.length);for(let C=0;C<n.length;C++)S[C]=n.charCodeAt(C),this.boundaryChars[S[C]]=!0;this.boundary=S,this.lookbehind=new Uint8Array(this.boundary.length+8)}write(n){let S=0,C=n.length,N=this.index,{lookbehind:F,boundary:I,boundaryChars:H,index:W,state:q,flags:Y}=this,X=this.boundary.length,Z=X-1,te=n.length,ne,re,mark=n=>{this[n+`Mark`]=S},clear=n=>{delete this[n+`Mark`]},callback=(n,S,C,N)=>{(S===void 0||S!==C)&&this[n](N&&N.subarray(S,C))},dataCallback=(C,N=!1)=>{let F=C+`Mark`;F in this&&(N?(callback(C,this[F],S,n),delete this[F]):(callback(C,this[F],n.length,n),this[F]=0))};for(S=0;S<C;S++)switch(ne=n[S],q){case 0:if(W===I.length-2){if(ne===45)Y|=Zi.LAST_BOUNDARY;else if(ne!==13)return;W++;break}else if(W-1==I.length-2){if(Y&Zi.LAST_BOUNDARY&&ne===45)q=9,Y=0;else if(!(Y&Zi.LAST_BOUNDARY)&&ne===10)W=0,callback(`onPartBegin`),q=1;else return;break}ne!==I[W+2]&&(W=-2),ne===I[W+2]&&W++;break;case 1:q=2,mark(`onHeaderField`),W=0;case 2:if(ne===13){clear(`onHeaderField`),q=6;break}if(W++,ne===45)break;if(ne===58){if(W===1)return;dataCallback(`onHeaderField`,!0),q=3;break}if(re=lower(ne),re<97||re>122)return;break;case 3:if(ne===32)break;mark(`onHeaderValue`),q=4;case 4:ne===13&&(dataCallback(`onHeaderValue`,!0),callback(`onHeaderEnd`),q=5);break;case 5:if(ne!==10)return;q=1;break;case 6:if(ne!==10)return;callback(`onHeadersEnd`),q=7;break;case 7:q=8,mark(`onPartData`);case 8:if(N=W,W===0){for(S+=Z;S<te&&!(n[S]in H);)S+=X;S-=Z,ne=n[S]}if(W<I.length)I[W]===ne?(W===0&&dataCallback(`onPartData`,!0),W++):W=0;else if(W===I.length)W++,ne===13?Y|=Zi.PART_BOUNDARY:ne===45?Y|=Zi.LAST_BOUNDARY:W=0;else if(W-1===I.length)if(Y&Zi.PART_BOUNDARY){if(W=0,ne===10){Y&=~Zi.PART_BOUNDARY,callback(`onPartEnd`),callback(`onPartBegin`),q=1;break}}else Y&Zi.LAST_BOUNDARY&&ne===45?(callback(`onPartEnd`),q=9,Y=0):W=0;if(W>0)F[W-1]=ne;else if(N>0){let n=new Uint8Array(F.buffer,F.byteOffset,F.byteLength);callback(`onPartData`,0,N,n),N=0,mark(`onPartData`),S--}break;case 9:break;default:throw Error(`Unexpected state entered: ${q}`)}dataCallback(`onHeaderField`),dataCallback(`onHeaderValue`),dataCallback(`onPartData`),this.index=W,this.state=q,this.flags=Y}end(){if(this.state===1&&this.index===0||this.state===8&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==9)throw Error(`MultipartParser.end(): stream ended unexpectedly`)}}});ye(),Li(),Bi(),gn(),lt(),gi(),Ji(),__name((n,S)=>new Promise((C,N)=>{pipeline(n,S,n=>{n?N(n):C()})}),`pipeline`);const ea=Symbol(`Body internals`);function isAnyArrayBuffer$2(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&n instanceof SharedArrayBuffer}__name$1(isAnyArrayBuffer$2,`isAnyArrayBuffer`);var Body=class{[ea]={body:null,stream:null,webStream:null,boundary:``,disturbed:!1,error:null};size=0;constructor(n,S={size:0}){if(this.size=S.size||0,n==null)this[ea].body=null;else if(isURLSearchParameters(n))this[ea].body=$e.from(n.toString());else if(isBlob(n))this[ea].body=n;else if($e.isBuffer(n))this[ea].body=n;else if(isAnyArrayBuffer$2(n))this[ea].body=$e.from(n);else if(ArrayBuffer.isView(n))this[ea].body=$e.from(n.buffer,n.byteOffset,n.byteLength);else if(n instanceof li)this[ea].body=n;else if(typeof ReadableStream<`u`&&n instanceof ReadableStream)this[ea].body=readableStreamToReadable(n);else if(n instanceof FormData){let S=formDataToBlob(n);this[ea].body=S,this[ea].boundary=S.type?.split(`boundary=`)?.[1]??``}else typeof n==`string`?this[ea].body=$e.from(n):n instanceof fn?this[ea].body=$e.from(n.toString()):(ve.warn(`Unknown body type "${typeof n}", try to parse the body to string!`),this[ea].body=$e.from(String(n)));let C=this[ea].body;$e.isBuffer(C)?this[ea].stream=li.from(C):isBlob(C)?this[ea].stream=li.from(blobToAsyncIterable(C)):C instanceof li&&(this[ea].stream=C),C instanceof ci&&C.on(`error`,n=>{let S=n instanceof FetchBaseError?n:new FetchError(`Invalid response body while trying to fetch ${this.url}: ${n.message}`,`system`,n);this[ea].error=S})}get body(){let n=this[ea].stream;if(!n)return null;let S=this[ea].webStream;if(S)return S;if(typeof ReadableStream<`u`){let S=!1,C=new ReadableStream({start(C){n.on(`data`,n=>{if(!S)try{C.enqueue(n instanceof Uint8Array?n:new Uint8Array(n))}catch{}}),n.on(`end`,()=>{if(!S){S=!0;try{C.close()}catch{}}}),n.on(`error`,n=>{if(!S){S=!0;try{C.error(n)}catch{}}})},cancel(){S=!0,n.destroy()}});return this[ea].webStream=C,C}return null}get _stream(){return this[ea].stream}get _rawBodyBuffer(){let n=this[ea].body;return n===null?null:$e.isBuffer(n)?n:n instanceof Uint8Array?$e.from(n.buffer,n.byteOffset,n.byteLength):null}get bodyUsed(){return this[ea].disturbed}async arrayBuffer(){let{buffer:n,byteOffset:S,byteLength:C}=await consumeBody(this);return n.slice(S,S+C)}async formData(){let n=this.headers?.get(`content-type`);if(n?.startsWith(`application/x-www-form-urlencoded`)){let n=new FormData,S=new fn(await this.text());for(let[C,N]of S)n.append(C,N);return n}let{toFormData:S}=await Promise.resolve().then(()=>($i(),Yi));return S(this.body,n)}async blob(){let n=this.headers?.get(`content-type`)||this[ea].body&&this[ea].body.type||``;return new ne([await this.arrayBuffer()],{type:n})}async json(){let n=await this.text();return JSON.parse(n)}async text(){let n=await consumeBody(this);return new TextDecoder().decode(n)}};Object.defineProperties(Body.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0}});async function consumeBody(n){if(n[ea].disturbed)throw TypeError(`body used already for: ${n.url}`);if(n[ea].disturbed=!0,n[ea].error)throw n[ea].error;let{_stream:S}=n;if(S===null||!(S instanceof ci))return $e.alloc(0);let C=[],N=0;try{for await(let F of S){if(n.size>0&&N+F.length>n.size){let C=new FetchError(`content size at ${n.url} over limit: ${n.size}`,`max-size`);throw S.destroy(C),C}N+=F.length,C.push(F)}}catch(S){let C=S instanceof Error?S:Error(String(S));throw S instanceof FetchBaseError?S:new FetchError(`Invalid response body while trying to fetch ${n.url}: ${C.message}`,`system`,C)}try{return C.every(n=>typeof n==`string`)?$e.from(C.join(``)):$e.concat(C,N)}catch(S){let C=S instanceof Error?S:Error(String(S));throw new FetchError(`Could not create Buffer from response body for ${n.url}: ${C.message}`,`system`,C)}}const clone=(n,S)=>{let C,N,{body:F}=n[ea];if(n.bodyUsed)throw Error(`cannot clone body after it is used`);return F instanceof ci&&typeof F.getBoundary!=`function`&&(C=new mi({highWaterMark:S}),N=new mi({highWaterMark:S}),F.pipe(C),F.pipe(N),n[ea].stream=C,F=N),F},extractContentType=(n,S)=>n===null?null:typeof n==`string`?`text/plain;charset=UTF-8`:isURLSearchParameters(n)?`application/x-www-form-urlencoded;charset=UTF-8`:isBlob(n)?n.type||null:$e.isBuffer(n)||isAnyArrayBuffer$2(n)||ArrayBuffer.isView(n)?null:n instanceof FormData?`multipart/form-data; boundary=${S[ea].boundary}`:n instanceof ci?null:`text/plain;charset=UTF-8`,getTotalBytes=n=>{let{body:S}=n[ea];if(S===null)return 0;if(isBlob(S))return S.size;if($e.isBuffer(S))return S.length;if(S&&typeof S.getLengthSync==`function`){let n=S;return n.hasKnownLength&&n.hasKnownLength()?n.getLengthSync():null}return null};function readableStreamToReadable(n){let S=n.getReader();return new li({async read(){try{let{done:n,value:C}=await S.read();n?this.push(null):this.push($e.from(C))}catch(n){this.destroy(n)}},destroy(n,C){S.cancel().then(()=>C(null),C)}})}async function*blobToAsyncIterable(n){if(typeof n.stream==`function`){let S=n.stream().getReader();for(;;){let{done:n,value:C}=await S.read();if(n)break;yield C}}else yield new Uint8Array(await n.arrayBuffer())}const ta=new Set([301,302,303,307,308]),isRedirect=n=>ta.has(n);gn(),pt(),Rr();const na=Symbol(`Response internals`);var ra=class Response extends Body{[na];_inputStream=null;constructor(n=null,S={}){super(n,S);let C=S.status==null?200:S.status,N=new zi(S.headers);if(n!==null&&!N.has(`Content-Type`)){let S=extractContentType(n,this);S&&N.append(`Content-Type`,S)}this[na]={type:`default`,url:S.url,status:C,statusText:S.statusText||``,headers:N,counter:S.counter,highWaterMark:S.highWaterMark}}get type(){return this[na].type}get url(){return this[na].url||``}get status(){return this[na].status}get ok(){return this[na].status>=200&&this[na].status<300}get redirected(){return this[na].counter>0}get statusText(){return this[na].statusText}get headers(){return this[na].headers}get highWaterMark(){return this[na].highWaterMark}clone(){return new Response(clone(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(n,S=302){if(!isRedirect(S))throw RangeError(`Failed to execute "redirect" on "response": Invalid status code`);return new Response(null,{headers:{location:new mn(n).toString()},status:S})}static error(){let n=new Response(null,{status:0,statusText:``});return n[na].type=`error`,n}static json(n,S){let C=JSON.stringify(n),N={...S},F=new zi(N.headers);return F.has(`content-type`)||F.set(`content-type`,`application/json`),N.headers=F,new Response(C,N)}get[Symbol.toStringTag](){return`Response`}async text(){if(!this._inputStream)return super.text();let n=Lr.MemoryOutputStream.new_resizable();await new Promise((S,C)=>{n.splice_async(this._inputStream,Lr.OutputStreamSpliceFlags.CLOSE_TARGET|Lr.OutputStreamSpliceFlags.CLOSE_SOURCE,ft.PRIORITY_DEFAULT,null,(N,F)=>{try{S(n.splice_finish(F))}catch(n){C(n)}})});let S=n.steal_as_bytes();return new TextDecoder().decode(S.toArray())}};Object.defineProperties(ra.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});function gbytesToUint8Array(n){return n.toArray()}var ia=__esmMin(()=>{}),aa,cli,oa=__esmMin(()=>{pt(),aa=new TextDecoder,cli=n=>{let[S,C,N,F]=ft.spawn_command_line_sync(n);if(N.byteLength)throw Error(aa.decode(N));return aa.decode(C)}}),sa,readJSON,ca=__esmMin(()=>{pt(),sa=new TextDecoder,readJSON=n=>{let[S,C]=ft.file_get_contents(n);if(S)return JSON.parse(sa.decode(C));throw Error(`Error on require "${n}"`)}}),la,ua=__esmMin(()=>{la=C}),da,fa=__esmMin(()=>{ua(),da=la});function existsSync(n){return typeof n!=`string`||n===``?!1:Lr.File.new_for_path(n).query_exists(null)}var pa=__esmMin(()=>{Rr(),fa()});async function readBytesAsync(n,S=4096,C=ft.PRIORITY_DEFAULT,N=null){return new Promise((F,I)=>{n.read_bytes_async(S,C,N,(S,C)=>{try{let S=n.read_bytes_finish(C);return S.get_size()===0?F(null):F(gbytesToUint8Array(S))}catch(n){let S=n;if(typeof S.matches==`function`&&(S.matches(Lr.IOErrorEnum,Lr.IOErrorEnum.PARTIAL_INPUT)||S.matches(Lr.IOErrorEnum,Lr.IOErrorEnum.CONNECTION_CLOSED)||S.matches(Lr.IOErrorEnum,Lr.IOErrorEnum.BROKEN_PIPE)||S.matches(Lr.IOErrorEnum,Lr.IOErrorEnum.CLOSED)))return F(null);I(n)}})})}async function*inputStreamAsyncIterator(n,S=4096,C=ft.PRIORITY_DEFAULT,N=null){let F;for(;(F=await readBytesAsync(n,S,C,N))!==null;)yield F}var ma=__esmMin(()=>{ia(),pt(),Rr()}),ha,ga,getPathSeparator,_a=__esmMin(()=>{pt(),Rr(),{File:ha}=Lr,ga=__name$1((n,...S)=>{let C=ha.new_for_path(n);for(let n of S)C=C.resolve_relative_path(n);return C},`resolve`),getPathSeparator=()=>ft.get_current_dir().startsWith(`/`)?`/`:`\\`}),va=__esmMin(()=>{ia(),oa(),oe(),Ie(),ca(),pa(),ma(),_a()});gi(),pt(),va();async function soupSendAsync(n,S,C=ft.PRIORITY_DEFAULT,N=null){return new Promise((F,I)=>{n.send_async(S,C,N,(S,C)=>{try{F(n.send_finish(C))}catch(n){I(n)}})})}function inputStreamToReadable(n,S={}){return li.from(inputStreamAsyncIterator(n),S)}let ya=null;async function loadSoup(){return ya??=(await import(`gi://Soup?version=3.0`)).default}function isIP(n){if(typeof n!=`string`)return 0;let S=n.includes(`%`)?n.slice(0,n.indexOf(`%`)):n,C=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(S);if(C)return C.slice(1).every(n=>(n.length===1||n[0]!==`0`)&&Number(n)<=255)?4:0;if(S.length===0||!S.includes(`:`))return 0;let N=/:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(S),F=N?S.slice(0,S.length-N[0].length):S;if(N&&isIP(N[1])!==4)return 0;let I=F.split(`::`);if(I.length>2)return 0;let H=0;for(let n of I)if(n!==``)for(let S of n.split(`:`)){if(!/^[0-9a-fA-F]{1,4}$/.test(S))return 0;H++}let W=N?6:8;return I.length===2?H<W?6:0:H===W?6:0}Rr(),pt(),gi(),Rr(),Kt(),gn();function stripURLForUseAsAReferrer(n,S=!1){if(n==null||n===`no-referrer`)return`no-referrer`;let C=new mn(n);return/^(about|blob|data):$/.test(C.protocol)?`no-referrer`:(C.username=``,C.password=``,C.hash=``,S&&(C.pathname=``,C.search=``),C)}const ba=new Set([``,`no-referrer`,`no-referrer-when-downgrade`,`same-origin`,`origin`,`strict-origin`,`origin-when-cross-origin`,`strict-origin-when-cross-origin`,`unsafe-url`]);function validateReferrerPolicy(n){if(!ba.has(n))throw TypeError(`Invalid referrerPolicy: ${n}`);return n}function isOriginPotentiallyTrustworthy(n){if(/^(http|ws)s:$/.test(n.protocol))return!0;let S=n.host.replace(/(^\[)|(]$)/g,``),C=isIP(S);return C===4&&S.startsWith(`127.`)||C===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(S)?!0:n.host===`localhost`||n.host.endsWith(`.localhost`)?!1:n.protocol===`file:`}function isUrlPotentiallyTrustworthy(n){return/^about:(blank|srcdoc)$/.test(n.toString())||(typeof n==`string`&&(n=new mn(n)),n.protocol===`data:`)||/^(blob|filesystem):$/.test(n.protocol)?!0:isOriginPotentiallyTrustworthy(n)}function determineRequestsReferrer(n,S={}){let{referrerURLCallback:C,referrerOriginCallback:N}=S;if(n.referrer===`no-referrer`||n.referrerPolicy===``)return null;let F=n.referrerPolicy;if(n.referrer===`about:client`)return`no-referrer`;let I=new mn(n.referrer),H=stripURLForUseAsAReferrer(I),W=stripURLForUseAsAReferrer(I,!0);H.toString().length>4096&&(H=W),C&&(H=C(H)),N&&(W=N(W));let q=new mn(n.url);switch(F){case`no-referrer`:return`no-referrer`;case`origin`:return W;case`unsafe-url`:return H;case`strict-origin`:return isUrlPotentiallyTrustworthy(H)&&!isUrlPotentiallyTrustworthy(q)?`no-referrer`:W.toString();case`strict-origin-when-cross-origin`:return H.origin===q.origin?H:isUrlPotentiallyTrustworthy(H)&&!isUrlPotentiallyTrustworthy(q)?`no-referrer`:W;case`same-origin`:return H.origin===q.origin?H:`no-referrer`;case`origin-when-cross-origin`:return H.origin===q.origin?H:W;case`no-referrer-when-downgrade`:return isUrlPotentiallyTrustworthy(H)&&!isUrlPotentiallyTrustworthy(q)?`no-referrer`:H;default:throw TypeError(`Invalid referrerPolicy: ${F}`)}}function parseReferrerPolicyFromHeader(n){let S=(n.get(`referrer-policy`)||``).split(/[,\s]+/),C=``;for(let n of S)n&&ba.has(n)&&(C=n);return C}gn(),pt(),Rr();const xa=Symbol(`Request internals`);let Sa=null;function envPositiveInt(n,S){let C=ft.getenv(n);if(!C)return S;let N=Number.parseInt(C,10);return Number.isFinite(N)&&N>0?N:S}function shouldAcceptAnyCert(n){return n===!1?!0:n===!0?!1:ft.getenv(`NODE_TLS_REJECT_UNAUTHORIZED`)===`0`}function getSharedSession(n){if(Sa===null){let S=envPositiveInt(`GJSIFY_FETCH_MAX_CONNS_PER_HOST`,16),C=Math.max(envPositiveInt(`GJSIFY_FETCH_MAX_CONNS`,64),S);Sa=new n.Session({maxConns:C,maxConnsPerHost:S}),Sa.remove_feature_by_type(n.ContentDecoder.$gtype)}return Sa}const isRequest=n=>typeof n==`object`&&typeof n.url==`string`;var Ca=class Request extends Body{cache;credentials;destination;get headers(){return this[xa].headers}integrity;keepalive;get method(){return this[xa].method}mode;get redirect(){return this[xa].redirect}get referrer(){if(this[xa].referrer===`no-referrer`)return``;if(this[xa].referrer===`client`)return`about:client`;if(this[xa].referrer)return this[xa].referrer.toString()}get referrerPolicy(){return this[xa].referrerPolicy}set referrerPolicy(n){this[xa].referrerPolicy=validateReferrerPolicy(n)}get signal(){return this[xa].signal}get url(){return this[xa].parsedURL.toString()}get _uri(){return ft.Uri.parse(this.url,ft.UriFlags.ENCODED)}get _session(){return this[xa].session}get _message(){return this[xa].message}get _inputStream(){return this[xa].inputStream}get[Symbol.toStringTag](){return`Request`}[xa];follow;compress=!1;counter=0;agent=``;highWaterMark=16384;insecureHTTPParser=!1;rejectUnauthorized;constructor(n,S){let C=n,N=S||{},F,I={};if(isRequest(n)?(F=new mn(C.url),I=C):F=new mn(n),F.username!==``||F.password!==``)throw TypeError(`${F} is an url with embedded credentials.`);let H=N.method||I.method||`GET`;if(/^(delete|get|head|options|post|put)$/i.test(H)&&(H=H.toUpperCase()),(S?.body!=null||isRequest(n)&&C.body!==null)&&(H===`GET`||H===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body`);let W=S?.body?S.body:isRequest(n)&&C.body!==null?clone(n):null;super(W,{size:N.size||0});let q=new zi(S?.headers||C.headers||{});if(W!==null&&!q.has(`Content-Type`)){let n=extractContentType(W,this);n&&q.set(`Content-Type`,n)}let Y=isRequest(n)?C.signal:null;if(S&&`signal`in S&&(Y=S.signal),Y!=null&&!isAbortSignal(Y))throw TypeError(`Expected signal to be an instanceof AbortSignal or EventTarget`);let X=S?.referrer==null?C.referrer:S.referrer;if(X===``)X=`no-referrer`;else if(X){let n=new mn(X);X=/^about:(\/\/)?client$/.test(n.toString())?`client`:n}else X=void 0;this[xa]={method:H,redirect:S?.redirect||C.redirect||`follow`,headers:q,parsedURL:F,signal:Y,referrer:X,referrerPolicy:``,session:null,message:null},this.follow=N.follow===void 0?C.follow===void 0?20:C.follow:N.follow,this.compress=N.compress===void 0?C.compress===void 0?!0:C.compress:N.compress,this.counter=N.counter||C.counter||0,this.agent=N.agent||C.agent,this.highWaterMark=N.highWaterMark||C.highWaterMark||16384,this.insecureHTTPParser=N.insecureHTTPParser||C.insecureHTTPParser||!1,this.rejectUnauthorized=N.rejectUnauthorized??C.rejectUnauthorized,this.referrerPolicy=S?.referrerPolicy||C.referrerPolicy||``}async _send(n){let{signal:S,parsedURL:C}=this[xa],N=C.protocol;if(N!==`http:`&&N!==`https:`)throw Error(`Cannot send request: no Soup session (non-HTTP URL?)`);let F=await loadSoup(),I=getSharedSession(F),H=new F.Message({method:this[xa].method,uri:ft.Uri.parse(C.toString(),ft.UriFlags.ENCODED)});this[xa].session=I,this[xa].message=H,n.headers._appendToSoupMessage(F,H);let W=this._rawBodyBuffer;if(W!==null&&W.byteLength>0){let S=n.headers.get(`content-type`)||null;H.set_request_body_from_bytes(S,new ft.Bytes(W))}C.protocol===`https:`&&shouldAcceptAnyCert(this.rejectUnauthorized)&&H.connect(`accept-certificate`,(n,S,C)=>!0);let q=new Lr.Cancellable;return S&&(S.aborted?q.cancel():S.addEventListener(`abort`,()=>q.cancel(),{once:!0})),this[xa].inputStream=await soupSendAsync(I,H,ft.PRIORITY_DEFAULT,q),this[xa].readable=inputStreamToReadable(this[xa].inputStream),{inputStream:this[xa].inputStream,readable:this[xa].readable,cancellable:q}}clone(){return new Request(this)}async arrayBuffer(){return super.arrayBuffer()}async blob(){return super.blob()}async formData(){return super.formData()}async json(){return super.json()}async text(){return super.text()}};Object.defineProperties(Ca.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});const getSoupRequestOptions=n=>{let{parsedURL:S}=n[xa],C=new zi(n[xa].headers);C.has(`Accept`)||C.set(`Accept`,`*/*`);let N=null;if(n.body===null&&/^(post|put)$/i.test(n.method)&&(N=`0`),n.body!==null){let S=getTotalBytes(n);typeof S==`number`&&!Number.isNaN(S)&&(N=String(S))}N&&C.set(`Content-Length`,N),n.referrerPolicy===``&&(n.referrerPolicy=`strict-origin-when-cross-origin`),n.referrer&&n.referrer!==`no-referrer`?n[xa].referrer=determineRequestsReferrer(n):n[xa].referrer=`no-referrer`,n[xa].referrer instanceof mn&&C.set(`Referer`,n.referrer),C.has(`User-Agent`)||C.set(`User-Agent`,`gjsify-fetch`),n.compress&&!C.has(`Accept-Encoding`)&&C.set(`Accept-Encoding`,`gzip, deflate`);let{agent:F}=n;return typeof F==`function`&&(F=F(S)),!C.has(`Connection`)&&!F&&C.set(`Connection`,`close`),{parsedURL:S,options:{headers:C}}};var AbortError=class extends FetchBaseError{constructor(n,S=`aborted`){super(n,S)}};function parseDataUri(n){let S=n.match(/^data:([^,]*?)(;base64)?,(.*)$/s);if(!S)throw TypeError(`Invalid data URI: ${n.slice(0,50)}...`);let C=S[1]||`text/plain;charset=US-ASCII`,N=!!S[2],F=S[3],I;if(N){let n=atob(F);I=new Uint8Array(n.length);for(let S=0;S<n.length;S++)I[S]=n.charCodeAt(S)}else I=new TextEncoder().encode(decodeURIComponent(F));return{buffer:I,typeFull:C}}Be();function rewriteRootRelativeUrl(n,S){if(!n.startsWith(`/`)||n.startsWith(`//`))return n;let C=lastPathSeparatorIndex(S);return C<=0?n:`${pathToFileUrlHref(S.slice(0,C))}${n}`}function resolveRootRelativeUrl(n){return rewriteRootRelativeUrl(n,N.programPath??N.programInvocationName??``)}ye(),Bi(),gn(),gi(),pt();const wa=new Set([`data:`,`http:`,`https:`,`file:`]);function rewriteFetchInput(n){if(typeof n!=`string`)return n;let S=resolveRootRelativeUrl(n);return S!==n&&globalThis.__GJSIFY_DEBUG_FETCH===!0&&ve.log(`[fetch] rewrite ${n} → ${S}`),S}async function fetch$1(n,S={}){n=rewriteFetchInput(n);let C=new Ca(n,S),{parsedURL:N,options:F}=getSoupRequestOptions(C);if(!wa.has(N.protocol))throw TypeError(`@gjsify/fetch cannot load ${n}. URL scheme "${N.protocol.replace(/:$/,``)}" is not supported.`);if(N.protocol===`data:`){let{buffer:n,typeFull:S}=parseDataUri(C.url);return new ra(Buffer.from(n),{headers:{"Content-Type":S}})}if(N.protocol===`file:`){let n=globalThis.__GJSIFY_DEBUG_FETCH===!0;n&&ve.log(`[fetch] file:// ${C.url}`);try{let S=ft.filename_from_uri(C.url)[0];n&&ve.log(`[fetch] file:// path=${S}`);let[N,F]=ft.file_get_contents(S);if(n&&ve.log(`[fetch] file:// ok=${N} bytes=${F?.byteLength??`?`}`),!N)throw new FetchError(`Failed to read file: ${S}`,`system`);let I=F,H=new Uint8Array(I.byteLength);H.set(I);let W=new ra(H);return n&&ve.log(`[fetch] file:// response created`),W}catch(S){let N=S instanceof Error?S:Error(String(S));throw n&&ve.warn(`[fetch] file:// FAIL: ${N.message}`),new FetchError(`request to ${C.url} failed, reason: ${N.message}`,`system`,N)}}let{signal:I}=C;if(I&&I.aborted)throw new AbortError(`The operation was aborted.`);let H,W;try{let n=await C._send(F);H=n.readable,W=n.cancellable}catch(n){if(I&&I.aborted)throw new AbortError(`The operation was aborted.`);let S=n instanceof Error?n:Error(String(n));throw new FetchError(`request to ${C.url} failed, reason: ${S.message}`,`system`,S)}let abortHandler=()=>{W.cancel()};I&&I.addEventListener(`abort`,abortHandler,{once:!0});let finalize=()=>{I&&I.removeEventListener(`abort`,abortHandler)};W.connect(()=>{H.destroy(new AbortError(`The operation was aborted.`))}),H.on(`error`,n=>{finalize()});let q=C._message,Y=await loadSoup(),X=zi._newFromSoupMessage(Y,q),Z=q.status_code,te=q.get_reason_phrase();if(isRedirect(Z)){let n=X.get(`Location`),N=null;try{N=n===null?null:new mn(n,C.url)}catch{if(C.redirect!==`manual`)throw finalize(),new FetchError(`uri requested responds with an invalid redirect URL: ${n}`,`invalid-redirect`)}switch(C.redirect){case`error`:throw finalize(),new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${C.url}`,`no-redirect`);case`manual`:break;case`follow`:{if(N===null)break;if(C.counter>=C.follow)throw finalize(),new FetchError(`maximum redirect reached at: ${C.url}`,`max-redirect`);let n={headers:new zi(C.headers),follow:C.follow,counter:C.counter+1,agent:C.agent,compress:C.compress,method:C.method,body:clone(C),signal:C.signal,size:C.size,referrer:C.referrer,referrerPolicy:C.referrerPolicy};if(!isDomainOrSubdomain(C.url,N)||!isSameProtocol(C.url,N))for(let S of[`authorization`,`www-authenticate`,`cookie`,`cookie2`])n.headers.delete(S);if(Z!==303&&C.body&&S.body instanceof hi.Readable)throw finalize(),new FetchError(`Cannot follow redirect with body being a readable stream`,`unsupported-redirect`);(Z===303||(Z===301||Z===302)&&C.method===`POST`)&&(n.method=`GET`,n.body=void 0,n.headers.delete(`content-length`));let F=parseReferrerPolicyFromHeader(X);return F&&(n.referrerPolicy=F),finalize(),fetch$1(new Ca(N,n))}default:throw TypeError(`Redirect option '${C.redirect}' is not a valid value of RequestRedirect`)}}let re={url:C.url,status:Z,statusText:te,headers:X,size:C.size,counter:C.counter,highWaterMark:C.highWaterMark},ie=X.get(`Content-Encoding`);if(!C.compress||C.method===`HEAD`||ie===null||Z===204||Z===304)return finalize(),new ra(H,re);if(typeof DecompressionStream<`u`){let n=null;if(ie===`gzip`||ie===`x-gzip`?n=`gzip`:(ie===`deflate`||ie===`x-deflate`)&&(n=`deflate`),n){let S=new ne([await new ra(H,re).arrayBuffer()]).stream().pipeThrough(new DecompressionStream(n));return finalize(),new ra(S,re)}}return finalize(),new ra(H,re)}__name$1(fetch$1,`fetch`);const Ta=globalThis;globalThis.fetch===void 0&&(Ta.fetch=fetch$1),globalThis.Headers===void 0&&(Ta.Headers=zi),globalThis.Request===void 0&&(Ta.Request=Ca),globalThis.Response===void 0&&(Ta.Response=ra);const Ea=globalThis;globalThis.ByteLengthQueuingStrategy===void 0&&(Ea.ByteLengthQueuingStrategy=jr),globalThis.CountQueuingStrategy===void 0&&(Ea.CountQueuingStrategy=Mr);const Da=globalThis;function isNativeStreamUsable$2(n,S){try{return typeof n==`function`?typeof n.prototype?.[S]==`function`:!1}catch{return!1}}__name$1(isNativeStreamUsable$2,`isNativeStreamUsable`),isNativeStreamUsable$2(globalThis.ReadableStream,`getReader`)||(Da.ReadableStream=Or),Da.ReadableStreamBYOBReader===void 0&&(Da.ReadableStreamBYOBReader=ReadableStreamBYOBReader),Da.ReadableStreamBYOBRequest===void 0&&(Da.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest),Da.ReadableByteStreamController===void 0&&(Da.ReadableByteStreamController=ReadableByteStreamController),Da.ReadableStreamDefaultController===void 0&&(Da.ReadableStreamDefaultController=ReadableStreamDefaultController),Da.ReadableStreamDefaultReader===void 0&&(Da.ReadableStreamDefaultReader=ReadableStreamDefaultReader);const Oa=globalThis;globalThis.TextEncoderStream===void 0&&(Oa.TextEncoderStream=Nr),globalThis.TextDecoderStream===void 0&&(Oa.TextDecoderStream=Pr);function isNativeStreamUsable$1(n,S){try{return typeof n==`function`?typeof n.prototype?.[S]==`function`:!1}catch{return!1}}if(__name$1(isNativeStreamUsable$1,`isNativeStreamUsable`),!isNativeStreamUsable$1(globalThis.TransformStream,`readable`)){let n=globalThis;n.TransformStream=Ar}function isNativeStreamUsable(n,S){try{return typeof n==`function`?typeof n.prototype?.[S]==`function`:!1}catch{return!1}}if(!isNativeStreamUsable(globalThis.WritableStream,`getWriter`)){let n=globalThis;n.WritableStream=kr}var CryptoKey=class{type;extractable;algorithm;usages;_handle;constructor(n,S,C,N,F){this.type=n,this.extractable=S,this.algorithm=Object.freeze({...C}),this.usages=Object.freeze([...N]),this._handle=F}get[Symbol.toStringTag](){return`CryptoKey`}};const ka=Uint8Array.of(166,166,166,166,166,166,166,166);function xorCounter(n,S){for(let C=0;C<8&&S>0;C++)n[7-C]^=S&255,S=Math.floor(S/256)}function aesKeyWrap(n,S){if(n.length<16||n.length%8!=0)throw new DOMException(`AES-KW: key data must be a multiple of 8 bytes and at least 16 bytes`,`OperationError`);let C=n.length/8,N=ka.slice(),F=[];for(let S=0;S<C;S++)F.push(n.slice(S*8,S*8+8));let I=new Uint8Array(16);for(let n=0;n<=5;n++)for(let H=1;H<=C;H++){I.set(N,0),I.set(F[H-1],8);let W=S(I);N.set(W.subarray(0,8)),xorCounter(N,C*n+H),F[H-1]=W.slice(8,16)}let H=new Uint8Array((C+1)*8);H.set(N,0);for(let n=0;n<C;n++)H.set(F[n],(n+1)*8);return H}function aesKeyUnwrap(n,S){if(n.length<24||n.length%8!=0)throw new DOMException(`AES-KW: wrapped key must be a multiple of 8 bytes and at least 24 bytes`,`OperationError`);let C=n.length/8-1,N=n.slice(0,8),F=[];for(let S=0;S<C;S++)F.push(n.slice((S+1)*8,(S+2)*8));let I=new Uint8Array(16);for(let n=5;n>=0;n--)for(let H=C;H>=1;H--){xorCounter(N,C*n+H),I.set(N,0),I.set(F[H-1],8);let W=S(I);N.set(W.subarray(0,8)),F[H-1]=W.slice(8,16)}let H=!0;for(let n=0;n<8;n++)N[n]!==ka[n]&&(H=!1);if(!H)throw new DOMException(`AES-KW: integrity check failed`,`OperationError`);let W=new Uint8Array(C*8);for(let n=0;n<C;n++)W.set(F[n],n*8);return W}function normalizeAlgorithm$1(n){if(typeof n==`string`)return{name:n};if(!n||typeof n.name!=`string`)throw TypeError(`Algorithm must have a name property`);return n}__name$1(normalizeAlgorithm$1,`normalizeAlgorithm`);const Aa={"SHA-1":`sha1`,"SHA-256":`sha256`,"SHA-384":`sha384`,"SHA-512":`sha512`};function toNodeHashName(n){let S=Aa[n.toUpperCase()]||Aa[n];if(!S)throw new On(`Unrecognized hash name: ${n}`,`NotSupportedError`);return S}const ja={"P-256":`prime256v1`,"P-384":`secp384r1`,"P-521":`secp521r1`};function toNodeCurveName(n){let S=ja[n];if(!S)throw new On(`Unrecognized curve name: ${n}`,`NotSupportedError`);return S}function hashSize$1(n){switch(toNodeHashName(n)){case`sha1`:return 20;case`sha256`:return 32;case`sha384`:return 48;case`sha512`:return 64;default:throw new On(`Unsupported hash: ${n}`,`NotSupportedError`)}}__name$1(hashSize$1,`hashSize`);function validateUsages(n,S){for(let C of n)if(!S.includes(C))throw new On(`Invalid key usage: ${C}`,`SyntaxError`);if(n.length===0)throw new On(`Key usages must not be empty`,`SyntaxError`)}function checkUsage(n,S){if(!n.usages.includes(S))throw new On(`Key does not support the '${S}' usage`,`InvalidAccessError`)}const Ma=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Na=new Uint8Array(128);for(let n=0;n<64;n++)Na[Ma.charCodeAt(n)]=n;function bytesToBase64$1(n){let S=``,C=n.length;for(let N=0;N<C;N+=3){let F=n[N],I=N+1<C?n[N+1]:0,H=N+2<C?n[N+2]:0;S+=Ma[F>>2&63],S+=Ma[(F<<4|I>>4)&63],S+=N+1<C?Ma[(I<<2|H>>6)&63]:`=`,S+=N+2<C?Ma[H&63]:`=`}return S}__name$1(bytesToBase64$1,`bytesToBase64`);function base64ToBytes(n){let S=n;for(;S.endsWith(`=`);)S=S.slice(0,-1);let C=[],N=0,F=0;for(let n=0;n<S.length;n++)F=F<<6|Na[S.charCodeAt(n)],N+=6,N>=8&&(N-=8,C.push(F>>N&255));return new Uint8Array(C)}function base64urlEncode(n){return bytesToBase64$1(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function base64urlDecode(n){let S=n.replace(/-/g,`+`).replace(/_/g,`/`);for(;S.length%4;)S+=`=`;return base64ToBytes(S)}function toUint8Array(n){if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);throw TypeError(`Expected BufferSource`)}var Pa,Fa=__esmMin(()=>{Pa={RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_PKCS1_PSS_PADDING:6,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8}});function timingSafeEqual(n,S){if(n.length!==S.length)throw RangeError(`Input buffers must have the same byte length`);let C=0;for(let N=0;N<n.length;N++)C|=n[N]^S[N];return C===0}var Ia=__esmMin(()=>{});function gmul(n,S){let C=0;for(let N=0;N<8;N++){S&1&&(C^=n);let N=n&128;n=n<<1&255,N&&(n^=27),S>>=1}return C}function keyExpansion(n){let S=n.length/4,C=S+6,N=4*(C+1),F=Array.from({length:N});for(let C=0;C<S;C++)F[C]=new Uint8Array([n[4*C],n[4*C+1],n[4*C+2],n[4*C+3]]);for(let n=S;n<N;n++){let C=new Uint8Array(F[n-1]);n%S===0?C=new Uint8Array([La[C[1]]^za[n/S-1],La[C[2]],La[C[3]],La[C[0]]]):S>6&&n%S===4&&(C=new Uint8Array([La[C[0]],La[C[1]],La[C[2]],La[C[3]]])),F[n]=new Uint8Array(4);for(let N=0;N<4;N++)F[n][N]=F[n-S][N]^C[N]}let I=[];for(let n=0;n<=C;n++){let S=new Uint8Array(16);for(let C=0;C<4;C++)S[4*C]=F[4*n+C][0],S[4*C+1]=F[4*n+C][1],S[4*C+2]=F[4*n+C][2],S[4*C+3]=F[4*n+C][3];I.push(S)}return I}function aesEncryptBlock(n,S){let C=new Uint8Array(n),N=S.length-1;for(let n=0;n<16;n++)C[n]^=S[0][n];for(let n=1;n<N;n++){for(let n=0;n<16;n++)C[n]=La[C[n]];let N=C[1];C[1]=C[5],C[5]=C[9],C[9]=C[13],C[13]=N;let F=C[2],I=C[6];C[2]=C[10],C[6]=C[14],C[10]=F,C[14]=I;let H=C[15];C[15]=C[11],C[11]=C[7],C[7]=C[3],C[3]=H;for(let n=0;n<4;n++){let S=n*4,N=C[S],F=C[S+1],I=C[S+2],H=C[S+3];C[S]=gmul(2,N)^gmul(3,F)^I^H,C[S+1]=N^gmul(2,F)^gmul(3,I)^H,C[S+2]=N^F^gmul(2,I)^gmul(3,H),C[S+3]=gmul(3,N)^F^I^gmul(2,H)}for(let N=0;N<16;N++)C[N]^=S[n][N]}for(let n=0;n<16;n++)C[n]=La[C[n]];let F=C[1];C[1]=C[5],C[5]=C[9],C[9]=C[13],C[13]=F;let I=C[2],H=C[6];C[2]=C[10],C[6]=C[14],C[10]=I,C[14]=H;let W=C[15];C[15]=C[11],C[11]=C[7],C[7]=C[3],C[3]=W;for(let n=0;n<16;n++)C[n]^=S[N][n];return C}function aesDecryptBlock(n,S){let C=new Uint8Array(n),N=S.length-1;for(let n=0;n<16;n++)C[n]^=S[N][n];for(let n=N-1;n>0;n--){let N=C[13];C[13]=C[9],C[9]=C[5],C[5]=C[1],C[1]=N;let F=C[10],I=C[14];C[10]=C[2],C[14]=C[6],C[2]=F,C[6]=I;let H=C[3];C[3]=C[7],C[7]=C[11],C[11]=C[15],C[15]=H;for(let n=0;n<16;n++)C[n]=Ra[C[n]];for(let N=0;N<16;N++)C[N]^=S[n][N];for(let n=0;n<4;n++){let S=n*4,N=C[S],F=C[S+1],I=C[S+2],H=C[S+3];C[S]=gmul(14,N)^gmul(11,F)^gmul(13,I)^gmul(9,H),C[S+1]=gmul(9,N)^gmul(14,F)^gmul(11,I)^gmul(13,H),C[S+2]=gmul(13,N)^gmul(9,F)^gmul(14,I)^gmul(11,H),C[S+3]=gmul(11,N)^gmul(13,F)^gmul(9,I)^gmul(14,H)}}let F=C[13];C[13]=C[9],C[9]=C[5],C[5]=C[1],C[1]=F;let I=C[10],H=C[14];C[10]=C[2],C[14]=C[6],C[2]=I,C[6]=H;let W=C[3];C[3]=C[7],C[7]=C[11],C[11]=C[15],C[15]=W;for(let n=0;n<16;n++)C[n]=Ra[C[n]];for(let n=0;n<16;n++)C[n]^=S[0][n];return C}function incrementCounter(n){for(let S=15;S>=0&&++n[S]===0;S--);}function gcmIncrementCounter(n){for(let S=15;S>=12&&++n[S]===0;S--);}function gfMul(n,S){let C=new Uint8Array(16),N=new Uint8Array(n);for(let n=0;n<128;n++){if(S[n>>>3]&1<<7-(n&7))for(let n=0;n<16;n++)C[n]^=N[n];let F=N[15]&1;for(let n=15;n>0;n--)N[n]=N[n]>>>1|(N[n-1]&1)<<7;N[0]>>>=1,F&&(N[0]^=225)}return C}function ghash(n,S,C){let N=new Uint8Array(16),F=Math.ceil(S.length/16)||0;for(let C=0;C<F;C++){let F=C*16,I=Math.min(F+16,S.length);for(let n=0;n<16;n++){let C=F+n;C<I&&(N[n]^=S[C])}let H=gfMul(N,n);N.set(H)}let I=Math.ceil(C.length/16)||0;for(let S=0;S<I;S++){let F=S*16,I=Math.min(F+16,C.length);for(let n=0;n<16;n++){let S=F+n;S<I&&(N[n]^=C[S])}let H=gfMul(N,n);N.set(H)}let H=new Uint8Array(16),W=S.length*8,q=C.length*8,Y=Math.floor(W/4294967296),X=W>>>0;H[0]=Y>>>24&255,H[1]=Y>>>16&255,H[2]=Y>>>8&255,H[3]=Y&255,H[4]=X>>>24&255,H[5]=X>>>16&255,H[6]=X>>>8&255,H[7]=X&255;let Z=Math.floor(q/4294967296),te=q>>>0;H[8]=Z>>>24&255,H[9]=Z>>>16&255,H[10]=Z>>>8&255,H[11]=Z&255,H[12]=te>>>24&255,H[13]=te>>>16&255,H[14]=te>>>8&255,H[15]=te&255;for(let n=0;n<16;n++)N[n]^=H[n];let ne=gfMul(N,n);return N.set(ne),N}var La,Ra,za,Ba=__esmMin(()=>{La=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),Ra=new Uint8Array([82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125]),za=[1,2,4,8,16,32,64,128,27,54]});function parseAlgorithm(n){let S=n.toLowerCase().match(/^aes-(128|192|256)-(cbc|ctr|ecb|cfb|ofb|gcm)$/);if(!S)throw Error(`Unsupported cipher algorithm: ${n}`);let C=parseInt(S[1]),N=S[2];return{keySize:C/8,ivSize:N===`ecb`?0:N===`gcm`?12:16,mode:N}}function toBuffer$2(n,S){return typeof n==`string`?$e.from(n,S||`utf8`):$e.from(n)}function encodeOutput(n,S){return S?$e.from(n).toString(S):$e.from(n)}function incompleteUtf8Tail(n){if(n.length===0)return 0;let S=n.length;for(let C=1;C<=Math.min(4,S);C++){let N=n[S-C];if(!(N&128))return 0;if((N&192)==128)continue;let F;if((N&224)==192)F=2;else if((N&240)==224)F=3;else if((N&248)==240)F=4;else return 0;return C<F?C:0}return 0}function pkcs7Pad(n){let S=16-n.length%16,C=new Uint8Array(n.length+S);C.set(n);for(let N=n.length;N<C.length;N++)C[N]=S;return C}function pkcs7Unpad(n){if(n.length===0||n.length%16!=0)throw Error(`bad decrypt`);let S=n[n.length-1];if(S===0||S>16)throw Error(`bad decrypt`);for(let C=n.length-S;C<n.length;C++)if(n[C]!==S)throw Error(`bad decrypt`);return new Uint8Array(n.slice(0,n.length-S))}var Va=__esmMin(()=>{lt(),__name$1(toBuffer$2,`toBuffer`)});function createCipher(n,S){throw Error(`crypto.createCipher() is deprecated. Use createCipheriv() instead.`)}function createCipheriv(n,S,C){return new Cipher(n,typeof S==`string`?$e.from(S):new Uint8Array(S),C==null?null:typeof C==`string`?$e.from(C):new Uint8Array(C))}function createDecipher(n,S){throw Error(`crypto.createDecipher() is deprecated. Use createDecipheriv() instead.`)}function createDecipheriv(n,S,C){return new Decipher(n,typeof S==`string`?$e.from(S):new Uint8Array(S),C==null?null:typeof C==`string`?$e.from(C):new Uint8Array(C))}function getCiphers(){return[`aes-128-cbc`,`aes-128-ecb`,`aes-192-cbc`,`aes-192-ecb`,`aes-256-cbc`,`aes-256-ecb`,`aes-128-ctr`,`aes-192-ctr`,`aes-256-ctr`,`aes-128-cfb`,`aes-192-cfb`,`aes-256-cfb`,`aes-128-gcm`,`aes-192-gcm`,`aes-256-gcm`]}var CipherBase,Cipher,Decipher,Ha=__esmMin(()=>{Ba(),Va(),lt(),CipherBase=class{_roundKeys;_iv;_mode;_buffer=new Uint8Array;_autoPadding=!0;_finalized=!1;constructor(n,S,C){let N=parseAlgorithm(n);if(S.length!==N.keySize)throw Error(`Invalid key length ${S.length}, expected ${N.keySize} for ${n}`);if(N.ivSize>0&&(!C||C.length!==N.ivSize))throw Error(`Invalid IV length ${C?.length??0}, expected ${N.ivSize} for ${n}`);this._roundKeys=keyExpansion(S),this._iv=C?new Uint8Array(C):new Uint8Array(16),this._mode=N.mode}setAutoPadding(n){return this._autoPadding=n,this}},Cipher=class extends CipherBase{_prevBlock;_counter;_gcmH=null;_gcmJ0=null;_gcmAAD=new Uint8Array;_gcmCiphertext=[];_gcmCiphertextLen=0;_gcmAuthTag=null;_gcmAADSet=!1;constructor(n,S,C){super(n,S,C),this._prevBlock=new Uint8Array(this._iv),this._mode===`gcm`?(this._gcmH=aesEncryptBlock(new Uint8Array(16),this._roundKeys),this._gcmJ0=new Uint8Array(16),this._gcmJ0.set(this._iv.subarray(0,12)),this._gcmJ0[15]=1,this._counter=new Uint8Array(this._gcmJ0),gcmIncrementCounter(this._counter)):this._counter=new Uint8Array(this._iv)}setAAD(n){if(this._mode!==`gcm`)throw Error(`setAAD is only supported in GCM mode`);if(this._gcmCiphertextLen>0)throw Error(`setAAD must be called before update()`);return this._gcmAAD=new Uint8Array(n),this._gcmAADSet=!0,this}getAuthTag(){if(this._mode!==`gcm`)throw Error(`getAuthTag is only supported in GCM mode`);if(!this._gcmAuthTag)throw Error(`getAuthTag must be called after final()`);return $e.from(this._gcmAuthTag)}update(n,S,C){let N=toBuffer$2(n,S),F=new Uint8Array(this._buffer.length+N.length);if(F.set(this._buffer),F.set(N,this._buffer.length),this._mode===`gcm`){let n=this._processGcmEncrypt(F);return this._buffer=new Uint8Array,encodeOutput(n,C)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){let n=this._processStream(F);return this._buffer=new Uint8Array,encodeOutput(n,C)}let I=Math.floor(F.length/16)*16,H=[];for(let n=0;n<I;n+=16){let S=F.slice(n,n+16);H.push(this._encryptBlock(S))}this._buffer=F.slice(I);let W=new Uint8Array(H.length*16);for(let n=0;n<H.length;n++)W.set(H[n],n*16);return encodeOutput(W,C)}final(n){if(this._finalized)throw Error(`Cipher already finalized`);if(this._finalized=!0,this._mode===`gcm`){let S=new Uint8Array;this._buffer.length>0&&(S=this._processGcmEncrypt(this._buffer),this._buffer=new Uint8Array);let C=new Uint8Array(this._gcmCiphertextLen),N=0;for(let n of this._gcmCiphertext)C.set(n,N),N+=n.length;let F=ghash(this._gcmH,this._gcmAAD,C),I=aesEncryptBlock(this._gcmJ0,this._roundKeys),H=new Uint8Array(16);for(let n=0;n<16;n++)H[n]=F[n]^I[n];return this._gcmAuthTag=$e.from(H),encodeOutput(S,n)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){if(this._buffer.length>0){let S=this._processStream(this._buffer);return this._buffer=new Uint8Array,encodeOutput(S,n)}return encodeOutput(new Uint8Array,n)}let S=this._buffer;if(this._autoPadding)S=pkcs7Pad(S);else if(S.length%16!=0)throw Error(`data not multiple of block size`);let C=[];for(let n=0;n<S.length;n+=16)C.push(this._encryptBlock(S.slice(n,n+16)));if(this._buffer=new Uint8Array,C.length===0)return encodeOutput(new Uint8Array,n);let N=new Uint8Array(C.length*16);for(let n=0;n<C.length;n++)N.set(C[n],n*16);return encodeOutput(N,n)}_encryptBlock(n){if(this._mode===`cbc`){let S=new Uint8Array(16);for(let C=0;C<16;C++)S[C]=n[C]^this._prevBlock[C];let C=aesEncryptBlock(S,this._roundKeys);return this._prevBlock=C,C}else if(this._mode===`ecb`)return aesEncryptBlock(n,this._roundKeys);throw Error(`Block encryption not supported for mode: ${this._mode}`)}_processStream(n){let S=new Uint8Array(n.length);for(let C=0;C<n.length;C+=16){let N=aesEncryptBlock(this._counter,this._roundKeys),F=Math.min(16,n.length-C);for(let I=0;I<F;I++)S[C+I]=n[C+I]^N[I];incrementCounter(this._counter)}return S}_processGcmEncrypt(n){let S=new Uint8Array(n.length);for(let C=0;C<n.length;C+=16){let N=aesEncryptBlock(this._counter,this._roundKeys),F=Math.min(16,n.length-C);for(let I=0;I<F;I++)S[C+I]=n[C+I]^N[I];gcmIncrementCounter(this._counter)}return this._gcmCiphertext.push(new Uint8Array(S)),this._gcmCiphertextLen+=S.length,S}},Decipher=class extends CipherBase{_prevBlock;_counter;_pendingUtf8=new Uint8Array;_gcmH=null;_gcmJ0=null;_gcmAAD=new Uint8Array;_gcmCiphertext=[];_gcmCiphertextLen=0;_gcmExpectedTag=null;_gcmAADSet=!1;constructor(n,S,C){super(n,S,C),this._prevBlock=new Uint8Array(this._iv),this._mode===`gcm`?(this._gcmH=aesEncryptBlock(new Uint8Array(16),this._roundKeys),this._gcmJ0=new Uint8Array(16),this._gcmJ0.set(this._iv.subarray(0,12)),this._gcmJ0[15]=1,this._counter=new Uint8Array(this._gcmJ0),gcmIncrementCounter(this._counter)):this._counter=new Uint8Array(this._iv)}setAAD(n){if(this._mode!==`gcm`)throw Error(`setAAD is only supported in GCM mode`);if(this._gcmCiphertextLen>0)throw Error(`setAAD must be called before update()`);return this._gcmAAD=new Uint8Array(n),this._gcmAADSet=!0,this}setAuthTag(n){if(this._mode!==`gcm`)throw Error(`setAuthTag is only supported in GCM mode`);return this._gcmExpectedTag=$e.from(n),this}_encodeWithUtf8Handling(n,S,C){if(!S||S!==`utf8`&&S!==`utf-8`)return encodeOutput(n,S);let N;if(this._pendingUtf8.length>0?(N=new Uint8Array(this._pendingUtf8.length+n.length),N.set(this._pendingUtf8),N.set(n,this._pendingUtf8.length),this._pendingUtf8=new Uint8Array):N=n,!C){let n=incompleteUtf8Tail(N);n>0&&(this._pendingUtf8=new Uint8Array(N.slice(N.length-n)),N=new Uint8Array(N.slice(0,N.length-n)))}return $e.from(N).toString(`utf8`)}update(n,S,C){let N=toBuffer$2(n,S),F=new Uint8Array(this._buffer.length+N.length);if(F.set(this._buffer),F.set(N,this._buffer.length),this._mode===`gcm`){this._gcmCiphertext.push(new Uint8Array(F)),this._gcmCiphertextLen+=F.length;let n=this._processGcmDecrypt(F);return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(n,C,!1)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){let n=this._processStream(F);return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(n,C,!1)}let I=Math.floor(F.length/16);if(I===0)return this._buffer=F,this._encodeWithUtf8Handling(new Uint8Array,C,!1);let H=(this._autoPadding?I-1:I)*16,W=[];for(let n=0;n<H;n+=16){let S=F.slice(n,n+16);W.push(this._decryptBlock(S))}this._buffer=F.slice(H);let q=new Uint8Array(W.length*16);for(let n=0;n<W.length;n++)q.set(W[n],n*16);return this._encodeWithUtf8Handling(q,C,!1)}final(n){if(this._finalized)throw Error(`Decipher already finalized`);if(this._finalized=!0,this._mode===`gcm`){let S=new Uint8Array;if(this._buffer.length>0&&(this._gcmCiphertext.push(new Uint8Array(this._buffer)),this._gcmCiphertextLen+=this._buffer.length,S=this._processGcmDecrypt(this._buffer),this._buffer=new Uint8Array),!this._gcmExpectedTag)throw Error(`Unsupported state or unable to authenticate data`);let C=new Uint8Array(this._gcmCiphertextLen),N=0;for(let n of this._gcmCiphertext)C.set(n,N),N+=n.length;let F=ghash(this._gcmH,this._gcmAAD,C),I=aesEncryptBlock(this._gcmJ0,this._roundKeys),H=new Uint8Array(16);for(let n=0;n<16;n++)H[n]=F[n]^I[n];let W=this._gcmExpectedTag,q=Math.min(W.length,16),Y=0;for(let n=0;n<q;n++)Y|=H[n]^W[n];if(Y!==0)throw Error(`Unsupported state or unable to authenticate data`);return this._encodeWithUtf8Handling(S,n,!0)}if(this._mode===`ctr`||this._mode===`cfb`||this._mode===`ofb`){if(this._buffer.length>0){let S=this._processStream(this._buffer);return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(S,n,!0)}return this._encodeWithUtf8Handling(new Uint8Array,n,!0)}if(this._buffer.length===0)return this._encodeWithUtf8Handling(new Uint8Array,n,!0);if(this._buffer.length%16!=0)throw Error(`bad decrypt`);let S=[];for(let n=0;n<this._buffer.length;n+=16)S.push(this._decryptBlock(this._buffer.slice(n,n+16)));let C=new Uint8Array(S.length*16);for(let n=0;n<S.length;n++)C.set(S[n],n*16);let N=this._autoPadding?pkcs7Unpad(C):C;return this._buffer=new Uint8Array,this._encodeWithUtf8Handling(N,n,!0)}_decryptBlock(n){if(this._mode===`cbc`){let S=aesDecryptBlock(n,this._roundKeys),C=new Uint8Array(16);for(let n=0;n<16;n++)C[n]=S[n]^this._prevBlock[n];return this._prevBlock=new Uint8Array(n),C}else if(this._mode===`ecb`)return aesDecryptBlock(n,this._roundKeys);throw Error(`Block decryption not supported for mode: ${this._mode}`)}_processStream(n){let S=new Uint8Array(n.length);for(let C=0;C<n.length;C+=16){let N=aesEncryptBlock(this._counter,this._roundKeys),F=Math.min(16,n.length-C);for(let I=0;I<F;I++)S[C+I]=n[C+I]^N[I];incrementCounter(this._counter)}return S}_processGcmDecrypt(n){let S=new Uint8Array(n.length);for(let C=0;C<n.length;C+=16){let N=aesEncryptBlock(this._counter,this._roundKeys),F=Math.min(16,n.length-C);for(let I=0;I<F;I++)S[C+I]=n[C+I]^N[I];gcmIncrementCounter(this._counter)}return S}}});function gjsGi(){return globalThis.imports?.gi}function fillFromWebCrypto(n,S){for(let C=0;C<n.length;C+=Ua){let N=Math.min(n.length-C,Ua);S.getRandomValues(new Uint8Array(n.buffer,n.byteOffset+C,N))}}function openUrandom(){if(Ga!==null)return Ga;let n=gjsGi()?.Gio;if(!n)return Ga=!1,!1;try{Ga=n.File.new_for_path(`/dev/urandom`).read(null)}catch{Ga=!1}return Ga}function fillFromUrandom(n){let S=openUrandom();if(!S)return!1;try{let C=0;for(;C<n.length;){let N=S.read_bytes(n.length-C,null).toArray();if(N.length===0)return!1;n.set(N,C),C+=N.length}return!0}catch{return!1}}function fillFromGLib(n){let S=gjsGi()?.GLib;if(!S?.random_int_range)return!1;for(let C=0;C<n.length;C++)n[C]=S.random_int_range(0,256);return!0}function fillFromMath(n){for(let S=0;S<n.length;S++)n[S]=Math.floor(Math.random()*256)}function warnInsecureOnce(n){Wa||(Wa=!0,ve.warn(`[@gjsify/webcrypto] No cryptographically secure random source available — falling back to "${n}". Neither GLib.Random nor Math.random is suitable for keys, tokens or IVs. Expected sources: WebCrypto (globalThis.crypto) or /dev/urandom via Gio on GJS.`))}function fillRandomBytes(n,S={}){if(n.length===0)return`webcrypto`;let C=S.webcrypto===void 0?globalThis.crypto??null:S.webcrypto;return C&&typeof C.getRandomValues==`function`?(fillFromWebCrypto(n,C),`webcrypto`):fillFromUrandom(n)?`urandom`:fillFromGLib(n)?(warnInsecureOnce(`glib`),`glib`):(fillFromMath(n),warnInsecureOnce(`math`),`math`)}var Ua,Wa,Ga,Ka=__esmMin(()=>{ye(),Ua=65536,Wa=!1,Ga=null});function fillRandom(n){fillRandomBytes(n)}function randomBytes(n,S){if(typeof n!=`number`||n<0||!Number.isInteger(n))throw TypeError(`The "size" argument must be a non-negative integer. Received ${n}`);try{let C=$e.alloc(n);if(n>0&&fillRandom(new Uint8Array(C.buffer,C.byteOffset,C.byteLength)),S)S(null,C);else return C}catch(n){if(S)S(n,$e.alloc(0));else throw n}}function randomFillSync(n,S=0,C){let N=C??n.length-S;if(S<0||S>n.length)throw RangeError(`The value of "offset" is out of range. Received ${S}`);if(N<0||S+N>n.length)throw RangeError(`The value of "size" is out of range. Received ${N}`);if(N>0){let C=(n instanceof $e,n.byteOffset);fillRandom(new Uint8Array(n.buffer,C+S,N))}return n}function randomFill(n,S,C,N){let F,I,H;typeof S==`function`?(H=S,F=0,I=n.length):typeof C==`function`?(H=C,F=S,I=n.length-S):(H=N,F=S,I=C);try{randomFillSync(n,F,I),H(null,n)}catch(S){H(S,n)}}function randomUUID(){if(typeof globalThis.crypto?.randomUUID==`function`)return globalThis.crypto.randomUUID();let n=new Uint8Array(16);fillRandom(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let S=Array.from(n,n=>n.toString(16).padStart(2,`0`)).join(``);return`${S.slice(0,8)}-${S.slice(8,12)}-${S.slice(12,16)}-${S.slice(16,20)}-${S.slice(20)}`}function randomInt(n,S,C){let N,F,I;if(typeof S==`function`?(I=S,F=n,N=0):typeof S==`number`?(N=n,F=S,I=C):(F=n,N=0,I=C),!Number.isInteger(N))throw TypeError(`The "min" argument must be a safe integer. Received ${N}`);if(!Number.isInteger(F))throw TypeError(`The "max" argument must be a safe integer. Received ${F}`);if(N>=F)throw RangeError(`The value of "min" must be less than "max". Received min: ${N}, max: ${F}`);let H=F-N,W=new Uint32Array(1);fillRandom(new Uint8Array(W.buffer));let q=N+W[0]%H;if(I)I(null,q);else return q}var qa=__esmMin(()=>{lt(),Ka()});function modPow(n,S,C){if(C===1n)return 0n;n=(n%C+C)%C;let N=1n;for(;S>0n;)S&1n&&(N=N*n%C),S>>=1n,n=n*n%C;return N}function bigIntToBytes(n,S){let C=new Uint8Array(S),N=n;for(let n=S-1;n>=0;n--)C[n]=Number(N&255n),N>>=8n;return C}function bytesToBigInt(n){let S=0n;for(let C=0;C<n.length;C++)S=S<<8n|BigInt(n[C]);return S}var Ja=__esmMin(()=>{});function bigIntToBuffer(n){if(n===0n)return $e.from([0]);let S=n.toString(16);return S.length%2!=0&&(S=`0`+S),$e.from(S,`hex`)}function bufferToBigInt(n){if(n.length===0)return 0n;let S=$e.from(n).toString(`hex`);return S.length===0?0n:BigInt(`0x`+S)}function bitLength(n){return n===0n?0:n.toString(2).length}function simpleSieve(n){for(let S of Xa){let C=BigInt(S);if(n%C===0n)return n===C}return!0}function fermatTest(n){return modPow(2n,n-1n,n)===1n}function millerRabinTest(n){if(n<2n)return!1;if(n===2n||n===3n)return!0;if(n%2n==0n)return!1;let S=n-1n,C=0;for(;S%2n==0n;)S/=2n,C++;for(let N of[2n,3n,5n,7n,11n,13n]){if(N>=n)continue;let F=modPow(N,S,n);if(F===1n||F===n-1n)continue;let I=!0;for(let S=0;S<C-1;S++)if(F=modPow(F,2n,n),F===n-1n){I=!1;break}if(I)return!1}return!0}function checkPrime(n,S){let C=S.toString(`hex`),N=0;if(n%2n==0n||!simpleSieve(n)||!fermatTest(n)||!millerRabinTest(n))return N+=1,C===`02`||C===`05`?N+=8:N+=4,N;switch(millerRabinTest(n>>1n)||(N+=2),C){case`02`:n%24n!=11n&&(N+=8);break;case`05`:{let S=n%10n;S!==3n&&S!==7n&&(N+=8)}break;default:N+=4}return N}function getCachedCheckPrime(n,S){let C=S.toString(`hex`)+`_`+n.toString(16);if(C in Za)return Za[C];let N=checkPrime(n,S);return Za[C]=N,N}function formatReturnValue$1(n,S){let C=bigIntToBuffer(n);return S?C.toString(S):C}function generatePrime(n,S){let C=bufferToBigInt(S);if(n<16)return C===2n||C===5n?$e.from([140,123]):$e.from([140,39]);let N=Math.ceil(n/8),F=2n,I=4n;for(;;){let S=bufferToBigInt(randomBytes(N));for(;bitLength(S)>n;)S>>=1n;if(S%F==0n&&(S+=1n),S&F||(S+=F),C===F)for(;S%24n!=11n;)S+=I;else if(C===5n)for(;S%10n!=3n;)S+=I;let H=S>>1n;if(simpleSieve(H)&&simpleSieve(S)&&fermatTest(H)&&fermatTest(S)&&millerRabinTest(H)&&millerRabinTest(S))return bigIntToBuffer(S)}}function createDiffieHellman(n,S,C,N){if(S!==void 0&&typeof S!=`number`&&($e.isBuffer(S)||S instanceof Uint8Array||typeof S==`string`&&!(S in Qa)))return createDiffieHellman(n,`binary`,S,C);let F=S||`binary`,I=N||`binary`,H=$e.from([2]);if(C!==void 0&&(typeof C==`number`?(H=$e.alloc(1),H[0]=C):H=$e.isBuffer(C)?C:$e.from(C,I)),typeof n==`number`)return new DiffieHellman(generatePrime(n,H),H,!0);let W;return W=$e.isBuffer(n)?n:n instanceof Uint8Array?$e.from(n):$e.from(n,F),new DiffieHellman(W,H,!0)}function getDiffieHellman(n){let S=Ya[n];if(!S)throw Error(`Unknown group: ${n}. Supported groups: ${Object.keys(Ya).join(`, `)}`);return new DiffieHellman($e.from(S.prime,`hex`),$e.from(S.gen,`hex`),!1)}var Ya,Xa,Za,DiffieHellman,Qa,$a,eo,to=__esmMin(()=>{Ja(),qa(),lt(),Ya={modp1:{gen:`02`,prime:`ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff`},modp2:{gen:`02`,prime:`ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff`},modp5:{gen:`02`,prime:`ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff`},modp14:{gen:`02`,prime:`ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff`},modp15:{gen:`02`,prime:`ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff`},modp16:{gen:`02`,prime:`ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff`},modp17:{gen:`02`,prime:`ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff`},modp18:{gen:`02`,prime:`ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff`}},Xa=[];{let n=1e3,S=new Uint8Array(1001);for(let C=2;C*C<=n;C++)if(!S[C])for(let N=C*C;N<=n;N+=C)S[N]=1;for(let C=2;C<=n;C++)S[C]||Xa.push(C)}Za={},__name$1(formatReturnValue$1,`formatReturnValue`),DiffieHellman=class{_prime;_generator;_generatorBuf;_primeByteLength;_pubKey;_privKey;_primeCode;_malleable;constructor(n,S,C=!1){this._prime=bufferToBigInt(n),this._generatorBuf=S,this._generator=bufferToBigInt(S),this._primeByteLength=n.length,this._pubKey=void 0,this._privKey=void 0,this._primeCode=void 0,this._malleable=C,C||(this._primeCode=0,this.setPublicKey=void 0,this.setPrivateKey=void 0)}get verifyError(){return typeof this._primeCode!=`number`&&(this._primeCode=getCachedCheckPrime(this._prime,this._generatorBuf)),this._primeCode}generateKeys(n){if(!this._privKey){let n=randomBytes(this._primeByteLength);this._privKey=bufferToBigInt(n)}return this._pubKey=modPow(this._generator,this._privKey,this._prime),this.getPublicKey(n)}computeSecret(n,S,C){let N;N=typeof n==`string`?$e.from(n,S||`utf8`):$e.from(n);let F=bufferToBigInt(N);if(!this._privKey)throw Error(`You must generate keys before computing a secret`);if(F<=0n||F>=this._prime)throw Error(`Supplied key is too large`);let I=bigIntToBuffer(modPow(F,this._privKey,this._prime)),H=this._primeByteLength;if(I.length<H){let n=$e.alloc(H);I.copy(n,H-I.length),I=n}return C?I.toString(C):I}getPrime(n){return formatReturnValue$1(this._prime,n)}getGenerator(n){return formatReturnValue$1(this._generator,n)}getPublicKey(n){if(!this._pubKey)throw Error(`No public key - call generateKeys() first`);return formatReturnValue$1(this._pubKey,n)}getPrivateKey(n){if(!this._privKey)throw Error(`No private key - call generateKeys() first`);return formatReturnValue$1(this._privKey,n)}setPublicKey(n,S){if(!this._malleable)throw Error(`setPublicKey is not available for predefined DH groups`);let C=typeof n==`string`?$e.from(n,S||`utf8`):$e.from(n);this._pubKey=bufferToBigInt(C)}setPrivateKey(n,S){if(!this._malleable)throw Error(`setPrivateKey is not available for predefined DH groups`);let C=typeof n==`string`?$e.from(n,S||`utf8`):$e.from(n);this._privKey=bufferToBigInt(C)}},Qa={binary:!0,hex:!0,base64:!0,latin1:!0,utf8:!0,"utf-8":!0,base64url:!0,ascii:!0,ucs2:!0,"ucs-2":!0,utf16le:!0,"utf-16le":!0},$a=getDiffieHellman,eo=getDiffieHellman});function mod(n,S){let C=n%S;return C<0n?C+S:C}function modInverse$2(n,S){if(n=mod(n,S),n===0n)throw Error(`No modular inverse for zero`);let[C,N]=[n,S],[F,I]=[1n,0n];for(;N!==0n;){let n=C/N;[C,N]=[N,C-n*N],[F,I]=[I,F-n*I]}if(C!==1n)throw Error(`Modular inverse does not exist`);return mod(F,S)}function pointAdd(n,S,C){if(n===null)return S;if(S===null)return n;let{p:N}=C;if(n.x===S.x)return mod(n.y+S.y,N)===0n?null:pointDouble(n,C);let F=mod(S.x-n.x,N),I=mod(mod(S.y-n.y,N)*modInverse$2(F,N),N),H=mod(I*I-n.x-S.x,N);return{x:H,y:mod(I*(n.x-H)-n.y,N)}}function pointDouble(n,S){if(n===null)return null;let{a:C,p:N}=S;if(n.y===0n)return null;let F=mod(mod(3n*n.x*n.x+C,N)*modInverse$2(mod(2n*n.y,N),N),N),I=mod(F*F-2n*n.x,N);return{x:I,y:mod(F*(n.x-I)-n.y,N)}}function scalarMul(n,S,C){if(S===null||n===0n)return null;let{n:N}=C;if(n=mod(n,N),n===0n)return null;let F=null,I=S,H=n.toString(2);for(let n=0;n<H.length;n++)H[n]===`1`?(F=pointAdd(F,I,C),I=pointDouble(I,C)):(I=pointAdd(F,I,C),F=pointDouble(F,C));return F}function bigintToBuffer(n,S){let C=n.toString(16).padStart(S*2,`0`);return $e.from(C,`hex`)}function bufferToBigint(n){let S=$e.from(n).toString(`hex`);return S.length===0?0n:BigInt(`0x`+S)}function encodePublicKey(n,S,C=`uncompressed`){if(n===null)throw Error(`Cannot encode the point at infinity`);let N=bigintToBuffer(n.x,S);if(C===`compressed`){let S=n.y%2n==0n?2:3;return $e.concat([$e.from([S]),N])}let F=bigintToBuffer(n.y,S);if(C===`hybrid`){let S=n.y%2n==0n?6:7;return $e.concat([$e.from([S]),N,F])}return $e.concat([$e.from([4]),N,F])}function decodePublicKey(n,S){let C=$e.from(n);if(C.length===0)throw Error(`Invalid public key: empty buffer`);let N=C[0],{p:F,a:I,b:H,byteLength:W}=S;if(N===4||N===6||N===7){if(C.length!==1+2*W)throw Error(`Invalid public key length: expected ${1+2*W} bytes, got ${C.length}`);let n=bufferToBigint(C.subarray(1,1+W)),S=bufferToBigint(C.subarray(1+W));if(mod(S*S,F)!==mod(n*n*n+I*n+H,F))throw Error(`Invalid public key: point is not on the curve`);return{x:n,y:S}}if(N===2||N===3){if(C.length!==1+W)throw Error(`Invalid public key length: expected ${1+W} bytes, got ${C.length}`);let n=bufferToBigint(C.subarray(1,1+W)),S=sqrtMod(mod(n*n*n+I*n+H,F),F);if(S===null)throw Error(`Invalid public key: no valid y coordinate for the given x`);let q=N===3;return{x:n,y:S%2n!=0n===q?S:mod(F-S,F)}}throw Error(`Invalid public key prefix: 0x${N.toString(16).padStart(2,`0`)}`)}function sqrtMod(n,S){if(n=mod(n,S),n===0n)return 0n;if(modPow(n,(S-1n)/2n,S)!==1n)return null;if(mod(S,4n)===3n)return modPow(n,(S+1n)/4n,S);let C=0n,N=S-1n;for(;mod(N,2n)===0n;)N/=2n,C++;let F=2n;for(;modPow(F,(S-1n)/2n,S)!==S-1n;)F++;let I=C,H=modPow(F,N,S),W=modPow(n,N,S),q=modPow(n,(N+1n)/2n,S);for(;;){if(W===0n)return 0n;if(W===1n)return q;let n=1n,C=mod(W*W,S);for(;C!==1n;)C=mod(C*C,S),n++;let N=modPow(H,modPow(2n,I-n-1n,S-1n),S);I=n,H=mod(N*N,S),W=mod(W*H,S),q=mod(q*N,S)}}function toBuffer$1(n,S){if($e.isBuffer(n))return n;if(n instanceof Uint8Array)return $e.from(n);if(typeof n==`string`)return $e.from(n,S||`utf8`);if(ArrayBuffer.isView(n))return $e.from(n.buffer,n.byteOffset,n.byteLength);throw TypeError(`The "key" argument must be of type string or an instance of Buffer, TypedArray, or DataView.`)}function formatReturnValue(n,S){return S?n.toString(S):n}function resolveCurve(n){let S=n.toLowerCase(),C=ro[S];if(!C)throw Error(`Unsupported curve: ${n}`);let N=no[C];if(!N)throw Error(`Unsupported curve: ${n}`);return{canonical:C,params:N}}function createECDH(n){return new ECDH(n)}function getCurves(){return[`secp256k1`,`prime256v1`,`secp256r1`,`secp384r1`,`secp521r1`]}var no,ro,ECDH,io=__esmMin(()=>{Ja(),qa(),lt(),no={secp256k1:{p:115792089237316195423570985008687907853269984665640564039457584007908834671663n,a:0n,b:7n,Gx:55066263022277343669578718895168534326250603453777594175500187360389116729240n,Gy:32670510020758816978083085130507043184471273380659243275938904335757337482424n,n:115792089237316195423570985008687907852837564279074904382605163141518161494337n,byteLength:32},prime256v1:{p:115792089210356248762697446949407573530086143415290314195533631308867097853951n,a:115792089210356248762697446949407573530086143415290314195533631308867097853951n-3n,b:41058363725152142129326129780047268409114441015993725554835256314039467401291n,Gx:48439561293906451759052585252797914202762949526041747995844080717082404635286n,Gy:36134250956749795798585127919587881956611106672985015071877198253568414405109n,n:115792089210356248762697446949407573529996955224135760342422259061068512044369n,byteLength:32},secp384r1:{p:39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319n,a:39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319n-3n,b:27580193559959705877849011840389048093056905856361568521428707301988689241309860865136260764883745107765439761230575n,Gx:26247035095799689268623156744566981891852923491109213387815615900925518854738050089022388053975719786650872476732087n,Gy:8325710961489029985546751289520108179287853048861315594709205902480503199884419224438643760392947333078086511627871n,n:39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643n,byteLength:48},secp521r1:{p:6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151n,a:6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151n-3n,b:1093849038073734274511112390766805569936207598951683748994586394495953116150735016013708737573759623248592132296706313309438452531591012912142327488478985984n,Gx:2661740802050217063228768716723360960729859168756973147706671368418802944996427808491545080627771902352094241225065558662157113545570916814161637315895999846n,Gy:3757180025770020463545507224491183603594455134769762486694567779615544477440556316691234405012945539562144444537289428522585666729196580810124344277578376784n,n:6864797660130609714981900799081393217269435300143305409394463459185543183397655394245057746333217197532963996371363321113864768612440380340372808892707005449n,byteLength:66}},ro={secp256k1:`secp256k1`,prime256v1:`prime256v1`,secp256r1:`prime256v1`,"p-256":`prime256v1`,p256:`prime256v1`,secp384r1:`secp384r1`,"p-384":`secp384r1`,p384:`secp384r1`,secp521r1:`secp521r1`,"p-521":`secp521r1`,p521:`secp521r1`},__name$1(modInverse$2,`modInverse`),__name$1(toBuffer$1,`toBuffer`),ECDH=class{_curve;_curveName;_privateKey=null;_publicKey=null;constructor(n){let S=resolveCurve(n);this._curve=S.params,this._curveName=S.canonical}generateKeys(n,S){let{n:C,byteLength:N}=this._curve,F;do F=bufferToBigint(randomBytes(N));while(F===0n||F>=C);this._privateKey=F;let I={x:this._curve.Gx,y:this._curve.Gy};return this._publicKey=scalarMul(F,I,this._curve),n===void 0?this.getPublicKey():this.getPublicKey(n,S)}computeSecret(n,S,C){if(this._privateKey===null)throw Error(`ECDH key not generated. Call generateKeys() or setPrivateKey() first.`);let N=decodePublicKey(toBuffer$1(n,S),this._curve);if(N===null)throw Error(`Invalid public key: point at infinity`);let F=scalarMul(this._privateKey,N,this._curve);if(F===null)throw Error(`Shared secret computation resulted in the point at infinity`);return formatReturnValue(bigintToBuffer(F.x,this._curve.byteLength),C)}getPublicKey(n,S){if(this._publicKey===null)throw Error(`ECDH key not generated. Call generateKeys() or setPrivateKey() first.`);return formatReturnValue(encodePublicKey(this._publicKey,this._curve.byteLength,S||`uncompressed`),n)}getPrivateKey(n){if(this._privateKey===null)throw Error(`ECDH key not generated. Call generateKeys() or setPrivateKey() first.`);return formatReturnValue(bigintToBuffer(this._privateKey,this._curve.byteLength),n)}setPublicKey(n,S){let C=toBuffer$1(n,S);this._publicKey=decodePublicKey(C,this._curve)}setPrivateKey(n,S){let C=bufferToBigint(toBuffer$1(n,S));if(C===0n||C>=this._curve.n)throw Error(`Private key is out of range [1, n-1]`);this._privateKey=C;let N={x:this._curve.Gx,y:this._curve.Gy};this._publicKey=scalarMul(C,N,this._curve)}}});function normalizeAlgorithm(n){return n.toLowerCase().replace(/-/g,``)}function hashSize(n){let S=normalizeAlgorithm(n),C=ao[S];if(C===void 0)throw Error(`Unknown hash algorithm: ${n}`);return C}function toBuffer(n,S){return typeof n==`string`?$e.from(n,S||`utf8`):n instanceof DataView?$e.from(n.buffer,n.byteOffset,n.byteLength):(n instanceof ArrayBuffer,$e.from(n))}var ao,oo,so,co=__esmMin(()=>{lt(),ao={md5:16,sha1:20,sha256:32,sha384:48,sha512:64},oo={md5:64,sha1:64,sha256:64,sha384:128,sha512:128},so=new Set([`md5`,`sha1`,`sha256`,`sha384`,`sha512`])});function getChecksumType(n){let S=normalizeAlgorithm(n),C=lo[S];if(C===void 0){let S=Error(`Unknown message digest: ${n}`);throw S.code=`ERR_CRYPTO_HASH_UNKNOWN`,S}return C}function getHashes(){return[`md5`,`sha1`,`sha256`,`sha384`,`sha512`]}function hash(n,S,C){return new uo(n).update(S).digest(C)}var lo,uo,fo=__esmMin(()=>{co(),lt(),pt(),gi(),lo={md5:ft.ChecksumType.MD5,sha1:ft.ChecksumType.SHA1,sha256:ft.ChecksumType.SHA256,sha384:ft.ChecksumType.SHA384,sha512:ft.ChecksumType.SHA512},uo=class Hash extends pi{_algorithm;_checksum;_finalized=!1;constructor(n){super();let S=normalizeAlgorithm(n),C=getChecksumType(S);this._algorithm=S,this._checksum=new ft.Checksum(C)}update(n,S){if(this._finalized)throw Error(`Digest already called`);let C;if(typeof n==`string`){let N=normalizeEncoding(S);C=$e.from(n,N)}else C=n instanceof Uint8Array?n:$e.from(n);return this._checksum.update(C),this}digest(n){if(this._finalized)throw Error(`Digest already called`);this._finalized=!0;let S=this._checksum.get_string(),C=$e.from(S,`hex`);return n?C.toString(n):C}copy(){if(this._finalized)throw Error(`Digest already called`);let n=Object.create(Hash.prototype);return pi.call(n),n._algorithm=this._algorithm,n._finalized=!1,n._checksum=this._checksum.copy(),n}_transform(n,S,C){try{this.update(n,S),C()}catch(n){C(n)}}_flush(n){try{this.push(this.digest()),n()}catch(S){n(S)}}}}),Hmac,po=__esmMin(()=>{co(),fo(),lt(),gi(),Hmac=class extends pi{_algorithm;_innerHash;_outerKeyPad;_finalized=!1;constructor(n,S){super();let C=normalizeAlgorithm(n);if(!so.has(C)){let S=Error(`Unknown message digest: ${n}`);throw S.code=`ERR_CRYPTO_HASH_UNKNOWN`,S}this._algorithm=C;let N;N=typeof S==`string`?$e.from(S,`utf8`):S instanceof Uint8Array?S:$e.from(S);let F=oo[C];if(N.length>F){let n=new uo(C);n.update(N),N=n.digest()}let I=new Uint8Array(F);I.set(N);let H=new Uint8Array(F),W=new Uint8Array(F);for(let n=0;n<F;n++)H[n]=I[n]^54,W[n]=I[n]^92;this._outerKeyPad=W,this._innerHash=new uo(C),this._innerHash.update(H)}update(n,S){if(this._finalized)throw Error(`Digest already called`);let C;if(typeof n==`string`){let N=normalizeEncoding(S);C=$e.from(n,N)}else C=n instanceof Uint8Array?n:$e.from(n);return this._innerHash.update(C),this}digest(n){if(this._finalized)throw Error(`Digest already called`);this._finalized=!0;let S=this._innerHash.digest(),C=new uo(this._algorithm);C.update(this._outerKeyPad),C.update(S);let N=C.digest();return n?N.toString(n):N}_transform(n,S,C){try{this.update(n,S),C()}catch(n){C(n)}}_flush(n){try{this.push(this.digest()),n()}catch(S){n(S)}}}});function getCurve(n){let S=ro[n.toLowerCase()];if(!S)throw Error(`Unsupported curve: ${n}`);return no[S]}function truncateHash(n,S){let C=S.n.toString(2).length,N=bytesToBigInt(n),F=n.length*8;return F>C&&(N>>=BigInt(F-C)),N}function hmacDigest$2(n,S,C){let N=new Hmac(n,S);return N.update(C),new Uint8Array(N.digest())}function rfc6979(n,S,C,N){let F=N.byteLength,I=C.length,H=new Uint8Array(I).fill(1),W=new Uint8Array(I).fill(0),q=bigIntToBytes(S,F),Y=bigIntToBytes(mod(truncateHash(C,N),N.n),F),X=new Uint8Array(I+1+F+F);X.set(H,0),X[I]=0,X.set(q,I+1),X.set(Y,I+1+F),W=hmacDigest$2(n,W,X),H=hmacDigest$2(n,W,H);let Z=new Uint8Array(I+1+F+F);Z.set(H,0),Z[I]=1,Z.set(q,I+1),Z.set(Y,I+1+F),W=hmacDigest$2(n,W,Z),H=hmacDigest$2(n,W,H);for(let S=0;S<100;S++){let S=new Uint8Array;for(;S.length<F;){H=hmacDigest$2(n,W,H);let C=new Uint8Array(S.length+H.length);C.set(S,0),C.set(H,S.length),S=C}let C=truncateHash(S.slice(0,F),N);if(C>=1n&&C<N.n)return C;let q=new Uint8Array(I+1);q.set(H,0),q[I]=0,W=hmacDigest$2(n,W,q),H=hmacDigest$2(n,W,H)}throw Error(`RFC 6979: failed to generate valid k after 100 attempts`)}function ecdsaSign(n,S,C,N){let F=getCurve(N),I={x:F.Gx,y:F.Gy},H=bytesToBigInt(S),W=new uo(n);W.update(C);let q=new Uint8Array(W.digest()),Y=truncateHash(q,F),X=rfc6979(n,H,q,F),Z=scalarMul(X,I,F);if(Z===null)throw Error(`ECDSA: k * G is point at infinity`);let te=mod(Z.x,F.n);if(te===0n)throw Error(`ECDSA: r is zero`);let ne=mod(modInverse$2(X,F.n)*(Y+te*H),F.n);if(ne===0n)throw Error(`ECDSA: s is zero`);let re=F.byteLength,ie=new Uint8Array(re*2);return ie.set(bigIntToBytes(te,re),0),ie.set(bigIntToBytes(ne,re),re),ie}function ecdsaVerify(n,S,C,N,F){let I=getCurve(F),H={x:I.Gx,y:I.Gy},W=I.byteLength;if(S[0]!==4||S.length!==1+W*2)return!1;let q={x:bytesToBigInt(S.slice(1,1+W)),y:bytesToBigInt(S.slice(1+W))};if(C.length!==W*2)return!1;let Y=bytesToBigInt(C.slice(0,W)),X=bytesToBigInt(C.slice(W));if(Y<1n||Y>=I.n||X<1n||X>=I.n)return!1;let Z=new uo(n);Z.update(N);let te=truncateHash(new Uint8Array(Z.digest()),I),ne=modInverse$2(X,I.n),re=mod(te*ne,I.n),ie=mod(Y*ne,I.n),ae=pointAdd(scalarMul(re,H,I),scalarMul(ie,q,I),I);return ae===null?!1:mod(ae.x,I.n)===Y}var mo=__esmMin(()=>{Ja(),io(),fo(),po(),__name$1(hmacDigest$2,`hmacDigest`)});function hmacDigest$1(n,S,C){let N=new Hmac(n,S);return N.update(C),N.digest()}function hkdfExtract(n,S,C){return hmacDigest$1(n,C,S)}function hkdfExpand(n,S,C,N,F){let I=Math.ceil(N/F);if(I>255)throw Error(`HKDF cannot generate more than 255 * HashLen bytes`);let H=$e.allocUnsafe(I*F),W=$e.alloc(0);for(let N=1;N<=I;N++)W=hmacDigest$1(n,S,$e.concat([W,C,$e.from([N])])),W.copy(H,(N-1)*F);return $e.from(H.buffer,H.byteOffset,N)}function hkdfSync(n,S,C,N,F){let I=normalizeAlgorithm(n),H=ao[I];if(!so.has(I)||H===void 0)throw TypeError(`Unknown message digest: ${n}`);if(typeof F!=`number`||F<0)throw TypeError(`keylen must be a non-negative number`);let W=toBuffer(S),q=toBuffer(C),Y=toBuffer(N),X=hkdfExpand(I,hkdfExtract(I,W,q.length===0?$e.alloc(H,0):q),Y,F,H),Z=new ArrayBuffer(X.length);return new Uint8Array(Z).set(X),Z}function hkdf(n,S,C,N,F,I){setTimeout(()=>{try{I(null,hkdfSync(n,S,C,N,F))}catch(n){I(n instanceof Error?n:Error(String(n)))}},0)}var ho=__esmMin(()=>{co(),po(),lt(),__name$1(hmacDigest$1,`hmacDigest`)});function hmacDigest(n,S,C){let N=new Hmac(n,S);return N.update(C),N.digest()}function validateParameters(n,S){if(typeof n!=`number`||n<0||!Number.isFinite(n)||n===0)throw TypeError(`iterations must be a positive number`);if(typeof S!=`number`||S<0||!Number.isFinite(S)||S>2147483647)throw TypeError(`keylen must be a positive number`)}function pbkdf2Sync(n,S,C,N,F){validateParameters(C,N);let I=toBuffer(n),H=toBuffer(S),W=normalizeAlgorithm(F||`sha1`),q=ao[W];if(!so.has(W)||q===void 0)throw TypeError(`Unknown message digest: ${F||`sha1`}`);if(N===0)return $e.alloc(0);let Y=Math.ceil(N/q),X=$e.allocUnsafe(Y*q);for(let n=1;n<=Y;n++){let S=$e.allocUnsafe(H.length+4);H.copy(S,0),S.writeUInt32BE(n,H.length);let N=hmacDigest(W,I,S),F=$e.from(N);for(let n=1;n<C;n++){N=hmacDigest(W,I,N);for(let n=0;n<q;n++)F[n]^=N[n]}F.copy(X,(n-1)*q)}return $e.from(X.buffer,X.byteOffset,N)}function pbkdf2(n,S,C,N,F,I){validateParameters(C,N),setTimeout(()=>{try{I(null,pbkdf2Sync(n,S,C,N,F))}catch(n){I(n instanceof Error?n:Error(String(n)))}},0)}var go=__esmMin(()=>{co(),po(),lt()});function R$2(n,S){return(n<<S|n>>>32-S)>>>0}function salsa20_8(n){let S=new Uint32Array(16);for(let C=0;C<16;C++)S[C]=n[C];for(let n=0;n<4;n++)S[4]^=R$2(S[0]+S[12],7),S[8]^=R$2(S[4]+S[0],9),S[12]^=R$2(S[8]+S[4],13),S[0]^=R$2(S[12]+S[8],18),S[9]^=R$2(S[5]+S[1],7),S[13]^=R$2(S[9]+S[5],9),S[1]^=R$2(S[13]+S[9],13),S[5]^=R$2(S[1]+S[13],18),S[14]^=R$2(S[10]+S[6],7),S[2]^=R$2(S[14]+S[10],9),S[6]^=R$2(S[2]+S[14],13),S[10]^=R$2(S[6]+S[2],18),S[3]^=R$2(S[15]+S[11],7),S[7]^=R$2(S[3]+S[15],9),S[11]^=R$2(S[7]+S[3],13),S[15]^=R$2(S[11]+S[7],18),S[1]^=R$2(S[0]+S[3],7),S[2]^=R$2(S[1]+S[0],9),S[3]^=R$2(S[2]+S[1],13),S[0]^=R$2(S[3]+S[2],18),S[6]^=R$2(S[5]+S[4],7),S[7]^=R$2(S[6]+S[5],9),S[4]^=R$2(S[7]+S[6],13),S[5]^=R$2(S[4]+S[7],18),S[11]^=R$2(S[10]+S[9],7),S[8]^=R$2(S[11]+S[10],9),S[9]^=R$2(S[8]+S[11],13),S[10]^=R$2(S[9]+S[8],18),S[12]^=R$2(S[15]+S[14],7),S[13]^=R$2(S[12]+S[15],9),S[14]^=R$2(S[13]+S[12],13),S[15]^=R$2(S[14]+S[13],18);for(let C=0;C<16;C++)n[C]=n[C]+S[C]>>>0}function blockMix(n,S){let C=2*S*16,N=new Uint32Array(16);for(let S=0;S<16;S++)N[S]=n[C-16+S];let F=new Uint32Array(C);for(let C=0;C<2*S;C++){for(let S=0;S<16;S++)N[S]^=n[C*16+S];salsa20_8(N);for(let n=0;n<16;n++)F[C*16+n]=N[n]}for(let C=0;C<S;C++)for(let S=0;S<16;S++)n[C*16+S]=F[2*C*16+S];for(let C=0;C<S;C++)for(let N=0;N<16;N++)n[(S+C)*16+N]=F[(2*C+1)*16+N]}function roMix(n,S,C){let N=2*C*16,F=Array.from({length:S});for(let N=0;N<S;N++)F[N]=new Uint32Array(n),blockMix(n,C);for(let I=0;I<S;I++){let I=n[N-16]&S-1;for(let S=0;S<N;S++)n[S]^=F[I][S];blockMix(n,C)}}function bytesToWords(n){let S=new Uint32Array(n.length/4);for(let C=0;C<S.length;C++)S[C]=n[C*4]|n[C*4+1]<<8|n[C*4+2]<<16|n[C*4+3]<<24;return S}function wordsToBytes(n){let S=new Uint8Array(n.length*4);for(let C=0;C<n.length;C++)S[C*4]=n[C]&255,S[C*4+1]=n[C]>>8&255,S[C*4+2]=n[C]>>16&255,S[C*4+3]=n[C]>>24&255;return S}function scryptCore(n,S,C,N,F,I){let H=128*N,W=pbkdf2Sync(n,S,1,F*H,`sha256`);for(let n=0;n<F;n++){let S=new Uint8Array(W.buffer,W.byteOffset+n*H,H),F=bytesToWords(S);roMix(F,C,N);let I=wordsToBytes(F);S.set(I)}return pbkdf2Sync(n,W,1,I,`sha256`)}function scryptSync(n,S,C,N){let F=$e.from(n),I=$e.from(S),H=N?.N??16384,W=N?.r??8,q=N?.p??1;if(H<=0||H&H-1)throw Error(`N must be a positive power of 2`);return scryptCore(F,I,H,W,q,C)}function scrypt(n,S,C,N,F){let I={},H;typeof N==`function`?H=N:(I=N,H=F);try{let N=scryptSync(n,S,C,I);setTimeout(()=>H(null,N),0)}catch(n){setTimeout(()=>H(n instanceof Error?n:Error(String(n)),$e.alloc(0)),0)}}var _o=__esmMin(()=>{go(),lt(),__name$1(R$2,`R`)});function pemToDer(n){let S=n.trim().split(/\r?\n/),C=S.findIndex(n=>n.startsWith(`-----BEGIN `));if(C===-1)throw Error(`Invalid PEM: no BEGIN line found`);let N=S[C].match(/^-----BEGIN (.+)-----$/);if(!N)throw Error(`Invalid PEM header format`);let F=N[1],I=S.findIndex((n,S)=>S>C&&n.startsWith(`-----END `));if(I===-1)throw Error(`Invalid PEM: no END line found`);let H=S.slice(C+1,I).join(``),W=$e.from(H,`base64`);return{type:F,der:new Uint8Array(W.buffer,W.byteOffset,W.byteLength)}}function parseTlv(n,S){if(S>=n.length)throw Error(`ASN.1 parse error: unexpected end of data`);let C=n[S++],N,F=n[S++];if(F<128)N=F;else{let C=F&127;if(C===0)throw Error(`ASN.1 parse error: indefinite length not supported`);N=0;for(let F=0;F<C;F++)N=N<<8|n[S++]}let I=n.slice(S,S+N),H=S+N,W={tag:C,data:I};return C===48&&(W.children=parseSequenceChildren(I)),{value:W,next:H}}function parseSequenceChildren(n){let S=[],C=0;for(;C<n.length;){let{value:N,next:F}=parseTlv(n,C);S.push(N),C=F}return S}function parseDer(n){let{value:S}=parseTlv(n,0);return S}function integerToBigInt(n){let S=0;for(;S<n.length-1&&n[S]===0;)S++;let C=0n;for(let N=S;N<n.length;N++)C=C<<8n|BigInt(n[N]);return C}function oidsEqual(n,S){if(n.length!==S.length)return!1;for(let C=0;C<n.length;C++)if(n[C]!==S[C])return!1;return!0}function parseRsaPublicKeyPkcs1(n){let S=n.children;if(!S||S.length<2)throw Error(`Invalid PKCS#1 RSAPublicKey structure`);return{n:integerToBigInt(S[0].data),e:integerToBigInt(S[1].data)}}function parseRsaPrivateKeyPkcs1(n){let S=n.children;if(!S||S.length<6)throw Error(`Invalid PKCS#1 RSAPrivateKey structure`);return{n:integerToBigInt(S[1].data),e:integerToBigInt(S[2].data),d:integerToBigInt(S[3].data),p:integerToBigInt(S[4].data),q:integerToBigInt(S[5].data)}}function parseSubjectPublicKeyInfo(n){let S=n.children;if(!S||S.length<2)throw Error(`Invalid SubjectPublicKeyInfo structure`);let C=S[0];if(!C.children||C.children.length<1)throw Error(`Invalid AlgorithmIdentifier`);let N=C.children[0];if(N.tag!==6||!oidsEqual(N.data,vo))throw Error(`Unsupported algorithm: only RSA is supported`);let F=S[1];if(F.tag!==3)throw Error(`Expected BIT STRING for public key data`);return parseRsaPublicKeyPkcs1(parseDer(F.data.slice(1)))}function parsePrivateKeyInfo(n){let S=n.children;if(!S||S.length<3)throw Error(`Invalid PrivateKeyInfo structure`);let C=S[1];if(!C.children||C.children.length<1)throw Error(`Invalid AlgorithmIdentifier`);let N=C.children[0];if(N.tag!==6||!oidsEqual(N.data,vo))throw Error(`Unsupported algorithm: only RSA is supported`);let F=S[2];if(F.tag!==4)throw Error(`Expected OCTET STRING for private key data`);return parseRsaPrivateKeyPkcs1(parseDer(F.data))}function encodeLength(n){if(n<128)return new Uint8Array([n]);let S=[],C=n;for(;C>0;)S.unshift(C&255),C>>=8;return new Uint8Array([128|S.length,...S])}function encodeTlv(n,S){let C=encodeLength(S.length),N=new Uint8Array(1+C.length+S.length);return N[0]=n,N.set(C,1),N.set(S,1+C.length),N}function bigintToAsn1Integer(n){if(n===0n)return encodeTlv(2,new Uint8Array([0]));let S=n.toString(16),C=S.length%2?`0`+S:S,N=[];for(let n=0;n<C.length;n+=2)N.push(parseInt(C.substring(n,n+2),16));return N[0]&128&&N.unshift(0),encodeTlv(2,new Uint8Array(N))}function encodeSequence(n){let S=0;for(let C of n)S+=C.length;let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return encodeTlv(48,C)}function encodeBitString(n){let S=new Uint8Array(1+n.length);return S[0]=0,S.set(n,1),encodeTlv(3,S)}function encodeOctetString(n){return encodeTlv(4,n)}function encodeOid(n){return encodeTlv(6,n)}function encodeNull(){return new Uint8Array([5,0])}function encodeRsaPublicKeyPkcs1(n){return encodeSequence([bigintToAsn1Integer(n.n),bigintToAsn1Integer(n.e)])}function encodeSubjectPublicKeyInfo(n){return encodeSequence([encodeSequence([encodeOid(vo),encodeNull()]),encodeBitString(encodeRsaPublicKeyPkcs1(n))])}function encodeRsaPrivateKeyPkcs1(n){let S=n.d%(n.p-1n),C=n.d%(n.q-1n),N=modInverse$1(n.q,n.p);return encodeSequence([bigintToAsn1Integer(0n),bigintToAsn1Integer(n.n),bigintToAsn1Integer(n.e),bigintToAsn1Integer(n.d),bigintToAsn1Integer(n.p),bigintToAsn1Integer(n.q),bigintToAsn1Integer(S),bigintToAsn1Integer(C),bigintToAsn1Integer(N)])}function encodePrivateKeyInfo(n){let S=encodeSequence([encodeOid(vo),encodeNull()]),C=encodeOctetString(encodeRsaPrivateKeyPkcs1(n));return encodeSequence([bigintToAsn1Integer(0n),S,C])}function derToPem(n,S){let C=$e.from(n).toString(`base64`),N=[`-----BEGIN ${S}-----`];for(let n=0;n<C.length;n+=64)N.push(C.substring(n,n+64));return N.push(`-----END ${S}-----`),N.join(`
|
|
@@ -39,7 +39,7 @@ function tokenizeArgString(n){if(Array.isArray(n))return n.map(n=>typeof n==`str
|
|
|
39
39
|
* SPDX-License-Identifier: ISC
|
|
40
40
|
*/
|
|
41
41
|
function combineAliases(n){let S=[],C=Object.create(null),N=!0;for(Object.keys(n).forEach(function(C){S.push([].concat(n[C],C))});N;){N=!1;for(let n=0;n<S.length;n++)for(let C=n+1;C<S.length;C++)if(S[n].filter(function(n){return S[C].indexOf(n)!==-1}).length){S[n]=S[n].concat(S[C]),S.splice(C,1),N=!0;break}}return S.forEach(function(n){n=n.filter(function(n,S,C){return C.indexOf(n)===S});let S=n.pop();S!==void 0&&typeof S==`string`&&(C[S]=n)}),C}function increment$1(n){return n===void 0?1:n+1}function sanitizeKey(n){return n===`__proto__`?`___proto___`:n}function stripQuotes$1(n){return typeof n==`string`&&(n[0]===`'`||n[0]===`"`)&&n[n.length-1]===n[0]?n.substring(1,n.length-1):n}var Fc,YargsParser,Ic=__esmMin(()=>{Mc(),Pc(),jc(),YargsParser=class{constructor(n){Fc=n}parse(n,S){let C=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},S),N=tokenizeArgString(n),F=typeof n==`string`,I=combineAliases(Object.assign(Object.create(null),C.alias)),H=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":`no-`,"parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},C.configuration),W=Object.assign(Object.create(null),C.default),q=C.configObjects||[],Y=C.envPrefix,X=H[`populate--`],Z=X?`--`:`_`,te=Object.create(null),ne=Object.create(null),re=C.__||Fc.format,ie={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},ae=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,oe=RegExp(`^--`+H[`negation-prefix`]+`(.+)`);[].concat(C.array||[]).filter(Boolean).forEach(function(n){let S=typeof n==`object`?n.key:n,C=Object.keys(n).map(function(n){return{boolean:`bools`,string:`strings`,number:`numbers`}[n]}).filter(Boolean).pop();C&&(ie[C][S]=!0),ie.arrays[S]=!0,ie.keys.push(S)}),[].concat(C.boolean||[]).filter(Boolean).forEach(function(n){ie.bools[n]=!0,ie.keys.push(n)}),[].concat(C.string||[]).filter(Boolean).forEach(function(n){ie.strings[n]=!0,ie.keys.push(n)}),[].concat(C.number||[]).filter(Boolean).forEach(function(n){ie.numbers[n]=!0,ie.keys.push(n)}),[].concat(C.count||[]).filter(Boolean).forEach(function(n){ie.counts[n]=!0,ie.keys.push(n)}),[].concat(C.normalize||[]).filter(Boolean).forEach(function(n){ie.normalize[n]=!0,ie.keys.push(n)}),typeof C.narg==`object`&&Object.entries(C.narg).forEach(([n,S])=>{typeof S==`number`&&(ie.nargs[n]=S,ie.keys.push(n))}),typeof C.coerce==`object`&&Object.entries(C.coerce).forEach(([n,S])=>{typeof S==`function`&&(ie.coercions[n]=S,ie.keys.push(n))}),C.config!==void 0&&(Array.isArray(C.config)||typeof C.config==`string`?[].concat(C.config).filter(Boolean).forEach(function(n){ie.configs[n]=!0}):typeof C.config==`object`&&Object.entries(C.config).forEach(([n,S])=>{(typeof S==`boolean`||typeof S==`function`)&&(ie.configs[n]=S)})),extendAliases(C.key,I,C.default,ie.arrays),Object.keys(W).forEach(function(n){(ie.aliases[n]||[]).forEach(function(S){W[S]=W[n]})});let se=null;checkConfiguration();let Q=[],ce=Object.assign(Object.create(null),{_:[]}),le={};for(let n=0;n<N.length;n++){let S=N[n],C=S.replace(/^-{3,}/,`---`),F,I,W,q,Y,X;if(S!==`--`&&/^-/.test(S)&&isUnknownOptionAsArg(S))pushPositional(S);else if(C.match(/^---+(=|$)/)){pushPositional(S);continue}else if(S.match(/^--.+=/)||!H[`short-option-groups`]&&S.match(/^-.+=/))q=S.match(/^--?([^=]+)=([\s\S]*)$/),q!==null&&Array.isArray(q)&&q.length>=3&&(checkAllAliases(q[1],ie.arrays)?n=eatArray(n,q[1],N,q[2]):checkAllAliases(q[1],ie.nargs)===!1?setArg(q[1],q[2],!0):n=eatNargs(n,q[1],N,q[2]));else if(S.match(oe)&&H[`boolean-negation`])q=S.match(oe),q!==null&&Array.isArray(q)&&q.length>=2&&(I=q[1],setArg(I,checkAllAliases(I,ie.arrays)?[!1]:!1));else if(S.match(/^--.+/)||!H[`short-option-groups`]&&S.match(/^-[^-]+/))q=S.match(/^--?(.+)/),q!==null&&Array.isArray(q)&&q.length>=2&&(I=q[1],checkAllAliases(I,ie.arrays)?n=eatArray(n,I,N):checkAllAliases(I,ie.nargs)===!1?(Y=N[n+1],Y!==void 0&&(!Y.match(/^-/)||Y.match(ae))&&!checkAllAliases(I,ie.bools)&&!checkAllAliases(I,ie.counts)||/^(true|false)$/.test(Y)?(setArg(I,Y),n++):setArg(I,defaultValue(I))):n=eatNargs(n,I,N));else if(S.match(/^-.\..+=/))q=S.match(/^-([^=]+)=([\s\S]*)$/),q!==null&&Array.isArray(q)&&q.length>=3&&setArg(q[1],q[2]);else if(S.match(/^-.\..+/)&&!S.match(ae))Y=N[n+1],q=S.match(/^-(.\..+)/),q!==null&&Array.isArray(q)&&q.length>=2&&(I=q[1],Y!==void 0&&!Y.match(/^-/)&&!checkAllAliases(I,ie.bools)&&!checkAllAliases(I,ie.counts)?(setArg(I,Y),n++):setArg(I,defaultValue(I)));else if(S.match(/^-[^-]+/)&&!S.match(ae)){W=S.slice(1,-1).split(``),F=!1;for(let C=0;C<W.length;C++){if(Y=S.slice(C+2),W[C+1]&&W[C+1]===`=`){X=S.slice(C+3),I=W[C],checkAllAliases(I,ie.arrays)?n=eatArray(n,I,N,X):checkAllAliases(I,ie.nargs)===!1?setArg(I,X):n=eatNargs(n,I,N,X),F=!0;break}if(Y===`-`){setArg(W[C],Y);continue}if(/[A-Za-z]/.test(W[C])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(Y)&&checkAllAliases(Y,ie.bools)===!1){setArg(W[C],Y),F=!0;break}if(W[C+1]&&W[C+1].match(/\W/)){setArg(W[C],Y),F=!0;break}else setArg(W[C],defaultValue(W[C]))}I=S.slice(-1)[0],!F&&I!==`-`&&(checkAllAliases(I,ie.arrays)?n=eatArray(n,I,N):checkAllAliases(I,ie.nargs)===!1?(Y=N[n+1],Y!==void 0&&(!/^(-|--)[^-]/.test(Y)||Y.match(ae))&&!checkAllAliases(I,ie.bools)&&!checkAllAliases(I,ie.counts)||/^(true|false)$/.test(Y)?(setArg(I,Y),n++):setArg(I,defaultValue(I))):n=eatNargs(n,I,N))}else if(S.match(/^-[0-9]$/)&&S.match(ae)&&checkAllAliases(S.slice(1),ie.bools))I=S.slice(1),setArg(I,defaultValue(I));else if(S===`--`){Q=N.slice(n+1);break}else if(H[`halt-at-non-option`]){Q=N.slice(n);break}else pushPositional(S)}applyEnvVars(ce,!0),applyEnvVars(ce,!1),setConfig(ce),setConfigObjects(),applyDefaultsAndAliases(ce,ie.aliases,W,!0),applyCoercions(ce),H[`set-placeholder-key`]&&setPlaceholderKeys(ce),Object.keys(ie.counts).forEach(function(n){hasKey(ce,n.split(`.`))||setArg(n,0)}),X&&Q.length&&(ce[Z]=[]),Q.forEach(function(n){ce[Z].push(n)}),H[`camel-case-expansion`]&&H[`strip-dashed`]&&Object.keys(ce).filter(n=>n!==`--`&&n.includes(`-`)).forEach(n=>{delete ce[n]}),H[`strip-aliased`]&&[].concat(...Object.keys(I).map(n=>I[n])).forEach(n=>{H[`camel-case-expansion`]&&n.includes(`-`)&&delete ce[n.split(`.`).map(n=>camelCase(n)).join(`.`)],delete ce[n]});function pushPositional(n){let S=maybeCoerceNumber(`_`,n);(typeof S==`string`||typeof S==`number`)&&ce._.push(S)}function eatNargs(n,S,C,N){let F,I=checkAllAliases(S,ie.nargs);if(I=typeof I!=`number`||isNaN(I)?1:I,I===0)return isUndefined(N)||(se=Error(re(`Argument unexpected for: %s`,S))),setArg(S,defaultValue(S)),n;let W=+!isUndefined(N);if(H[`nargs-eats-options`])C.length-(n+1)+W<I&&(se=Error(re(`Not enough arguments following: %s`,S))),W=I;else{for(F=n+1;F<C.length&&(!C[F].match(/^-[^0-9]/)||C[F].match(ae)||isUnknownOptionAsArg(C[F]));F++)W++;W<I&&(se=Error(re(`Not enough arguments following: %s`,S)))}let q=Math.min(W,I);for(!isUndefined(N)&&q>0&&(setArg(S,N),q--),F=n+1;F<q+n+1;F++)setArg(S,C[F]);return n+q}function eatArray(n,S,C,N){let I=[],q=N||C[n+1],Y=checkAllAliases(S,ie.nargs);if(checkAllAliases(S,ie.bools)&&!/^(true|false)$/.test(q))I.push(!0);else if(isUndefined(q)||isUndefined(N)&&/^-/.test(q)&&!ae.test(q)&&!isUnknownOptionAsArg(q)){if(W[S]!==void 0){let n=W[S];I=Array.isArray(n)?n:[n]}}else{isUndefined(N)||I.push(processValue(S,N,!0));for(let N=n+1;N<C.length&&!(!H[`greedy-arrays`]&&I.length>0||Y&&typeof Y==`number`&&I.length>=Y||(q=C[N],/^-/.test(q)&&!ae.test(q)&&!isUnknownOptionAsArg(q)));N++)n=N,I.push(processValue(S,q,F))}return typeof Y==`number`&&(Y&&I.length<Y||isNaN(Y)&&I.length===0)&&(se=Error(re(`Not enough arguments following: %s`,S))),setArg(S,I),n}function setArg(n,S,C=F){/-/.test(n)&&H[`camel-case-expansion`]&&addNewAlias(n,n.split(`.`).map(function(n){return camelCase(n)}).join(`.`));let N=processValue(n,S,C),I=n.split(`.`);setKey(ce,I,N),ie.aliases[n]&&ie.aliases[n].forEach(function(n){let S=n.split(`.`);setKey(ce,S,N)}),I.length>1&&H[`dot-notation`]&&(ie.aliases[I[0]]||[]).forEach(function(S){let C=S.split(`.`),F=[].concat(I);F.shift(),C=C.concat(F),(ie.aliases[n]||[]).includes(C.join(`.`))||setKey(ce,C,N)}),checkAllAliases(n,ie.normalize)&&!checkAllAliases(n,ie.arrays)&&[n].concat(ie.aliases[n]||[]).forEach(function(n){Object.defineProperty(le,n,{enumerable:!0,get(){return S},set(n){S=typeof n==`string`?Fc.normalize(n):n}})})}function addNewAlias(n,S){ie.aliases[n]&&ie.aliases[n].length||(ie.aliases[n]=[S],te[S]=!0),ie.aliases[S]&&ie.aliases[S].length||addNewAlias(S,n)}function processValue(n,S,C){C&&(S=stripQuotes$1(S)),(checkAllAliases(n,ie.bools)||checkAllAliases(n,ie.counts))&&typeof S==`string`&&(S=S===`true`);let N=Array.isArray(S)?S.map(function(S){return maybeCoerceNumber(n,S)}):maybeCoerceNumber(n,S);return checkAllAliases(n,ie.counts)&&(isUndefined(N)||typeof N==`boolean`)&&(N=increment$1()),checkAllAliases(n,ie.normalize)&&checkAllAliases(n,ie.arrays)&&(N=Array.isArray(S)?S.map(n=>Fc.normalize(n)):Fc.normalize(S)),N}function maybeCoerceNumber(n,S){return!H[`parse-positional-numbers`]&&n===`_`||!checkAllAliases(n,ie.strings)&&!checkAllAliases(n,ie.bools)&&!Array.isArray(S)&&(looksLikeNumber(S)&&H[`parse-numbers`]&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))||!isUndefined(S)&&checkAllAliases(n,ie.numbers))&&(S=Number(S)),S}function setConfig(n){let S=Object.create(null);applyDefaultsAndAliases(S,ie.aliases,W),Object.keys(ie.configs).forEach(function(C){let N=n[C]||S[C];if(N)try{let n=null,S=Fc.resolve(Fc.cwd(),N),F=ie.configs[C];if(typeof F==`function`){try{n=F(S)}catch(S){n=S}if(n instanceof Error){se=n;return}}else n=Fc.require(S);setConfigObject(n)}catch(S){S.name===`PermissionDenied`?se=S:n[C]&&(se=Error(re(`Invalid JSON config file: %s`,N)))}})}function setConfigObject(n,S){Object.keys(n).forEach(function(C){let N=n[C],F=S?S+`.`+C:C;typeof N==`object`&&N&&!Array.isArray(N)&&H[`dot-notation`]?setConfigObject(N,F):(!hasKey(ce,F.split(`.`))||checkAllAliases(F,ie.arrays)&&H[`combine-arrays`])&&setArg(F,N)})}function setConfigObjects(){q!==void 0&&q.forEach(function(n){setConfigObject(n)})}function applyEnvVars(n,S){if(Y===void 0)return;let C=typeof Y==`string`?Y:``,N=Fc.env();Object.keys(N).forEach(function(F){if(C===``||F.lastIndexOf(C,0)===0){let I=F.split(`__`).map(function(n,S){return S===0&&(n=n.substring(C.length)),camelCase(n)});(S&&ie.configs[I.join(`.`)]||!S)&&!hasKey(n,I)&&setArg(I.join(`.`),N[F])}})}function applyCoercions(n){let S,C=new Set;Object.keys(n).forEach(function(N){if(!C.has(N)&&(S=checkAllAliases(N,ie.coercions),typeof S==`function`))try{let F=maybeCoerceNumber(N,S(n[N]));[].concat(ie.aliases[N]||[],N).forEach(S=>{C.add(S),n[S]=F})}catch(n){se=n}})}function setPlaceholderKeys(n){return ie.keys.forEach(S=>{~S.indexOf(`.`)||n[S]===void 0&&(n[S]=void 0)}),n}function applyDefaultsAndAliases(n,S,C,N=!1){Object.keys(C).forEach(function(F){hasKey(n,F.split(`.`))||(setKey(n,F.split(`.`),C[F]),N&&(ne[F]=!0),(S[F]||[]).forEach(function(S){hasKey(n,S.split(`.`))||setKey(n,S.split(`.`),C[F])}))})}function hasKey(n,S){let C=n;H[`dot-notation`]||(S=[S.join(`.`)]),S.slice(0,-1).forEach(function(n){C=C[n]||{}});let N=S[S.length-1];return typeof C==`object`?N in C:!1}function setKey(n,S,C){let N=n;H[`dot-notation`]||(S=[S.join(`.`)]),S.slice(0,-1).forEach(function(n){n=sanitizeKey(n),typeof N==`object`&&N[n]===void 0&&(N[n]={}),typeof N[n]!=`object`||Array.isArray(N[n])?(Array.isArray(N[n])?N[n].push({}):N[n]=[N[n],{}],N=N[n][N[n].length-1]):N=N[n]});let F=sanitizeKey(S[S.length-1]),I=checkAllAliases(S.join(`.`),ie.arrays),W=Array.isArray(C),q=H[`duplicate-arguments-array`];!q&&checkAllAliases(F,ie.nargs)&&(q=!0,(!isUndefined(N[F])&&ie.nargs[F]===1||Array.isArray(N[F])&&N[F].length===ie.nargs[F])&&(N[F]=void 0)),C===increment$1()?N[F]=increment$1(N[F]):Array.isArray(N[F])?q&&I&&W?N[F]=H[`flatten-duplicate-arrays`]?N[F].concat(C):(Array.isArray(N[F][0])?N[F]:[N[F]]).concat([C]):!q&&!!I==!!W?N[F]=C:N[F]=N[F].concat([C]):N[F]===void 0&&I?N[F]=W?C:[C]:q&&!(N[F]===void 0||checkAllAliases(F,ie.counts)||checkAllAliases(F,ie.bools))?N[F]=[N[F],C]:N[F]=C}function extendAliases(...n){n.forEach(function(n){Object.keys(n||{}).forEach(function(n){ie.aliases[n]||(ie.aliases[n]=[].concat(I[n]||[]),ie.aliases[n].concat(n).forEach(function(S){if(/-/.test(S)&&H[`camel-case-expansion`]){let C=camelCase(S);C!==n&&ie.aliases[n].indexOf(C)===-1&&(ie.aliases[n].push(C),te[C]=!0)}}),ie.aliases[n].concat(n).forEach(function(S){if(S.length>1&&/[A-Z]/.test(S)&&H[`camel-case-expansion`]){let C=decamelize(S,`-`);C!==n&&ie.aliases[n].indexOf(C)===-1&&(ie.aliases[n].push(C),te[C]=!0)}}),ie.aliases[n].forEach(function(S){ie.aliases[S]=[n].concat(ie.aliases[n].filter(function(n){return S!==n}))}))})})}function checkAllAliases(n,S){let C=[].concat(ie.aliases[n]||[],n),N=Object.keys(S),F=C.find(n=>N.includes(n));return F?S[F]:!1}function hasAnyFlag(n){let S=Object.keys(ie);return[].concat(S.map(n=>ie[n])).some(function(S){return Array.isArray(S)?S.includes(n):S[n]})}function hasFlagsMatching(n,...S){return[].concat(...S).some(function(S){let C=n.match(S);return C&&hasAnyFlag(C[1])})}function hasAllShortFlags(n){if(n.match(ae)||!n.match(/^-[^-]+/))return!1;let S=!0,C,N=n.slice(1).split(``);for(let F=0;F<N.length;F++){if(C=n.slice(F+2),!hasAnyFlag(N[F])){S=!1;break}if(N[F+1]&&N[F+1]===`=`||C===`-`||/[A-Za-z]/.test(N[F])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(C)||N[F+1]&&N[F+1].match(/\W/))break}return S}function isUnknownOptionAsArg(n){return H[`unknown-options-as-args`]&&isUnknownOption(n)}function isUnknownOption(n){return n=n.replace(/^-{3,}/,`--`),n.match(ae)||hasAllShortFlags(n)?!1:!hasFlagsMatching(n,/^-+([^=]+?)=[\s\S]*$/,oe,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function defaultValue(n){return!checkAllAliases(n,ie.bools)&&!checkAllAliases(n,ie.counts)&&`${n}`in W?W[n]:defaultForType(guessType(n))}function defaultForType(n){return{[Nc.BOOLEAN]:!0,[Nc.STRING]:``,[Nc.NUMBER]:void 0,[Nc.ARRAY]:[]}[n]}function guessType(n){let S=Nc.BOOLEAN;return checkAllAliases(n,ie.strings)?S=Nc.STRING:checkAllAliases(n,ie.numbers)?S=Nc.NUMBER:checkAllAliases(n,ie.bools)?S=Nc.BOOLEAN:checkAllAliases(n,ie.arrays)&&(S=Nc.ARRAY),S}function isUndefined(n){return n===void 0}function checkConfiguration(){Object.keys(ie.counts).find(n=>checkAllAliases(n,ie.arrays)?(se=Error(re(`Invalid configuration: %s, opts.count excludes opts.array.`,n)),!0):checkAllAliases(n,ie.nargs)?(se=Error(re(`Invalid configuration: %s, opts.count excludes opts.narg.`,n)),!0):!1)}return{aliases:Object.assign({},ie.aliases),argv:Object.assign(le,ce),configuration:H,defaulted:Object.assign({},ne),error:se,newAliases:Object.assign({},te)}}},__name$1(increment$1,`increment`),__name$1(stripQuotes$1,`stripQuotes`)}),Lc,Rc,zc=__esmMin(()=>{Lc=Object.defineProperty,Rc=__name$1((n,S)=>{let C={};for(var N in n)Lc(C,N,{get:n[N],enumerable:!0});return S||Lc(C,Symbol.toStringTag,{value:`Module`}),C},`__exportAll`)});function normalizePath(n){return n instanceof URL||n instanceof mn?fileURLToPath(n):typeof n==`string`?n:n.toString()}function randomName(){return[...[,,,,,,]].map(()=>`0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`[Math.floor(Math.random()*62)]).join(``)}var Bc=__esmMin(()=>{gn()});function createNodeError(n,S,C,N){return typeof n?.code==`string`?n:createNodeError$1(n,S,{path:C.toString(),dest:N?.toString()})}function requireCallback(n,S=`cb`){if(typeof n==`function`)return n;let C=TypeError(`The "${S}" argument must be of type function. Received ${describeReceived(n)}`);throw C.code=`ERR_INVALID_ARG_TYPE`,C}function describeReceived(n){if(n==null)return String(n);if(typeof n==`object`){let S=n.constructor?.name;return`an instance of ${S&&S.length>0?S:`Object`}`}if(typeof n==`string`){let S=n.length>25?`${n.slice(0,25)}...`:n;return S.includes(`'`)?`type string ("${S}")`:`type string ('${S}')`}return typeof n==`bigint`?`type bigint (${n}n)`:typeof n==`symbol`?`type symbol (${n.toString()})`:`type ${typeof n} (${String(n)})`}function invalidState(n){let S=Error(`Invalid state: ${n}`);return S.code=`ERR_INVALID_STATE`,S}var Vc=__esmMin(()=>{Be()});function gioEventToNodeType(n){switch(n){case Lr.FileMonitorEvent.CHANGED:case Lr.FileMonitorEvent.CHANGES_DONE_HINT:return`change`;case Lr.FileMonitorEvent.DELETED:case Lr.FileMonitorEvent.CREATED:case Lr.FileMonitorEvent.RENAMED:case Lr.FileMonitorEvent.MOVED_IN:case Lr.FileMonitorEvent.MOVED_OUT:return`rename`;default:return null}}var WatchTree,Hc=__esmMin(()=>{Vc(),Rr(),Hs(),Be(),WatchTree=class{_monitors=new Map;_fileMonitors=new Map;_closed=!1;_root;_recursive;_fanOut;_budget;_budgetReported=!1;_onEvent;_onError;constructor(n,S,C,N,F){this._recursive=S,this._onEvent=C,this._onError=N,this._fanOut=F?.fanOut??isDarwin(),this._budget=F?.budget??(this._fanOut?4096:1/0);let I=Lr.File.new_for_path(n);this._root=I.get_path()??n,this._open(this._root,I),I.query_file_type(Lr.FileQueryInfoFlags.NONE,null)===Lr.FileType.DIRECTORY&&(S||this._fanOut)&&this._descend(this._root,!1)}get monitorCount(){return this._monitors.size+this._fileMonitors.size}close(){this._closed=!0;for(let n of this._monitors.values())n.cancel();this._monitors.clear();for(let n of this._fileMonitors.values())n.cancel();this._fileMonitors.clear()}_open(n,S){let C=S.monitor(Lr.FileMonitorFlags.NONE,null);C.connect(`changed`,(n,S,C,N)=>{this._dispatch(S,N)}),this._monitors.set(n,C)}_watchFile(n){if(this._closed||this._fileMonitors.has(n)||!this._admit(n))return;let S;try{S=Lr.File.new_for_path(n).monitor(Lr.FileMonitorFlags.NONE,null)}catch(n){isNotFoundError(n)||this._onError(n);return}S.connect(`changed`,(n,S,C,N)=>{if(gioEventToNodeType(N)!==`change`)return;let F=S.get_path();F!==null&&this._emit(`change`,F)}),this._fileMonitors.set(n,S)}_admit(n){if(this.monitorCount<this._budget)return!0;if(this._budgetReported)return!1;this._budgetReported=!0;let S=Error(`fs.watch: this watch holds its whole budget of ${this._budget} monitors and stopped at ${n}. Anything under ${this._root} that is not already attached is NOT being watched, and no further event will arrive for it. The budget is finite because this host needs a monitor per FILE rather than per directory, and unbounded growth of a shared process resource surfaces as an unrelated allocation failing elsewhere, in a trace that never mentions fs.watch. Watch a narrower directory.`);return S.code=`ERR_FS_WATCH_MONITOR_BUDGET`,S.path=n,this._onError(S),!1}_dispatch(n,S){let C=n.get_path();if(C===null)return;let N=gioEventToNodeType(S);if(N!==null&&this._emit(N,C),!(!this._recursive&&!this._fanOut))switch(S){case Lr.FileMonitorEvent.CREATED:case Lr.FileMonitorEvent.MOVED_IN:{let S=n.query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null);S===Lr.FileType.DIRECTORY?this._recursive&&this._addSubtree(C,!0):this._fanOut&&S===Lr.FileType.REGULAR&&this._watchFile(C);break}case Lr.FileMonitorEvent.DELETED:case Lr.FileMonitorEvent.MOVED_OUT:this._dropSubtree(C);break}}_emit(n,S){let C=Ms(this._root,S);this._onEvent(n,C===``?Fs(S):C)}_addSubtree(n,S){if(!(this._closed||this._monitors.has(n))&&this._admit(n)){try{this._open(n,Lr.File.new_for_path(n))}catch(n){isNotFoundError(n)||this._onError(n);return}this._descend(n,S)}}_descend(n,S){for(let C of this._children(n)){if(this._closed)return;if(C.isDirectory){if(!this._recursive)continue;S&&this._emit(`rename`,C.path),this._addSubtree(C.path,S)}else S&&this._emit(`rename`,C.path),this._fanOut&&C.isFile&&this._watchFile(C.path)}}_dropSubtree(n){this._fileMonitors.get(n)?.cancel(),this._fileMonitors.delete(n);let S=n+zs;for(let[n,C]of this._fileMonitors)n.startsWith(S)&&(C.cancel(),this._fileMonitors.delete(n));for(let[C,N]of this._monitors)C!==n&&!C.startsWith(S)||(N.cancel(),this._monitors.delete(C))}_children(n){let S;try{S=Lr.File.new_for_path(n).enumerate_children(`standard::name,standard::type`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(n){return isNotFoundError(n)||this._onError(n),[]}let C=[];try{let N=S.next_file(null);for(;N!==null;){let F=N.get_file_type();C.push({path:js(n,N.get_name()),isDirectory:F===Lr.FileType.DIRECTORY,isFile:F===Lr.FileType.REGULAR}),N=S.next_file(null)}}catch(n){isNotFoundError(n)||this._onError(n)}finally{try{S.close(null)}catch{}}return C}}});async function*watchAsync(n,S){let C=S?.signal;if(C?.aborted)return;let N=normalizePath(n),F=[],I=[],H=!1,W=null;function enqueue(n){H||(I.length>0?I.shift().resolve({value:n,done:!1}):F.push(n))}function terminate(){if(!H)for(H=!0;I.length>0;)I.shift().resolve({value:void 0,done:!0})}let q;try{q=new WatchTree(N,S?.recursive===!0,(n,S)=>{enqueue({eventType:n,filename:S})},n=>{W=n,terminate()})}catch{return}let abortHandler=()=>terminate();C?.addEventListener(`abort`,abortHandler);try{for(;!H;){if(F.length>0){yield F.shift();continue}let n=await new Promise(n=>{I.push({resolve:n})});if(n.done)break;yield n.value}if(W!==null)throw W}finally{C?.removeEventListener(`abort`,abortHandler),q.close()}}var Uc,FSWatcher,Wc=__esmMin(()=>{Bc(),Hc(),pt(),Kt(),Uc=new WeakMap,FSWatcher=class extends Ft{constructor(n,S,C){super(),(!S||typeof S!=`object`)&&(S={persistent:!0});let N=S.persistent!==!1,F=new WatchTree(normalizePath(n),S.recursive===!0,(n,S)=>{this.emit(`change`,n,S)},n=>{this.emit(`error`,n)}),I=null;N&&(I=ft.timeout_add(ft.PRIORITY_LOW,2147483647,()=>ft.SOURCE_CONTINUE)),Uc.set(this,{persistent:N,closed:!1,sourceId:I,tree:F}),C&&this.on(`change`,C)}close(){let n=Uc.get(this);n.closed||(n.closed=!0,n.tree.close(),n.sourceId!==null&&(ft.source_remove(n.sourceId),n.sourceId=null))}ref(){let n=Uc.get(this);return!n.persistent&&!n.closed&&(n.persistent=!0,n.sourceId=ft.timeout_add(ft.PRIORITY_LOW,2147483647,()=>ft.SOURCE_CONTINUE)),this}unref(){let n=Uc.get(this);return n.persistent&&(n.persistent=!1,n.sourceId!==null&&(ft.source_remove(n.sourceId),n.sourceId=null)),this}}}),Gc=__exportAll$4({lchmod:()=>void 0,lchmodAsync:()=>lchmodAsync,lchmodSync:()=>void 0,lchown:()=>lchown,lchownAsync:()=>lchownAsync,lchownSync:()=>lchownSync,lutimes:()=>lutimes,lutimesAsync:()=>lutimesAsync,lutimesSync:()=>lutimesSync,utimes:()=>utimes,utimesAsync:()=>utimesAsync,utimesSync:()=>utimesSync});function toGLibDateTime(n){let S=n instanceof Date?n.getTime():typeof n==`bigint`?Number(n):typeof n==`string`?Date.parse(n):n*1e3;return ft.DateTime.new_from_unix_utc(Math.floor(S/1e3))}function setTimestamps(n,S,C,N){let F=Lr.File.new_for_path(n),I=new Lr.FileInfo;I.set_modification_date_time(toGLibDateTime(C)),I.set_access_date_time(toGLibDateTime(S)),F.set_attributes_from_info(I,N,null)}function utimesSync(n,S,C){setTimestamps(normalizePath(n),S,C,Lr.FileQueryInfoFlags.NONE)}function utimes(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>utimesSync(n,S,C)).then(()=>N(null),N)}async function utimesAsync(n,S,C){utimesSync(n,S,C)}function lutimesSync(n,S,C){setTimestamps(normalizePath(n),S,C,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS)}function lutimes(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>lutimesSync(n,S,C)).then(()=>N(null),N)}async function lutimesAsync(n,S,C){lutimesSync(n,S,C)}function lchownSync(n,S,C){let N=normalizePath(n),F=Lr.File.new_for_path(N),I=new Lr.FileInfo;S!==-1&&I.set_attribute_uint32(`unix::uid`,S),C!==-1&&I.set_attribute_uint32(`unix::gid`,C),F.set_attributes_from_info(I,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}function lchown(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>lchownSync(n,S,C)).then(()=>N(null),N)}async function lchownAsync(n,S,C){lchownSync(n,S,C)}function lchmodUnsupported(){let n=Error(`The lchmod() method is not implemented`);return n.code=`ERR_METHOD_NOT_IMPLEMENTED`,n}async function lchmodAsync(n,S){throw lchmodUnsupported()}var Kc=__esmMin(()=>{Bc(),Vc(),pt(),Rr()});function isStdFd(n){return n===0||n===1||n===2}function stdinInput(){return qc||=da.InputStream.new(0,!1),qc}function stdOutput(n){return Jc[n]||(Jc[n]=da.OutputStream.new(n,!1)),Jc[n]}function readStdFdAll(n){try{let S=n===0?stdinInput():da.InputStream.new(n,!1),C=[],N=0;for(;;){let n=S.read_bytes(64*1024,null).get_data();if(!n||n.length===0)break;C.push(n),N+=n.length}return concat(C,N)}catch(S){if(n!==0)throw S;let[C,N]=Lr.File.new_for_path(`/dev/stdin`).load_contents(null);if(!C)throw S;return N}}function readStdFdSync(n,S,C,N){let F=(n===0?stdinInput():da.InputStream.new(n,!1)).read_bytes(N,null).get_data();return F&&F.length>0?(new Uint8Array(S.buffer,S.byteOffset+C).set(F),F.length):0}function writeStdFdSync(n,S){return stdOutput(n).write_bytes(ft.Bytes.new(S),null)}function concat(n,S){if(n.length===1)return n[0];let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}var qc,Jc,Yc=__esmMin(()=>{pt(),Rr(),fa(),qc=null,Jc={}});function getEncodingFromOptions(n={encoding:null,flag:`r`},S=`utf8`){return n===null?S:typeof n==`string`?n:typeof n==`object`&&typeof n.encoding==`string`?n.encoding:S}function encodeUint8Array(n,S){return n===`buffer`?$e.from(S):new TextDecoder(n).decode(S)}function decode(n,S){if(S){let C=new TextDecoder(S),N=new TextEncoder;return C.decode(N.encode(n))}else return n}var Xc=__esmMin(()=>{lt()});function createReadStream(n,S){return new ReadStream$1(n,S)}var ReadStream$1,Zc=__esmMin(()=>{Bc(),Fl(),Pl(),pt(),Rr(),lt(),gi(),ReadStream$1=class extends li{static{__name$1(this,`ReadStream`)}bytesRead=0;path;pending=!0;fd=null;_ownFd=null;_autoCloseFd=!0;_positional=!1;_gioFile;_inputStream=null;_cancellable=new Lr.Cancellable;_start;_end;_pos;_reading=!1;_readAgain=!1;_lastSize=64*1024;close(n){this._cancellable.cancel(),this._release(),this.destroy(),n&&n(null)}constructor(n,S){let C=normalizePath(n);super({highWaterMark:S?.highWaterMark??64*1024,encoding:S?.encoding,objectMode:!1}),this.path=C,this._gioFile=Lr.File.new_for_path(C),this._start=S?.start??0,this._end=S?.end??1/0,this._pos=this._start,this._positional=S?.start!==void 0,typeof S?.fd==`number`&&(this._ownFd=S.fd,this.fd=S.fd,this._autoCloseFd=S.autoClose!==!1),this.once(`end`,()=>this._release())}_construct(n){if(this._ownFd!==null){this.pending=!1,n(),this.emit(`open`,this._ownFd),this.emit(`ready`);return}this._gioFile.read_async(ft.PRIORITY_DEFAULT,this._cancellable,(S,C)=>{if(this.destroyed){n();return}try{this._inputStream=this._gioFile.read_finish(C),this.pending=!1,this.emit(`open`,0),this.emit(`ready`),this._start>0&&this._inputStream.can_seek()&&this._inputStream.seek(this._start,ft.SeekType.SET,null),n()}catch(S){this._cancellable.is_cancelled()||n(S)}})}_read(n){if(this._lastSize=n,this._reading){this._readAgain=!0;return}this._doRead(n)}_doRead(n){if(this._ownFd!==null){if(this._reading||this.destroyed)return;this._reading=!0,ft.timeout_add(ft.PRIORITY_DEFAULT,0,()=>(this._reading=!1,this.destroyed||this._readThroughFd(n),ft.SOURCE_REMOVE));return}let S=n;if(this._end!==1/0){let C=this._end-this._pos+1;if(C<=0){this.push(null);return}S=Math.min(n,C)}let C=this._inputStream;!C||this.destroyed||(this._reading=!0,C.read_bytes_async(S,ft.PRIORITY_DEFAULT,this._cancellable,(n,S)=>{this._reading=!1;try{let n=C.read_bytes_finish(S).get_data();if(!n||n.length===0){this._readAgain=!1,this.push(null);return}this.bytesRead+=n.length,this._pos+=n.length,this.push($e.from(n)),this._readAgain&&!this._reading&&(this._readAgain=!1,this._doRead(this._lastSize))}catch(n){this._readAgain=!1,this._cancellable.is_cancelled()||this.destroy(n)}}))}_readThroughFd(n){try{let S=n;if(this._end!==1/0){let C=this._end-this._pos+1;if(C<=0){this._readAgain=!1,this.push(null);return}S=Math.min(n,C)}let C=Nl.getInstance(this._ownFd,`read`),N=$e.alloc(S),F=C._readSync(N,0,S,this._positional?this._pos:null);if(F===0){this._readAgain=!1,this.push(null);return}this.bytesRead+=F,this._pos+=F,this.push(N.subarray(0,F))}catch(n){this._readAgain=!1,this.destroy(n)}}_release(){this._inputStream&&=(this._inputStream.close_async(ft.PRIORITY_DEFAULT,null,()=>{}),null),this._releaseFd()}_releaseFd(){if(this._ownFd===null||!this._autoCloseFd)return;let n=this._ownFd;this._ownFd=null,this.fd=null;try{closeSync(n)}catch{}}_destroy(n,S){this._cancellable.cancel(),this._release(),S(n)}}});function openFlagValues(){return isWin32()?el:isDarwin()?$c:Qc}function stringFlagBits(n,S){switch(n){case`r`:return S.O_RDONLY;case`rs`:case`sr`:return S.O_RDONLY|S.O_SYNC;case`r+`:return S.O_RDWR;case`rs+`:case`sr+`:return S.O_RDWR|S.O_SYNC;case`w`:return S.O_TRUNC|S.O_CREAT|S.O_WRONLY;case`wx`:case`xw`:return S.O_TRUNC|S.O_CREAT|S.O_WRONLY|S.O_EXCL;case`w+`:return S.O_TRUNC|S.O_CREAT|S.O_RDWR;case`wx+`:case`xw+`:return S.O_TRUNC|S.O_CREAT|S.O_RDWR|S.O_EXCL;case`a`:return S.O_APPEND|S.O_CREAT|S.O_WRONLY;case`ax`:case`xa`:return S.O_APPEND|S.O_CREAT|S.O_WRONLY|S.O_EXCL;case`as`:case`sa`:return S.O_APPEND|S.O_CREAT|S.O_WRONLY|S.O_SYNC;case`a+`:return S.O_APPEND|S.O_CREAT|S.O_RDWR;case`ax+`:case`xa+`:return S.O_APPEND|S.O_CREAT|S.O_RDWR|S.O_EXCL;case`as+`:case`sa+`:return S.O_APPEND|S.O_CREAT|S.O_RDWR|S.O_SYNC;default:return}}function parseOpenFlags(n){let S=openFlagValues(),C;if(n==null)C=S.O_RDONLY;else if(typeof n==`number`)C=n;else{let N=stringFlagBits(n,S);if(N===void 0){let S=TypeError(`Unknown file open flag: ${n}`);throw S.code=`ERR_INVALID_ARG_VALUE`,S}C=N}let N=C&(S.O_RDONLY|S.O_WRONLY|S.O_RDWR);return{posix:C,readable:N===S.O_RDONLY||N===S.O_RDWR,writable:N===S.O_WRONLY||N===S.O_RDWR,append:(C&S.O_APPEND)!==0,creat:(C&S.O_CREAT)!==0,excl:(C&S.O_CREAT)!==0&&(C&S.O_EXCL)!==0,trunc:(C&S.O_TRUNC)!==0,nofollow:S.O_NOFOLLOW!==0&&(C&S.O_NOFOLLOW)!==0,directory:S.O_DIRECTORY!==0&&(C&S.O_DIRECTORY)!==0}}function normalizeMode(n,S){let C=n??S,N=C;if(typeof C==`string`){if(!/^[0-7]+$/.test(C))throw invalidMode(C);N=parseInt(C,8)}if(typeof N!=`number`)throw modeNotANumber(N);if(!Number.isInteger(N))throw modeOutOfRange(`an integer`,N);if(N<0||N>4294967295)throw modeOutOfRange(`>= 0 && <= 4294967295`,N);return N}function invalidMode(n){let S=TypeError(`The argument 'mode' must be a 32-bit unsigned integer or an octal string. Received '${n}'`);return S.code=`ERR_INVALID_ARG_VALUE`,S}function modeNotANumber(n){let S=n==null?String(n):`type ${typeof n} (${describeValue(n)})`,C=TypeError(`The "mode" argument must be of type number. Received ${S}`);return C.code=`ERR_INVALID_ARG_TYPE`,C}function describeValue(n){try{return typeof n==`object`?Object.prototype.toString.call(n):String(n)}catch{return`<unprintable>`}}function modeOutOfRange(n,S){let C=RangeError(`The value of "mode" is out of range. It must be ${n}. Received ${S}`);return C.code=`ERR_OUT_OF_RANGE`,C}var Qc,$c,el,tl=__esmMin(()=>{Be(),Qc={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,O_CREAT:64,O_EXCL:128,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_NONBLOCK:2048,O_DSYNC:4096,O_SYNC:1052672,O_DIRECTORY:65536,O_NOFOLLOW:131072},$c={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,O_CREAT:512,O_EXCL:2048,O_NOCTTY:131072,O_TRUNC:1024,O_APPEND:8,O_NONBLOCK:4,O_DSYNC:4194304,O_SYNC:128,O_DIRECTORY:1048576,O_NOFOLLOW:256},el={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,O_CREAT:256,O_EXCL:1024,O_NOCTTY:0,O_TRUNC:512,O_APPEND:8,O_NONBLOCK:0,O_DSYNC:0,O_SYNC:0,O_DIRECTORY:0,O_NOFOLLOW:0}}),Dirent,nl=__esmMin(()=>{Rr(),Hs(),Dirent=class{name;parentPath;_isFile=!1;_isDirectory=!1;_isBlockDevice=!1;_isCharacterDevice=!1;_isSymbolicLink=!1;_isFIFO=!1;_isSocket=!1;_file;constructor(n,S,C,N){switch(S||=Fs(n),this.name=S,this.parentPath=Ps(n),this._file=Lr.File.new_for_path(n),C??this._file.query_file_type(Lr.FileQueryInfoFlags.NONE,null)){case Lr.FileType.DIRECTORY:this._isDirectory=!0;break;case Lr.FileType.MOUNTABLE:break;case Lr.FileType.REGULAR:this._isFile=!0;break;case Lr.FileType.SYMBOLIC_LINK:case Lr.FileType.SHORTCUT:this._isSymbolicLink=!0;break;case Lr.FileType.SPECIAL:this._classifySpecialFile(n,N);break}}_classifySpecialFile(n,S){try{let C=S?.has_attribute(`unix::mode`)===!0?S:Lr.File.new_for_path(n).query_info(`unix::mode`,Lr.FileQueryInfoFlags.NONE,null),N=C.has_attribute(`unix::mode`)?C.get_attribute_uint32(`unix::mode`):0;if(N===0)return;switch(N&61440){case 24576:this._isBlockDevice=!0;break;case 8192:this._isCharacterDevice=!0;break;case 49152:this._isSocket=!0;break;case 4096:this._isFIFO=!0;break}}catch{}}isFile(){return this._isFile}isDirectory(){return this._isDirectory}isBlockDevice(){return this._isBlockDevice}isCharacterDevice(){return this._isCharacterDevice}isSymbolicLink(){return this._isSymbolicLink}isFIFO(){return this._isFIFO}isSocket(){return this._isSocket}}});function fsError(n,S,C,N){let F=`${n}: ${describe(n)}, ${S}`;C&&(F+=` '${C}'`),N&&(F+=` -> '${N}'`);let I=Error(F);return I.code=n,I.errno=rl[n]??-1,I.syscall=S,C&&(I.path=C),N&&(I.dest=N),I}function describe(n){switch(n){case`ENOENT`:return`no such file or directory`;case`EEXIST`:return`file already exists`;case`EACCES`:return`permission denied`;case`EISDIR`:return`illegal operation on a directory`;case`ENOTDIR`:return`not a directory`;case`EBADF`:return`bad file descriptor`;case`EPERM`:return`operation not permitted`;case`EINVAL`:return`invalid argument`;case`ELOOP`:return`too many symbolic links encountered`;case`ENAMETOOLONG`:return`name too long`;case`EMFILE`:return`too many open files`;case`ENFILE`:return`file table overflow`;case`EROFS`:return`read-only file system`;case`ESPIPE`:return`invalid seek`;case`ENXIO`:return`no such device or address`;default:return`i/o error`}}function hasProcFd(){return il===null&&(il=ft.file_test(`/proc/self/fd`,ft.FileTest.IS_DIR)),il}function fdPath(n){return hasProcFd()?`/proc/self/fd/${n}`:null}function openFd(n,S,C){let N=ft.open(n,S.posix,C);if(N<0)throw classifyOpenFailure(n,S);return N}function closeFd(n){ft.close(n)}function classifyOpenFailure(n,S){let C=nameTooLong(n,`open`);if(C)return C;let N=Lr.File.new_for_path(n),F=null,I=!1;try{let n=N.query_info(`standard::type,standard::symlink-target,unix::mode,access::can-read,access::can-write`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null);answered(n)?F=n:I=!0}catch{F=null}if(I)return refusalNotAboutThePath(n,S,N,null);if(F){if(S.excl)return fsError(`EEXIST`,`open`,n);if(F.get_file_type()===Lr.FileType.SYMBOLIC_LINK&&!S.nofollow){let C=walkSymlinkChain(N);if(C===`loop`)return fsError(`ELOOP`,`open`,n);if(C===`too-long`)return fsError(`ENAMETOOLONG`,`open`,n);if(C===`dangling`&&!S.creat)return fsError(`ENOENT`,`open`,n)}return F.get_file_type()===Lr.FileType.DIRECTORY&&S.writable?fsError(`EISDIR`,`open`,n):S.directory&&F.get_file_type()!==Lr.FileType.DIRECTORY?fsError(`ENOTDIR`,`open`,n):refusalNotAboutThePath(n,S,N,F)}if(ancestorIsNotADirectory(N))return fsError(`ENOTDIR`,`open`,n);if(!S.creat)return fsError(`ENOENT`,`open`,n);let H=N.get_parent();if(!H)return fsError(`ENOENT`,`open`,n);try{H.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null)}catch{return fsError(`ENOENT`,`open`,n)}return refusalNotAboutThePath(n,S,N,null)}function ancestorIsNotADirectory(n){for(let S=n.get_parent();S;S=S.get_parent()){let n;try{n=S.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null)}catch{continue}return answered(n)?n.get_file_type()!==Lr.FileType.DIRECTORY:!1}return!1}function answered(n){return n!==null&&n.has_attribute(`standard::type`)}function nameTooLong(n,S){let C=new TextEncoder;if(C.encode(n).length>4096)return fsError(`ENAMETOOLONG`,S,n);for(let N of splitPathComponents(n))if(C.encode(N).length>255)return fsError(`ENAMETOOLONG`,S,n);return null}function walkSymlinkChain(n){let S=new TextEncoder,C=n;for(let n=0;n<40;n++){let n;try{n=C.query_info(`standard::type,standard::symlink-target`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch{return`dangling`}if(!answered(n)||n.get_file_type()!==Lr.FileType.SYMBOLIC_LINK)return`resolved`;let N=n.get_symlink_target();if(!N)return`dangling`;if(S.encode(N).length>4096)return`too-long`;let F=C.get_parent();C=N.startsWith(`/`)?Lr.File.new_for_path(N):F?.resolve_relative_path(N)??Lr.File.new_for_path(N)}return`loop`}function refusalNotAboutThePath(n,S,C,N){let F=ft.open(`/dev/null`,0,0);if(F<0)return fsError(`EMFILE`,`open`,n);ft.close(F);let I=N!==null&&(N.get_attribute_uint32(`unix::mode`)&146)==0;if((S.writable||S.creat)&&!I)try{if(C.query_filesystem_info(`filesystem::readonly`,null).get_attribute_boolean(`filesystem::readonly`))return fsError(`EROFS`,`open`,n)}catch{}return N&¬hingOnTheOtherEnd(S,N)?fsError(`ENXIO`,`open`,n):fsError(`EACCES`,`open`,n)}function nothingOnTheOtherEnd(n,S){if(!S.has_attribute(`unix::mode`))return!1;let C=S.get_attribute_uint32(`unix::mode`)&61440;if(!(C===8192||C===24576||C===4096))return!1;let permits=n=>S.has_attribute(n)&&S.get_attribute_boolean(n);return!(n.readable&&!permits(`access::can-read`)||n.writable&&!permits(`access::can-write`))}function classifyMkdirFailure(n){let S=nameTooLong(n,`mkdir`);if(S)return S;let C=Lr.File.new_for_path(n);try{return answered(C.query_info(`standard::type`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null))?fsError(`EEXIST`,`mkdir`,n):fsError(`EACCES`,`mkdir`,n)}catch{}let N=C.get_parent();if(!N)return fsError(`ENOENT`,`mkdir`,n);try{let S=N.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null);if(answered(S)&&S.get_file_type()!==Lr.FileType.DIRECTORY)return fsError(`ENOTDIR`,`mkdir`,n)}catch{return fsError(`ENOENT`,`mkdir`,n)}return fsError(`EACCES`,`mkdir`,n)}function seekHandle(n){let S=al.get(n);return S||(S=ft.IOChannel.unix_new(n),S.set_encoding(null),S.set_buffered(!1),S.set_close_on_unref(!1),al.set(n,S)),S}function input(n){let S=ol.get(n);return S||(S=da.InputStream.new(n,!1),ol.set(n,S)),S}function output(n){let S=sl.get(n);return S||(S=da.OutputStream.new(n,!1),sl.set(n,S)),S}function isSeekableFd(n,S){let C=cl.get(n);return C===void 0&&(C=probeSeekable(n,S),cl.set(n,C)),C}function probeSeekable(n,S){try{let C=Lr.File.new_for_path(fdPath(n)??S).query_info(`unix::mode`,Lr.FileQueryInfoFlags.NONE,null);if(C.has_attribute(`unix::mode`)){let n=C.get_attribute_uint32(`unix::mode`)&61440;if(n===4096||n===49152)return!1}}catch{}try{return seekHandle(n).seek_position(0,ft.SeekType.CUR),!0}catch{return!1}}function seekFd(n,S){seekHandle(n).seek_position(S,ft.SeekType.SET)}function tellFd(n){if(!hasProcFd())return null;try{let[S,C]=ft.file_get_contents(`/proc/self/fdinfo/${n}`);if(!S)return null;let N=/^pos:\s*(\d+)/m.exec(new TextDecoder().decode(C));return N?Number(N[1]):null}catch{return null}}function readFd(n,S){return S<=0?new Uint8Array:input(n).read_bytes(S,null).get_data()??new Uint8Array}function writeFd(n,S){if(S.length===0)return 0;let[,C]=output(n).write_all(S,null);return C}function fsyncFd(n){output(n).flush(null),ft.fsync(n)}function releaseFd(n){let S=sl.get(n);if(S)try{S.flush(null)}catch{}al.delete(n),ol.delete(n),sl.delete(n),cl.delete(n)}function sizeOfFd(n,S){let C=fdPath(n)??S,N=Lr.File.new_for_path(C).query_info(`standard::size`,Lr.FileQueryInfoFlags.NONE,null);return Number(N.get_size())}function truncateFd(n,S,C){let N=Lr.File.new_for_path(fdPath(n)??C),F;try{let n=N.append_to(Lr.FileCreateFlags.NONE,null);try{n.truncate(S,null)}finally{n.close(null)}return}catch(n){F=n}try{let n=N.open_readwrite(null);try{n.get_output_stream().truncate(S,null)}finally{n.close(null)}return}catch{}throw createNodeError(F,`ftruncate`,C)}var rl,il,al,ol,sl,cl,ll=__esmMin(()=>{Vc(),pt(),Rr(),Be(),fa(),rl={EPERM:-1,ENOENT:-2,EIO:-5,ENXIO:-6,EBADF:-9,EACCES:-13,EEXIST:-17,ENOTDIR:-20,EISDIR:-21,EINVAL:-22,ENFILE:-23,EMFILE:-24,ETXTBSY:-26,ENOSPC:-28,ESPIPE:-29,EROFS:-30,ENAMETOOLONG:-36,ENOTEMPTY:-39,ELOOP:-40},il=null,al=new Map,ol=new Map,sl=new Map,cl=new Map});function populateFromInfo(n){let S=n.get_attribute_uint64(`time::access`),C=n.get_attribute_uint32(`time::access-usec`)||0,N=n.get_attribute_uint64(`time::modified`),F=n.get_attribute_uint32(`time::modified-usec`)||0,I=n.get_attribute_uint64(`time::changed`),H=n.get_attribute_uint32(`time::changed-usec`)||0,W=n.get_attribute_uint64(`time::created`),q=n.get_attribute_uint32(`time::created-usec`)||0,Y=S*1e3+C/1e3,X=N*1e3+F/1e3,Z=I?I*1e3+H/1e3:X,te=W?W*1e3+q/1e3:Z;return{dev:n.get_attribute_uint32(`unix::device`)||0,ino:Number(n.get_attribute_uint64(`unix::inode`)||0),mode:n.get_attribute_uint32(`unix::mode`)||0,nlink:n.get_attribute_uint32(`unix::nlink`)||0,uid:n.get_attribute_uint32(`unix::uid`)||0,gid:n.get_attribute_uint32(`unix::gid`)||0,rdev:n.get_attribute_uint32(`unix::rdev`)||0,size:Number(n.get_size()||0),blksize:n.get_attribute_uint32(`unix::block-size`)||4096,blocks:Number(n.get_attribute_uint64(`unix::blocks`)||0),atimeMs:Y,mtimeMs:X,ctimeMs:Z,birthtimeMs:te,atime:new Date(Y),mtime:new Date(X),ctime:new Date(Z),birthtime:new Date(te)}}function statsFrom(n,S,C,N){if(!answered(n))throw fsError(`EACCES`,C,S);return N?new BigIntStats(n,S):new Stats(n,S)}var ul,Stats,BigIntStats,dl=__esmMin(()=>{nl(),ll(),Rr(),Hs(),ul=`standard::*,time::*,unix::*`,Stats=class extends Dirent{dev;ino;mode;nlink;uid;gid;rdev;size;blksize;blocks;atimeMs;mtimeMs;ctimeMs;birthtimeMs;atime;mtime;ctime;birthtime;_info;constructor(n,S,C){let N,F;n instanceof Lr.FileInfo?(N=n,F=S.toString(),C||=Fs(F)):(F=n.toString(),typeof S==`string`&&(C=S),C||=Fs(F),N=Lr.File.new_for_path(F).query_info(ul,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)),super(F,C,N.get_file_type(),N),this._info=N;let I=populateFromInfo(N);this.dev=I.dev,this.ino=I.ino,this.mode=I.mode,this.nlink=I.nlink,this.uid=I.uid,this.gid=I.gid,this.rdev=I.rdev,this.size=I.size,this.blksize=I.blksize,this.blocks=I.blocks,this.atimeMs=I.atimeMs,this.mtimeMs=I.mtimeMs,this.ctimeMs=I.ctimeMs,this.birthtimeMs=I.birthtimeMs,this.atime=I.atime,this.mtime=I.mtime,this.ctime=I.ctime,this.birthtime=I.birthtime}},BigIntStats=class extends Dirent{dev;ino;mode;nlink;uid;gid;rdev;size;blksize;blocks;atimeMs;mtimeMs;ctimeMs;birthtimeMs;atimeNs;mtimeNs;ctimeNs;birthtimeNs;atime;mtime;ctime;birthtime;_info;constructor(n,S,C){let N,F;n instanceof Lr.FileInfo?(N=n,F=S.toString(),C||=Fs(F)):(F=n.toString(),typeof S==`string`&&(C=S),C||=Fs(F),N=Lr.File.new_for_path(F).query_info(ul,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)),super(F,C,N.get_file_type(),N),this._info=N;let I=populateFromInfo(N);this.dev=BigInt(I.dev),this.ino=BigInt(I.ino),this.mode=BigInt(I.mode),this.nlink=BigInt(I.nlink),this.uid=BigInt(I.uid),this.gid=BigInt(I.gid),this.rdev=BigInt(I.rdev),this.size=BigInt(I.size),this.blksize=BigInt(I.blksize),this.blocks=BigInt(I.blocks),this.atimeMs=BigInt(Math.trunc(I.atimeMs)),this.mtimeMs=BigInt(Math.trunc(I.mtimeMs)),this.ctimeMs=BigInt(Math.trunc(I.ctimeMs)),this.birthtimeMs=BigInt(Math.trunc(I.birthtimeMs)),this.atimeNs=this.atimeMs*1000000n,this.mtimeNs=this.mtimeMs*1000000n,this.ctimeNs=this.ctimeMs*1000000n,this.birthtimeNs=this.birthtimeMs*1000000n,this.atime=I.atime,this.mtime=I.mtime,this.ctime=I.ctime,this.birthtime=I.birthtime}}});function statSync(n,S){let C=normalizePath(n);try{return statsFrom(Lr.File.new_for_path(C).query_info(ul,Lr.FileQueryInfoFlags.NONE,null),C,`stat`,S?.bigint)}catch(n){if(S?.throwIfNoEntry===!1&&isNotFoundError(n))return;throw createNodeError(n,`stat`,C)}}function lstatSync(n,S){let C=normalizePath(n);try{return statsFrom(Lr.File.new_for_path(C).query_info(ul,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null),C,`lstat`,S?.bigint)}catch(n){if(S?.throwIfNoEntry===!1&&isNotFoundError(n))return;throw createNodeError(n,`lstat`,C)}}function readdirSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C).enumerate_children(`standard::name,standard::type`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null),F=[];try{let n=N.next_file(null);for(;n!==null;)F.push({name:n.get_name(),type:n.get_file_type()}),n=N.next_file(null)}finally{try{N.close(null)}catch{}}let I=[];for(let n of F){let N=js(C,n.name);if(S?.withFileTypes?I.push(new Dirent(N,n.name,n.type)):I.push(n.name),S?.recursive&&n.type===Lr.FileType.DIRECTORY){let C=readdirSync(N,S);for(let S of C)typeof S==`string`?I.push(js(n.name,S)):I.push(S)}}return I}function realpathSync(n){let S=normalizePath(n);return resolveEveryComponent(Lr.File.new_for_path(S),{left:40},S)}function resolveEveryComponent(n,S,C){let N=n.get_parent();return expandSymlinks(N===null?n:Lr.File.new_for_path(resolveEveryComponent(N,S,C)).get_child(n.get_basename()),S,C)}function expandSymlinks(n,S,C){let N=n;for(;;){let n=N.query_info(`standard::is-symlink,standard::symlink-target`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null);if(!n.get_is_symlink())return N.get_path();if(--S.left<0)throw Error(`ELOOP: too many levels of symbolic links, realpath '${C}'`);let F=n.get_symlink_target(),I=N.get_parent(),H=ft.path_is_absolute(F)?Lr.File.new_for_path(F):(I??N).resolve_relative_path(F);N=Lr.File.new_for_path(resolveEveryComponent(H,S,C))}}function symlinkSync(n,S,C){let N=normalizePath(S),F=normalizePath(n);Lr.File.new_for_path(N).make_symbolic_link(F,null)}function readFileSync(n,S={encoding:null,flag:`r`}){if(n instanceof Nl&&(n=n.fd),typeof n==`number`&&isStdFd(n))return encodeUint8Array(getEncodingFromOptions(S,`buffer`),readStdFdAll(n));if(typeof n==`number`)return encodeUint8Array(getEncodingFromOptions(S,`buffer`),Nl.getInstance(n,`read`)._readToEndSync());let C=normalizePath(n),N=Lr.File.new_for_path(C);try{let[n,F]=N.load_contents(null);if(!n)throw createNodeError(Error(`failed to read file`),`read`,C);return encodeUint8Array(getEncodingFromOptions(S,`buffer`),F)}catch(n){throw n.code&&typeof n.code==`string`?n:createNodeError(n,`read`,C)}}function mkdirSync(n,S){let C=!1,N;S!=null&&(typeof S==`object`?(S.recursive&&(C=S.recursive),S.mode!==void 0&&(N=S.mode)):N=S),n=normalizePath(n);let F=normalizeMode(N,511);if(C)return mkdirSyncRecursive(n,F);mkdirWithMode(n,F)}function mkdirWithMode(n,S){if(ft.mkdir(n,S)!==0)throw classifyMkdirFailure(n)}function mkdirSyncRecursive(n,S){if(ft.mkdir(n,S)===0)return n;let C=classifyMkdirFailure(n);if(C.code===`EEXIST`){if(ft.file_test(n,ft.FileTest.IS_DIR))return;throw C}if(C.code!==`ENOENT`)throw C;let N=js(n,`..`),F=Lr.File.new_for_path(N).get_path();if(F===n)throw C;let I=mkdirSyncRecursive(F,S);return mkdirWithMode(n,S),I??n}function rmdirSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);try{if(N.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null).get_file_type()!==Lr.FileType.DIRECTORY)throw createNodeError(Object.assign(Error(),{code:4}),`rmdir`,C);if(N.enumerate_children(`standard::name`,Lr.FileQueryInfoFlags.NONE,null).next_file(null)!==null)throw createNodeError(Object.assign(Error(),{code:5}),`rmdir`,C);N.delete(null)}catch(n){throw n.code&&typeof n.code==`string`?n:createNodeError(n,`rmdir`,C)}}function unlinkSync(n){let S=normalizePath(n),C=Lr.File.new_for_path(S);try{C.delete(null)}catch(n){throw createNodeError(n,`unlink`,S)}}function writeWholeFile(n,S,C,N){let F=getEncodingFromOptions(C,`utf8`),I=typeof C==`object`&&C?C:{},H=typeof S==`string`?$e.from(S,F||`utf8`):S;if(typeof n==`number`||n instanceof Nl){if(typeof n==`number`&&isStdFd(n)){writeStdFdSync(n,H);return}Nl.getInstance(n,`write`)._writeSync(H,null);return}let W=new Nl({path:normalizePath(n),flags:I.flag??N,mode:I.mode??438});try{W._writeSync(H,null)}finally{W._closeSync()}}function writeFileSync(n,S,C){writeWholeFile(n,S,C??null,`w`)}function renameSync(n,S){let C=normalizePath(n),N=normalizePath(S),F=Lr.File.new_for_path(C),I=Lr.File.new_for_path(N);try{F.move(I,Lr.FileCopyFlags.OVERWRITE,null,null)}catch(n){throw createNodeError(n,`rename`,C,N)}}function copyFileSync(n,S,C){let N=normalizePath(n),F=normalizePath(S),I=Lr.File.new_for_path(N),H=Lr.File.new_for_path(F),W=Lr.FileCopyFlags.NONE;C&&!(C&1)?W=Lr.FileCopyFlags.OVERWRITE:C||(W=Lr.FileCopyFlags.OVERWRITE);try{I.copy(H,W,null,null)}catch(n){throw createNodeError(n,`copyfile`,N,F)}stripPrivilegeBitsAfterCopy(H,N,F)}function stripPrivilegeBitsAfterCopy(n,S,C){try{let S=n.query_info(`unix::mode,standard::size`,Lr.FileQueryInfoFlags.NONE,null);if(S.get_size()===0)return;let C=S.get_attribute_uint32(`unix::mode`),N=C&-2049;if((isDarwin()||C&8)&&(N&=-1025),N===C)return;n.set_attribute_uint32(`unix::mode`,N,Lr.FileQueryInfoFlags.NONE,null)}catch(n){throw createNodeError(n,`copyfile`,S,C)}}function accessSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);try{let n=N.query_info(`access::*`,Lr.FileQueryInfoFlags.NONE,null);if(S!==void 0&&S!==0){let N={code:14,message:`permission denied, access '${C}'`};if(S&4&&!n.get_attribute_boolean(`access::can-read`)||S&2&&!n.get_attribute_boolean(`access::can-write`)||S&1&&!n.get_attribute_boolean(`access::can-execute`))throw createNodeError(N,`access`,C)}}catch(n){throw n.code&&typeof n.code==`string`?n:createNodeError(n,`access`,C)}}function appendFileSync(n,S,C){writeWholeFile(n,S,C??null,`a`)}function readlinkSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);try{let n=N.query_info(`standard::symlink-target`,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null).get_symlink_target();if(!n)throw Object.assign(Error(`EINVAL: invalid argument, readlink '${C}'`),{code:`EINVAL`,errno:-22,syscall:`readlink`,path:C});return(typeof S==`string`?S:S?.encoding)===`buffer`?$e.from(n):n}catch(n){throw typeof n.code==`string`?n:createNodeError(n,`readlink`,C)}}function linkSync(n,S){let C=normalizePath(n),N=normalizePath(S);if(Lr.File.new_for_path(C).query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)===Lr.FileType.UNKNOWN)throw Object.assign(Error(`ENOENT: no such file or directory, link '${C}' -> '${N}'`),{code:`ENOENT`,errno:-2,syscall:`link`,path:C,dest:N});if(Lr.File.new_for_path(N).query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)!==Lr.FileType.UNKNOWN)throw Object.assign(Error(`EEXIST: file already exists, link '${C}' -> '${N}'`),{code:`EEXIST`,errno:-17,syscall:`link`,path:C,dest:N});let F=``;try{let[,,n,S]=ft.spawn_sync(null,[`ln`,`--`,C,N],null,ft.SpawnFlags.SEARCH_PATH,null);if(F=n?new TextDecoder().decode(n).trim():``,!ft.spawn_check_wait_status(S))throw Error(`ln exited non-zero (${S})`);return}catch(n){throw F===``&&n instanceof Error&&(F=n.message),Object.assign(Error(`EPERM: operation not permitted, link '${C}' -> '${N}'`+(F?` (${F})`:``)),{code:`EPERM`,errno:-1,syscall:`link`,path:C,dest:N})}}function truncateSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);try{let n=N.open_readwrite(null);try{n.get_output_stream().truncate(Math.max(0,S??0),null)}finally{n.close(null)}}catch(n){throw createNodeError(n,`truncate`,C)}}function chmodSync(n,S){let C=normalizePath(n),N=normalizeMode(S);try{Lr.File.new_for_path(C).set_attribute_uint32(`unix::mode`,N,Lr.FileQueryInfoFlags.NONE,null)}catch(n){throw createNodeError(n,`chmod`,C)}}function chownSync(n,S,C){let N=normalizePath(n);try{let n=Lr.File.new_for_path(N),F=new Lr.FileInfo;S!==-1&&F.set_attribute_uint32(`unix::uid`,S),C!==-1&&F.set_attribute_uint32(`unix::gid`,C),n.set_attributes_from_info(F,Lr.FileQueryInfoFlags.NONE,null)}catch(n){throw createNodeError(n,`chown`,N)}}function watch(n,S,C){return typeof S==`function`&&(C=S,S=void 0),new FSWatcher(normalizePath(n),S,C)}function openSync(n,S,C){return new Nl({path:n,flags:S,mode:C})}function mkdtempSync(n,S){let C=getEncodingFromOptions(S),N=mkdtempAt(n);return C===`buffer`?$e.from(N):decode(N,C)}function mkdtempAt(n){for(let S=0;S<64;S++){let S=n+randomName();if(ft.mkdir(S,448)===0)return S;let C=classifyMkdirFailure(S);if(C.code!==`EEXIST`)throw C.syscall=`mkdtemp`,C}throw fsError(`EEXIST`,`mkdtemp`,n+`XXXXXX`)}function rmSync(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C),F=S?.recursive||!1,I=S?.force||!1,H;try{H=N.query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){if(I&&isNotFoundError(S))return;throw createNodeError(S,`rm`,n)}if(H===Lr.FileType.SYMBOLIC_LINK){try{N.delete(null)}catch(S){if(I&&isNotFoundError(S))return;throw createNodeError(S,`rm`,n)}return}if(H===Lr.FileType.DIRECTORY){let N=readdirSync(n);if(!F&&N.length)throw createNodeError(Object.assign(Error(),{code:5}),`rm`,n);for(let n of N)rmSync(js(C,n),S)}try{N.delete(null)}catch(S){if(I&&isNotFoundError(S))return;throw createNodeError(S,`rm`,n)}}var fl=__esmMin(()=>{Xc(),Bc(),Vc(),Wc(),Yc(),tl(),nl(),ll(),dl(),Pl(),pt(),Rr(),Hs(),lt(),va(),Be(),realpathSync.native=realpathSync});function makeEEXIST(n){let S=Error(`ERR_FS_CP_EEXIST: file already exists, copyfile '${n}'`);return S.code=`ERR_FS_CP_EEXIST`,S.syscall=`copyfile`,S.path=n,S}function makeEISDIR(n){let S=Error(`ERR_FS_EISDIR: illegal operation on a directory, copyfile '${n}'`);return S.code=`ERR_FS_EISDIR`,S.syscall=`copyfile`,S.path=n,S}function makeENOTDIR(n,S){let C=Error(`ENOTDIR: not a directory, copyfile '${n}' -> '${S}'`);return C.code=`ENOTDIR`,C.syscall=`copyfile`,C.path=n,C.dest=S,C}function makeSYMLINKLOOP(n,S){let C=Error(`ELOOP: too many levels of symbolic links, copyfile '${n}' -> '${S}'`);return C.code=`ELOOP`,C.syscall=`copyfile`,C.path=n,C.dest=S,C}function queryCopyFlags(n){let S=n.force??!0,C=Lr.FileCopyFlags.NONE;return S&&(C|=Lr.FileCopyFlags.OVERWRITE),n.preserveTimestamps&&(C|=Lr.FileCopyFlags.TARGET_DEFAULT_MODIFIED_TIME),n.dereference||(C|=Lr.FileCopyFlags.NOFOLLOW_SYMLINKS),C}function copyOneSyncFile(n,S,C,N,F){let I=F.force??!0;try{if(S.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null).get_file_type()===Lr.FileType.DIRECTORY)throw makeENOTDIR(C,N);if(!I){if(F.errorOnExist)throw makeEEXIST(N);return}}catch(n){if(typeof n.code==`string`)throw n}let H=queryCopyFlags(F);try{n.copy(S,H,null,null)}catch(n){throw createNodeError(n,`copyfile`,C,N)}}function cpOneDirSync(n,S,C,N,F){let I=C.endsWith(`/`)?``:`/`;if(N.startsWith(C+I)&&N!==C)throw makeSYMLINKLOOP(C,N);if(S.query_exists(null))try{if(S.query_info(`standard::type`,Lr.FileQueryInfoFlags.NONE,null).get_file_type()!==Lr.FileType.DIRECTORY)throw makeENOTDIR(N,C)}catch(n){if(typeof n.code==`string`)throw n}else try{S.make_directory_with_parents(null)}catch(n){throw createNodeError(n,`mkdir`,N)}let H;try{H=n.enumerate_children(`standard::name,standard::type,standard::is-symlink`,F.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(n){throw createNodeError(n,`scandir`,C)}let W=H.next_file(null);for(;W!==null;){let n=W.get_name(),S=js(C,n),I=js(N,n),q=F.filter;if(q&&!q(S,I)){W=H.next_file(null);continue}cpSyncInternal(S,I,F),W=H.next_file(null)}}function cpSyncInternal(n,S,C){let N=Lr.File.new_for_path(n),F=Lr.File.new_for_path(S),I;try{I=N.query_info(`standard::type,standard::is-symlink`,C.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){throw createNodeError(S,`stat`,n)}if(I.get_file_type()===Lr.FileType.DIRECTORY){if(!C.recursive)throw makeEISDIR(n);cpOneDirSync(N,F,n,S,C)}else copyOneSyncFile(N,F,n,S,C)}function cpSync(n,S,C){let N=normalizePath(n),F=normalizePath(S),I=C??{},H=Lr.File.new_for_path(N),W=I.filter;if(!(W&&!W(N,F))){try{if(H.query_info(`standard::type`,I.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null).get_file_type()===Lr.FileType.DIRECTORY&&!I.recursive)throw makeEISDIR(N)}catch(n){throw typeof n.code==`string`?n:createNodeError(n,`stat`,N)}cpSyncInternal(N,F,I)}}function cp(n,S,C,N){let F,I;typeof C==`function`?(I=C,F={}):(I=requireCallback(N),F=C);let H=F.filter;if(H){Promise.resolve(H(normalizePath(n),normalizePath(S))).then(C=>{if(!C){I(null);return}try{cpPromises(n,S,F).then(()=>I(null)).catch(I)}catch(n){I(n)}}).catch(I);return}Promise.resolve().then(()=>{try{cpSync(n,S,F),I(null)}catch(n){I(n)}})}async function cpPromisesDir(n,S,C){let N=n.endsWith(`/`)?``:`/`;if(S.startsWith(n+N)&&S!==n)throw makeSYMLINKLOOP(n,S);let F=Lr.File.new_for_path(S);if(!F.query_exists(null))try{F.make_directory_with_parents(null)}catch(n){throw createNodeError(n,`mkdir`,S)}let I=Lr.File.new_for_path(n),H;try{H=I.enumerate_children(`standard::name,standard::type`,C.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){throw createNodeError(S,`scandir`,n)}let W=H.next_file(null);for(;W!==null;){let N=W.get_name(),F=js(n,N),I=js(S,N),q=C.filter;if(q&&!await Promise.resolve(q(F,I))){W=H.next_file(null);continue}await cpPromises(F,I,C),W=H.next_file(null)}}async function cpPromises(n,S,C={}){let N=normalizePath(n),F=normalizePath(S),I=Lr.File.new_for_path(N),H;try{H=I.query_info(`standard::type`,C.dereference?Lr.FileQueryInfoFlags.NONE:Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(n){throw createNodeError(n,`stat`,N)}if(H.get_file_type()===Lr.FileType.DIRECTORY){if(!C.recursive)throw makeEISDIR(N);await cpPromisesDir(N,F,C)}else copyOneSyncFile(I,Lr.File.new_for_path(F),N,F,C)}var pl=__esmMin(()=>{Bc(),Vc(),Rr(),Hs()});function _openDir(n){let S=Lr.File.new_for_path(n),C;try{C=S.enumerate_children(ml,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){throw createNodeError(S,`opendir`,n)}return new Dir(n,C)}function opendirSync(n){return _openDir(normalizePath(n))}function opendir(n,S,C){let N;if(N=typeof S==`function`?S:requireCallback(C,`callback`),typeof N!=`function`)throw TypeError(`The "callback" argument must be of type function`);Promise.resolve().then(()=>{try{let S=opendirSync(n);N(null,S)}catch(n){N(n,null)}})}async function opendirAsync(n,S){return new Promise((S,C)=>{let N=normalizePath(n),F=Lr.File.new_for_path(N);F.enumerate_children_async(ml,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,ft.PRIORITY_DEFAULT,null,(n,I)=>{try{let n=F.enumerate_children_finish(I);S(new Dir(N,n))}catch(n){C(createNodeError(n,`opendir`,N))}})})}var ml,Dir,hl=__esmMin(()=>{Bc(),Vc(),nl(),pt(),Rr(),ml=`standard::name,standard::type,standard::is-symlink,standard::size,standard::symlink-target,unix::uid,unix::gid,unix::mode,time::modified,time::access,time::created`,Dir=class{path;_enumerator;_closed=!1;constructor(n,S){this.path=n,this._enumerator=S}_assertOpen(){if(this._closed){let n=Error(`Directory handle was closed`);throw n.code=`ERR_DIR_CLOSED`,n}}readSync(){this._assertOpen();try{let n=this._enumerator.next_file(null);if(n===null)return null;let S=n.get_name(),C=n.get_file_type();return new Dirent(this.path.endsWith(`/`)?this.path+S:this.path+`/`+S,S,C)}catch(n){throw createNodeError(n,`readdir`,this.path)}}read(n){if(n!==void 0){if(typeof n!=`function`)throw TypeError(`The "callback" argument must be of type function`);try{this._assertOpen();let S=this.readSync();Promise.resolve().then(()=>n(null,S))}catch(S){Promise.resolve().then(()=>n(S,null))}return}return new Promise((n,S)=>{try{this._assertOpen(),n(this.readSync())}catch(n){S(n)}})}closeSync(){this._assertOpen(),this._closed=!0;try{this._enumerator.close(null)}catch{}this._enumerator=null}close(n){if(n!==void 0){if(typeof n!=`function`)throw TypeError(`The "callback" argument must be of type function`);try{this.closeSync(),Promise.resolve().then(()=>n(null))}catch(S){Promise.resolve().then(()=>n(S))}return}return new Promise((n,S)=>{try{this.closeSync(),n()}catch(n){S(n)}})}async*[Symbol.asyncIterator](){try{for(;;){let n=await this.read();if(n===null)break;yield n}}finally{this._closed||await this.close()}}}});function segmentToRegexSrc(n){let S=/^([!*+?@])\((.+)\)$/.exec(n);if(S){let[,n,C]=S,N=C.split(`|`).map(n=>segmentToRegexSrc(n)),F=`(?:`+N.join(`|`)+`)`;switch(n){case`!`:return`(?!(?:`+N.join(`|`)+`))[^/]*`;case`*`:return F+`*`;case`+`:return F+`+`;case`?`:return F+`?`;case`@`:return F}}let C=``,N=0;for(;N<n.length;){let S=n[N];if(S===`*`){C+=`[^/]*`,N++;continue}if(S===`?`){C+=`[^/]`,N++;continue}if(S===`[`){let S=n.indexOf(`]`,N+1);if(S===-1){C+=`\\[`,N++;continue}C+=n.slice(N,S+1),N=S+1;continue}if(S===`{`){let S=n.indexOf(`}`,N+1);if(S===-1){C+=`\\{`,N++;continue}let F=n.slice(N+1,S).split(`,`).map(n=>segmentToRegexSrc(n.trim()));C+=`(?:`+F.join(`|`)+`)`,N=S+1;continue}`.+^$|()[]{}`.includes(S)?C+=`\\`+S:C+=S,N++}return C}function globToRegex$2(n){n=n.replace(/\/+/g,`/`).replace(/^\.\//,``);let S=n.split(`/`),C=[];for(let n=0;n<S.length;n++){let N=S[n],F=n===S.length-1;N===`**`?F?C.length>0&&C[C.length-1]===`/`?(C.pop(),C.push(`(?:/.+)?`)):C.push(`(?:.+)?`):C.push(`(?:[^/]+/)*`):(C.push(segmentToRegexSrc(N)),F||C.push(`/`))}return RegExp(`^(?:`+C.join(``)+`)$`)}function buildExcludePredicate(n){if(!n)return null;if(typeof n==`function`)return n;let S=(Array.isArray(n)?n:[n]).map(n=>globToRegex$2(n));return n=>S.some(S=>S.test(n))}function matchAll(n,S,C){let N=globToRegex$2(n),F=buildExcludePredicate(C),I;try{I=readdirSync(S,{recursive:!0})}catch{return[]}let H=[`.`,...I],W=[];for(let n of H){let S=n.replace(/\\/g,`/`);N.test(S)&&(F&&F(S)||W.push(n))}return W}function globSync(n,S){let C=Array.isArray(n)?n:[n],N=S?.cwd?normalizePath(S.cwd):globalThis.process?.cwd?.()??`/`,F=S?.exclude,I=new Set,H=[];for(let n of C)for(let S of matchAll(n,N,F))I.has(S)||(I.add(S),H.push(S));return H}function glob(n,S,C){let N,F;typeof S==`function`?(F=S,N={}):(F=requireCallback(C),N=S||{}),Promise.resolve().then(()=>{try{let S=globSync(n,N);F(null,S)}catch(n){F(n,[])}})}async function*globAsync(n,S){let C=globSync(n,S);for(let n of C)yield n}var gl=__esmMin(()=>{Bc(),Vc(),fl(),__name$1(globToRegex$2,`globToRegex`)});function buildStatFs(n){let S=Number(n.get_attribute_uint64(`filesystem::size`)??0),C=Number(n.get_attribute_uint64(`filesystem::free`)??0),N=Math.floor(S/vl),F=Math.floor(C/vl);return{type:0,bsize:vl,blocks:N,bfree:F,bavail:F,files:0,ffree:0}}function buildBigIntStatFs(n){let S=BigInt(n.get_attribute_uint64(`filesystem::size`)??0),C=BigInt(n.get_attribute_uint64(`filesystem::free`)??0),N=BigInt(vl),F=S/N,I=C/N;return{type:0n,bsize:N,blocks:F,bfree:I,bavail:I,files:0n,ffree:0n}}function statfsSync(n,S){let C=Lr.File.new_for_path(normalizePath(n)).query_filesystem_info(_l,null);return S?.bigint===!0?buildBigIntStatFs(C):buildStatFs(C)}function queryFsInfoAsync(n,S){return new Promise((C,N)=>{let F=Lr.File.new_for_path(normalizePath(n));F.query_filesystem_info_async(_l,ft.PRIORITY_DEFAULT,null,(n,I)=>{try{let n=F.query_filesystem_info_finish(I);C(S?buildBigIntStatFs(n):buildStatFs(n))}catch(n){N(n)}})})}function statfs(n,S,C){let N=typeof S==`function`?S:requireCallback(C);queryFsInfoAsync(n,(typeof S==`function`?{}:S)?.bigint===!0).then(n=>N(null,n),n=>N(n,null))}async function statfsAsync(n,S){return queryFsInfoAsync(n,S?.bigint===!0)}var _l,vl,yl=__esmMin(()=>{Bc(),Vc(),pt(),Rr(),_l=[`filesystem::size`,`filesystem::free`].join(`,`),vl=4096}),bl=__exportAll$4({access:()=>access$1,appendFile:()=>appendFile$1,chmod:()=>chmod$1,chown:()=>chown$1,copyFile:()=>copyFile$1,cp:()=>cpPromises,default:()=>Sl,fchmod:()=>fchmodAsync,fchown:()=>fchownAsync,fdatasync:()=>fdatasyncAsync,fstat:()=>fstatAsync,fsync:()=>fsyncAsync,ftruncate:()=>ftruncateAsync,futimes:()=>futimesAsync,glob:()=>globAsync,lchmod:()=>lchmodAsync,lchown:()=>lchownAsync,link:()=>link$1,lstat:()=>lstat$1,lutimes:()=>lutimesAsync,mkdir:()=>mkdir$1,mkdtemp:()=>mkdtemp$1,open:()=>open$2,openAsBlob:()=>openAsBlob,opendir:()=>opendirAsync,promises_exports:()=>xl,readFile:()=>readFile$1,readdir:()=>readdir$1,readlink:()=>readlink$1,readv:()=>readvAsync,realpath:()=>realpath$1,rename:()=>rename$1,rm:()=>rm$1,rmdir:()=>rmdir$1,stat:()=>stat$1,statfs:()=>statfsAsync,symlink:()=>symlink$1,truncate:()=>truncate$1,unlink:()=>unlink$1,utimes:()=>utimesAsync,watch:()=>watchAsync,write:()=>write$1,writeFile:()=>writeFile$1,writev:()=>writevAsync});async function mkdir$1(n,S){return mkdirSync(normalizePath(n),S)}async function readFile$1(n,S={encoding:null,flag:`r`}){if(n instanceof Nl||typeof n==`number`){let C=Nl.getInstance(n,`read`);return encodeUint8Array(getEncodingFromOptions(S,`buffer`),C._readToEndSync())}let C=normalizePath(n),N=Lr.File.new_for_path(C),F,I;try{[F,I]=await new Promise((n,S)=>{N.load_contents_async(null,(C,F)=>{try{n(N.load_contents_finish(F))}catch(n){S(n)}})})}catch(n){throw createNodeError(n,`open`,C)}if(!F)throw createNodeError(Error(`failed to read file`),`open`,C);return encodeUint8Array(getEncodingFromOptions(S,`buffer`),I)}async function mkdtemp$1(n,S){let C=getEncodingFromOptions(S);return decode(mkdtempAt(n),C)}async function writeFile$1(n,S,C){writeFileSync(n,typeof S==`string`||S instanceof Uint8Array?S:String(S),C??null)}async function rmdir$1(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C);if((await new Promise((n,S)=>{N.query_info_async(`standard::type`,Lr.FileQueryInfoFlags.NONE,ft.PRIORITY_DEFAULT,null,(F,I)=>{try{n(N.query_info_finish(I))}catch(n){S(createNodeError(n,`rmdir`,C))}})})).get_file_type()!==Lr.FileType.DIRECTORY)throw createNodeError(Object.assign(Error(),{code:4}),`rmdir`,C);if((await new Promise((n,S)=>{N.enumerate_children_async(`standard::name`,Lr.FileQueryInfoFlags.NONE,ft.PRIORITY_DEFAULT,null,(F,I)=>{try{n(N.enumerate_children_finish(I))}catch(n){S(createNodeError(n,`rmdir`,C))}})})).next_file(null)!==null)throw createNodeError(Object.assign(Error(),{code:5}),`rmdir`,C);await new Promise((n,S)=>{N.delete_async(ft.PRIORITY_DEFAULT,null,(F,I)=>{try{N.delete_finish(I),n()}catch(n){S(createNodeError(n,`rmdir`,C))}})})}async function unlink$1(n){let S=normalizePath(n),C=Lr.File.new_for_path(S);await new Promise((n,N)=>{C.delete_async(ft.PRIORITY_DEFAULT,null,(F,I)=>{try{C.delete_finish(I),n()}catch(n){N(createNodeError(n,`unlink`,S))}})})}async function open$2(n,S,C){return new Nl({path:n,flags:S,mode:C})}async function write$1(n,S,C,N,F){return typeof S==`string`?_writeStr(n,S,C,N):_writeBuf(n,S,C,N,F)}async function _writeBuf(n,S,C,N,F){return{bytesWritten:(await Nl.getInstance(n,`write`).write(S,C,N,F)).bytesWritten,buffer:S}}async function _writeStr(n,S,C,N){return{bytesWritten:(await Nl.getInstance(n,`write`).write(S,C,N)).bytesWritten,buffer:S}}function queryInfoAsync(n,S,C,N){let F=normalizePath(n);return new Promise((n,I)=>{let H=Lr.File.new_for_path(F);H.query_info_async(ul,S,ft.PRIORITY_DEFAULT,null,(S,W)=>{try{n(statsFrom(H.query_info_finish(W),F,C,N?.bigint))}catch(n){I(createNodeError(n,C,F))}})})}async function stat$1(n,S){return queryInfoAsync(n,Lr.FileQueryInfoFlags.NONE,`stat`,S)}async function lstat$1(n,S){return queryInfoAsync(n,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,`lstat`,S)}async function readdir$1(n,S){try{return readdirSync(n,S)}catch(S){throw createNodeError(S,`scandir`,n)}}async function realpath$1(n){return realpathSync(n)}async function symlink$1(n,S,C){let N=normalizePath(S),F=normalizePath(n);return new Promise((n,S)=>{let C=Lr.File.new_for_path(N);C.make_symbolic_link_async(F,ft.PRIORITY_DEFAULT,null,(I,H)=>{try{C.make_symbolic_link_finish(H),n()}catch(n){S(createNodeError(n,`symlink`,F,N))}})})}async function rm$1(n,S){let C=normalizePath(n),N=Lr.File.new_for_path(C),F=S?.recursive||!1,I=S?.force||!1,H;try{H=N.query_file_type(Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,null)}catch(S){if(I)return;throw createNodeError(S,`rm`,n)}if(H===Lr.FileType.SYMBOLIC_LINK){await new Promise((S,C)=>{N.delete_async(ft.PRIORITY_DEFAULT,null,(F,H)=>{try{N.delete_finish(H),S()}catch(N){if(I){S();return}C(createNodeError(N,`rm`,n))}})});return}if(H===Lr.FileType.DIRECTORY){let N=await readdir$1(n,{withFileTypes:!0});if(!F&&N.length)throw createNodeError(Object.assign(Error(),{code:5}),`rm`,n);for(let n of N)typeof n!=`string`&&await rm$1(js(C,n.name),S)}await new Promise((S,C)=>{N.delete_async(ft.PRIORITY_DEFAULT,null,(F,H)=>{try{N.delete_finish(H),S()}catch(N){if(I){S();return}C(createNodeError(N,`rm`,n))}})})}async function rename$1(n,S){renameSync(n,S)}async function copyFile$1(n,S,C){copyFileSync(n,S,C)}async function access$1(n,S){accessSync(n,S)}async function appendFile$1(n,S,C){appendFileSync(n,S,C)}async function readlink$1(n,S){return readlinkSync(n,S)}async function truncate$1(n,S){truncateSync(n,S)}async function chmod$1(n,S){chmodSync(n,S)}async function chown$1(n,S,C){chownSync(n,S,C)}async function link$1(n,S){linkSync(n,S)}var xl,Sl,Cl=__esmMin(()=>{zc(),Xc(),Bc(),Vc(),Wc(),Kc(),Fl(),dl(),Pl(),fl(),pl(),hl(),gl(),yl(),pt(),Rr(),Hs(),xl=Rc({access:()=>access$1,appendFile:()=>appendFile$1,chmod:()=>chmod$1,chown:()=>chown$1,copyFile:()=>copyFile$1,cp:()=>cpPromises,default:()=>Sl,fchmod:()=>fchmodAsync,fchown:()=>fchownAsync,fdatasync:()=>fdatasyncAsync,fstat:()=>fstatAsync,fsync:()=>fsyncAsync,ftruncate:()=>ftruncateAsync,futimes:()=>futimesAsync,glob:()=>globAsync,lchmod:()=>lchmodAsync,lchown:()=>lchownAsync,link:()=>link$1,lstat:()=>lstat$1,lutimes:()=>lutimesAsync,mkdir:()=>mkdir$1,mkdtemp:()=>mkdtemp$1,open:()=>open$2,openAsBlob:()=>openAsBlob,opendir:()=>opendirAsync,readFile:()=>readFile$1,readdir:()=>readdir$1,readlink:()=>readlink$1,readv:()=>readvAsync,realpath:()=>realpath$1,rename:()=>rename$1,rm:()=>rm$1,rmdir:()=>rmdir$1,stat:()=>stat$1,statfs:()=>statfsAsync,symlink:()=>symlink$1,truncate:()=>truncate$1,unlink:()=>unlink$1,utimes:()=>utimesAsync,watch:()=>watchAsync,write:()=>write$1,writeFile:()=>writeFile$1,writev:()=>writevAsync}),__name$1(mkdir$1,`mkdir`),__name$1(readFile$1,`readFile`),__name$1(mkdtemp$1,`mkdtemp`),__name$1(writeFile$1,`writeFile`),__name$1(rmdir$1,`rmdir`),__name$1(unlink$1,`unlink`),__name$1(open$2,`open`),__name$1(write$1,`write`),__name$1(stat$1,`stat`),__name$1(lstat$1,`lstat`),__name$1(readdir$1,`readdir`),__name$1(realpath$1,`realpath`),__name$1(symlink$1,`symlink`),__name$1(rm$1,`rm`),__name$1(rename$1,`rename`),__name$1(copyFile$1,`copyFile`),__name$1(access$1,`access`),__name$1(appendFile$1,`appendFile`),__name$1(readlink$1,`readlink`),__name$1(truncate$1,`truncate`),__name$1(chmod$1,`chmod`),__name$1(chown$1,`chown`),__name$1(link$1,`link`),Sl={readFile:readFile$1,mkdir:mkdir$1,mkdtemp:mkdtemp$1,realpath:realpath$1,readdir:readdir$1,writeFile:writeFile$1,rmdir:rmdir$1,unlink:unlink$1,open:open$2,write:write$1,rm:rm$1,lstat:lstat$1,symlink:symlink$1,stat:stat$1,rename:rename$1,copyFile:copyFile$1,access:access$1,appendFile:appendFile$1,readlink:readlink$1,truncate:truncate$1,chmod:chmod$1,chown:chown$1,link:link$1,cp:cpPromises,opendir:opendirAsync,glob:globAsync,watch:watchAsync,statfs:statfsAsync,utimes:utimesAsync,lutimes:lutimesAsync,lchown:lchownAsync,lchmod:lchmodAsync,fstat:fstatAsync,ftruncate:ftruncateAsync,fdatasync:fdatasyncAsync,fsync:fsyncAsync,fchmod:fchmodAsync,fchown:fchownAsync,futimes:futimesAsync,readv:readvAsync,writev:writevAsync,openAsBlob}});function withHandle(n,S,C){try{return Nl.getInstance(n,S)}catch(n){return Promise.resolve().then(()=>C(n)),null}}function parseOptsCb(n,S){return typeof n==`function`?{options:{},callback:n}:{options:n??{},callback:requireCallback(S)}}function statImpl(n,S,C,N,F){let I=normalizePath(n),H=Lr.File.new_for_path(I);H.query_info_async(ul,S,ft.PRIORITY_DEFAULT,null,(n,S)=>{try{F(null,statsFrom(H.query_info_finish(S),I,C,N?.bigint))}catch(n){F(createNodeError(n,C,I))}})}function stat(n,S,C){let{options:N,callback:F}=parseOptsCb(S,C);statImpl(n,Lr.FileQueryInfoFlags.NONE,`stat`,N,F)}function lstat(n,S,C){let{options:N,callback:F}=parseOptsCb(S,C);statImpl(n,Lr.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,`lstat`,N,F)}function readdir(n,S,C){let{options:N,callback:F}=parseOptsCb(S,C);Promise.resolve().then(()=>{try{F(null,readdirSync(n,N))}catch(S){F(createNodeError(S,`readdir`,n))}})}function realpath(n,S,C){let{callback:N}=parseOptsCb(S,C);Promise.resolve().then(()=>{try{N(null,realpathSync(n))}catch(n){N(n)}})}function symlink(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);if(typeof F!=`function`)throw TypeError(`Callback must be a function. Received `+typeof F);let I=normalizePath(S),H=normalizePath(n),W=Lr.File.new_for_path(I);W.make_symbolic_link_async(H,ft.PRIORITY_DEFAULT,null,(n,S)=>{try{W.make_symbolic_link_finish(S),F(null)}catch(n){F(createNodeError(n,`symlink`,H,I))}})}function open$1(n,...S){let C,N,F;switch(S.length){case 1:F=S[0];break;case 2:C=S[0],F=S[1];break;case 3:C=S[0],N=S[1],F=S[2];break;default:break}let I=requireCallback(F);open$2(n,C,N).then(n=>{I(null,n.fd)}).catch(n=>{I(n,-1)})}function write(n,S,...C){requireCallback(C[C.length-1]);let N=withHandle(n,`write`,n=>{let N=C[C.length-1];typeof S==`string`?N(n,0,``):N(n,0,$e.from([]))});if(!N)return;if(typeof S==`string`){let n=C.pop(),F=C[0],I=C[1];N.write(S,F,I).then(S=>{n(null,S.bytesWritten,S.buffer)}).catch(S=>{n(S,0,``)});return}let F=C[C.length-1],I=C[0],H=C[1],W=C[2];N.write(S,I,H,W).then(n=>{F(null,n.bytesWritten,n.buffer)}).catch(n=>{F(n,0,$e.from([]))})}function read$1(n,...S){let C=requireCallback(S[S.length-1]),N=withHandle(n,`read`,n=>{typeof C==`function`&&C(n,0,$e.from([]))});if(!N)return;let F,I,H,W;if(!(S.length<=1))if(typeof S[0]==`object`&&!ArrayBuffer.isView(S[0])){let n=S[0];F=n.buffer,I=n.offset,H=n.length,W=n.position}else F=S[0],I=S[1],H=S[2],W=S[3];N.read(F,I,H,W).then(n=>{C(null,n.bytesRead,n.buffer)}).catch(n=>{C(n,0,$e.from([]))})}function close$1(n,S){let done=n=>{typeof S==`function`&&S(n)},C=withHandle(n,`close`,done);C&&C.close().then(()=>done(null)).catch(n=>done(n))}function rm(n,...S){let C={},N=S[S.length-1];S.length>=2&&(C=S[0]),rm$1(n,C).then(()=>{N(null)}).catch(n=>{N(n)})}function rename(n,S,C){requireCallback(C),Promise.resolve().then(()=>{try{renameSync(n,S),C(null)}catch(n){C(n)}})}function copyFile(n,S,C,N){let F=typeof C==`function`?0:C,I=typeof C==`function`?C:requireCallback(N);Promise.resolve().then(()=>{try{copyFileSync(n,S,F),I(null)}catch(n){I(n)}})}function access(n,S,C){let N=typeof S==`function`?void 0:S,F=typeof S==`function`?S:requireCallback(C);Promise.resolve().then(()=>{try{accessSync(n,N),F(null)}catch(n){F(n)}})}function appendFile(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N),I=typeof C==`function`?void 0:C;Promise.resolve().then(()=>{try{appendFileSync(n,S,I),F(null)}catch(n){F(n)}})}function readlink(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{try{N(null,readlinkSync(n,F))}catch(n){N(n,``)}})}function truncate(n,S,C){let N=typeof S==`function`?0:S,F=typeof S==`function`?S:requireCallback(C);Promise.resolve().then(()=>{try{truncateSync(n,N),F(null)}catch(n){F(n)}})}function chmod(n,S,C){requireCallback(C),Promise.resolve().then(()=>{try{chmodSync(n,S),C(null)}catch(n){C(n)}})}function chown(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>{try{chownSync(n,S,C),N(null)}catch(n){N(n)}})}function mkdir(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{try{mkdirSync(n,F),N(null)}catch(n){N(n)}})}function mkdtemp(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{let S;try{S=mkdtempSync(n,F)}catch(n){N(n,void 0);return}N(null,S)})}function rmdir(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{try{rmdirSync(n,F),N(null)}catch(n){N(n)}})}function readFile(n,S,C){let N=typeof S==`function`?S:requireCallback(C),F=typeof S==`function`?void 0:S;Promise.resolve().then(()=>{try{let S=typeof F==`string`?{encoding:F,flag:`r`}:{encoding:F?.encoding??null,flag:F?.flag??`r`};N(null,readFileSync(n,S))}catch(n){N(n,null)}})}function writeFile(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N),I=typeof C==`function`?void 0:C;Promise.resolve().then(()=>{try{writeFileSync(n,S,I),F(null)}catch(n){F(n)}})}function link(n,S,C){requireCallback(C),Promise.resolve().then(()=>{try{linkSync(n,S),C(null)}catch(n){C(n)}})}function unlink(n,S){requireCallback(S);let C=normalizePath(n);Promise.resolve().then(()=>{ft.unlink(C),S(null)})}var wl=__esmMin(()=>{Bc(),Vc(),dl(),Pl(),fl(),Cl(),pt(),Rr(),lt(),__name$1(open$1,`open`),__name$1(read$1,`read`),__name$1(close$1,`close`)});function toPathIfFileURL(n){return normalizePath(n)}function createWriteStream(n,S){return new WriteStream$1(n,S)}var Tl,El,WriteStream$1,Dl=__esmMin(()=>{Bc(),tl(),wl(),gi(),Tl=Symbol(`kIsPerformingIO`),El=Symbol(`kIoDone`),WriteStream$1=class extends di{static{__name$1(this,`WriteStream`)}close(n,S=null){let done=S=>{typeof n==`function`&&n(S)};if(this.fd===null||!this._autoClose)this.fd=null,done(S);else{let n=this._fdFromHandle;close$1(this.fd,C=>{let N=n&&C?.code===`EBADF`?null:C;done(N||S)}),this.fd=null}}bytesWritten=0;path;pending;fd=null;flags=`w`;mode=438;pos=void 0;_autoClose=!0;_fdFromHandle=!1;[Tl]=!1;constructor(n,S={}){super(S),this.path=toPathIfFileURL(n),S.flags!==void 0&&(this.flags=S.flags),S.mode!==void 0&&(this.mode=normalizeMode(S.mode,438)),S.start!==void 0&&(this.pos=S.start),S.encoding&&this.setDefaultEncoding(S.encoding),typeof S.fd==`number`?(this.fd=S.fd,this._autoClose=S.autoClose??!0,this._fdFromHandle=S.fdFromHandle===!0):S.autoClose!==void 0&&(this._autoClose=S.autoClose),this.pending=this.fd===null}_construct(n){if(this.fd!==null){n(),this.emit(`open`,this.fd),this.emit(`ready`);return}open$1(this.path.toString(),this.flags,this.mode,(S,C)=>{if(S){n(S);return}this.fd=C,this.pending=!1,n(),this.emit(`open`,this.fd),this.emit(`ready`)})}_write(n,S,C){this[Tl]=!0,write(this.fd,n,0,n.length,this.pos??null,(n,S)=>{if(this[Tl]=!1,this.destroyed)return C(n),this.emit(El,n);if(n)return C(n);this.bytesWritten+=S,C()}),this.pos!==void 0&&(this.pos+=n.length)}_destroy(n,S){this[Tl]?this.once(El,C=>this.close(S,n||C)):this.close(S,n)}}});function createInterface$1(n,S,C,N){return typeof n==`object`&&n&&!(`read`in n&&typeof n.read==`function`)?new Interface$1(n):new Interface$1({input:n,output:S,completer:C,terminal:N})}function*emitKeys(n){for(;;){let S=yield,C=S,N=!1,F={sequence:``,name:void 0,ctrl:!1,meta:!1,shift:!1};if(S===`\x1B`&&(N=!0,C+=S=yield,S===`\x1B`&&(C+=S=yield)),N&&(S===`O`||S===`[`)){let n=S,N=0;if(S===`O`)C+=S=yield,S>=`0`&&S<=`9`&&(N=S.charCodeAt(0)-1,C+=S=yield),n+=S;else if(S===`[`){C+=S=yield,S===`[`&&(n+=S,C+=S=yield);let F=C.length-1;S>=`0`&&S<=`9`&&(C+=S=yield,S>=`0`&&S<=`9`&&(C+=S=yield,S>=`0`&&S<=`9`&&(C+=S=yield))),S===`;`&&(C+=S=yield,S>=`0`&&S<=`9`&&(C+=yield));let I=C.slice(F),H;(H=/^(?:(\d\d?)(?:;(\d))?([~^$])|(\d{3}~))$/.exec(I))?H[4]?n+=H[4]:(n+=H[1]+H[3],N=(parseInt(H[2]??`1`,10)||1)-1):(H=/^((\d;)?(\d))?([A-Za-z])$/.exec(I))?(n+=H[4],N=(parseInt(H[3]??`1`,10)||1)-1):n+=I}switch(F.ctrl=!!(N&4),F.meta=!!(N&10),F.shift=!!(N&1),F.code=n,n){case`[P`:case`OP`:case`[11~`:case`[[A`:F.name=`f1`;break;case`[Q`:case`OQ`:case`[12~`:case`[[B`:F.name=`f2`;break;case`[R`:case`OR`:case`[13~`:case`[[C`:F.name=`f3`;break;case`[S`:case`OS`:case`[14~`:case`[[D`:F.name=`f4`;break;case`[15~`:case`[[E`:F.name=`f5`;break;case`[17~`:F.name=`f6`;break;case`[18~`:F.name=`f7`;break;case`[19~`:F.name=`f8`;break;case`[20~`:F.name=`f9`;break;case`[21~`:F.name=`f10`;break;case`[23~`:F.name=`f11`;break;case`[24~`:F.name=`f12`;break;case`[200~`:F.name=`paste-start`;break;case`[201~`:F.name=`paste-end`;break;case`[A`:case`OA`:F.name=`up`;break;case`[B`:case`OB`:F.name=`down`;break;case`[C`:case`OC`:F.name=`right`;break;case`[D`:case`OD`:F.name=`left`;break;case`[E`:case`OE`:F.name=`clear`;break;case`[F`:case`OF`:F.name=`end`;break;case`[H`:case`OH`:F.name=`home`;break;case`[1~`:F.name=`home`;break;case`[2~`:F.name=`insert`;break;case`[3~`:F.name=`delete`;break;case`[4~`:F.name=`end`;break;case`[5~`:case`[[5~`:F.name=`pageup`;break;case`[6~`:case`[[6~`:F.name=`pagedown`;break;case`[7~`:F.name=`home`;break;case`[8~`:F.name=`end`;break;case`[a`:F.name=`up`,F.shift=!0;break;case`[b`:F.name=`down`,F.shift=!0;break;case`[c`:F.name=`right`,F.shift=!0;break;case`[d`:F.name=`left`,F.shift=!0;break;case`[2$`:F.name=`insert`,F.shift=!0;break;case`[3$`:F.name=`delete`,F.shift=!0;break;case`[5$`:F.name=`pageup`,F.shift=!0;break;case`[6$`:F.name=`pagedown`,F.shift=!0;break;case`[7$`:F.name=`home`,F.shift=!0;break;case`[8$`:F.name=`end`,F.shift=!0;break;case`Oa`:F.name=`up`,F.ctrl=!0;break;case`Ob`:F.name=`down`,F.ctrl=!0;break;case`Oc`:F.name=`right`,F.ctrl=!0;break;case`Od`:F.name=`left`,F.ctrl=!0;break;case`[2^`:F.name=`insert`,F.ctrl=!0;break;case`[3^`:F.name=`delete`,F.ctrl=!0;break;case`[5^`:F.name=`pageup`,F.ctrl=!0;break;case`[6^`:F.name=`pagedown`,F.ctrl=!0;break;case`[7^`:F.name=`home`,F.ctrl=!0;break;case`[8^`:F.name=`end`,F.ctrl=!0;break;case`[Z`:F.name=`tab`,F.shift=!0;break;default:F.name=`undefined`;break}}else S===`\r`?(F.name=`return`,F.meta=N):S===`
|
|
42
|
-
`?(F.name=`enter`,F.meta=N):S===` `?(F.name=`tab`,F.meta=N):S===`\b`||S===``?(F.name=`backspace`,F.meta=N):S===`\x1B`?(F.name=`escape`,F.meta=N):S===` `?(F.name=`space`,F.meta=N):!N&&S<=``?(F.name=String.fromCharCode(S.charCodeAt(0)+97-1),F.ctrl=!0):/^[0-9A-Za-z]$/.test(S)?(F.name=S.toLowerCase(),F.shift=/^[A-Z]$/.test(S),F.meta=N):N&&(F.name=S.length?void 0:`escape`,F.meta=!0);F.sequence=C,C.length!==0&&(F.name!==void 0||N)?n.emit(`keypress`,N?void 0:C,F):C.length===1&&n.emit(`keypress`,C,F)}}function emitKeypressEvents(n,S={}){let C=n;if(C[Al])return;C[Al]=new qt(`utf8`),C[jl]=emitKeys(n),C[jl].next();let N=S.escapeCodeTimeout??500,F,triggerEscape=()=>C[jl].next(``);function onData(S){if(n.listenerCount(`keypress`)>0){let I=C[Al].write(typeof S==`string`?Buffer.from(S):S);if(I){clearTimeout(F);for(let S of I)try{C[jl].next(S),S===`\x1B`&&(F=setTimeout(triggerEscape,N))}catch{C[jl]=emitKeys(n),C[jl].next()}}}else n.removeListener(`data`,onData),delete C[Al],delete C[jl]}n.on(`data`,onData)}var Ol,Interface$1,kl,Al,jl,Ml=__esmMin(()=>{Kt(),Jt(),Ol=/\r\n|\r|\n/,Interface$1=class extends Ft{static{__name$1(this,`Interface`)}terminal;line=``;cursor=0;escapeCodeTimeout;_input;_output;get input(){return this._input}get output(){return this._output}_prompt;_closed=!1;_paused=!1;history;_historySize;_crlfDelay;_lineBuffer=``;_questionCallback=null;_boundOnData=null;_boundOnEnd=null;_boundOnError=null;_boundOnKeypress=null;constructor(n,S){super();let C;if(C=n&&typeof n==`object`&&!(`read`in n&&typeof n.read==`function`)?n:{input:n,output:S},this._input=C.input||null,this._output=C.output||null,this._prompt=C.prompt||`> `,this.terminal=C.terminal??this._output!==null,this._historySize=C.historySize??30,this.history=[],this._crlfDelay=C.crlfDelay??100,this.escapeCodeTimeout=C.escapeCodeTimeout,this._input&&(this._boundOnData=n=>this._onData(n),this._boundOnEnd=()=>this._onEnd(),this._boundOnError=n=>this.emit(`error`,n),this._input.on(`data`,this._boundOnData),this._input.on(`end`,this._boundOnEnd),this._input.on(`error`,this._boundOnError),`setEncoding`in this._input&&typeof this._input.setEncoding==`function`&&this._input.setEncoding(`utf8`),this.terminal)){emitKeypressEvents(this._input,this);let n=this._input;typeof n.setRawMode==`function`&&(n.isRaw||n.setRawMode(!0)),typeof this._input.resume==`function`&&this._input.resume(),this._boundOnKeypress=(n,S)=>{S&&(S.name===`backspace`||S.name===`delete`?this.cursor>0&&(this.line=this.line.slice(0,this.cursor-1)+this.line.slice(this.cursor),this.cursor--):n&&n.length===1&&!S.ctrl&&!S.meta&&S.name!==`return`&&S.name!==`enter`&&S.name!==`escape`&&(this.line=this.line.slice(0,this.cursor)+n+this.line.slice(this.cursor),this.cursor++))},this._input.on(`keypress`,this._boundOnKeypress)}}_onData(n){if(this._closed||this._paused)return;let S=typeof n==`string`?n:n.toString(`utf8`);this._lineBuffer+=S;let C;for(;(C=Ol.exec(this._lineBuffer))!==null;){let n=this._lineBuffer.substring(0,C.index);this._lineBuffer=this._lineBuffer.substring(C.index+C[0].length),this._onLine(n)}}_onLine(n){if(n.length>0&&this._historySize>0&&(this.history.length===0||this.history[0]!==n)&&(this.history.unshift(n),this.history.length>this._historySize&&this.history.pop()),this._questionCallback){let S=this._questionCallback;this._questionCallback=null,S(n)}this.emit(`line`,n)}_onEnd(){this._lineBuffer.length>0&&(this._onLine(this._lineBuffer),this._lineBuffer=``),this.close()}setPrompt(n){this._prompt=n}getPrompt(){return this._prompt}prompt(n){if(this._closed)throw Error(`readline was closed`);this._output?.write(this._prompt)}question(n,S,C){if(this._closed)throw Error(`readline was closed`);let N=typeof S==`function`?S:C;this._questionCallback=N,this._output?.write(n)}clearLine(n,S){return this.line=``,this.cursor=0,S&&S(),!0}write(n,S){if(!this._closed){if(S){this._input&&this._input.emit(`keypress`,n??``,S);return}if(n!=null){let S=typeof n==`string`?n:n.toString(`utf8`);S&&(this.line=this.line.slice(0,this.cursor)+S+this.line.slice(this.cursor),this.cursor+=S.length),this._output?.write(n)}}}close(){if(!this._closed){if(this._closed=!0,this._input){this._boundOnData&&this._input.removeListener(`data`,this._boundOnData),this._boundOnEnd&&this._input.removeListener(`end`,this._boundOnEnd),this._boundOnError&&this._input.removeListener(`error`,this._boundOnError),this._boundOnKeypress&&this._input.removeListener(`keypress`,this._boundOnKeypress),this._boundOnData=null,this._boundOnEnd=null,this._boundOnError=null,this._boundOnKeypress=null;let n=this._input;this.terminal&&n.isRaw&&typeof n.setRawMode==`function`&&n.setRawMode(!1),typeof this._input.pause==`function`&&this._input.pause()}this.emit(`close`)}}pause(){return this._closed?this:(this._paused=!0,this._input&&`pause`in this._input&&typeof this._input.pause==`function`&&this._input.pause(),this.emit(`pause`),this)}resume(){return this._closed?this:(this._paused=!1,this._input&&`resume`in this._input&&typeof this._input.resume==`function`&&this._input.resume(),this.emit(`resume`),this)}getCursorPos(){let n=this._output?.columns??80,S=this._prompt.length+this.cursor;return{rows:Math.floor(S/n),cols:S%n}}[Symbol.asyncIterator](){let n=[],S=null,C=!1,onLine=C=>{if(S){let n=S;S=null,n({value:C,done:!1})}else n.push(C)},onClose=()=>{if(C=!0,S){let n=S;S=null,n({value:void 0,done:!0})}};return this.on(`line`,onLine),this.on(`close`,onClose),{next:()=>n.length>0?Promise.resolve({value:n.shift(),done:!1}):C?Promise.resolve({value:void 0,done:!0}):new Promise(n=>{S=n}),return:()=>(C=!0,this.removeListener(`line`,onLine),this.removeListener(`close`,onClose),Promise.resolve({value:void 0,done:!0})),[Symbol.asyncIterator](){return this}}}},kl=Symbol.dispose??Symbol.for(`Symbol.dispose`),Interface$1.prototype[kl]=function(){this.close()},__name$1(createInterface$1,`createInterface`),Al=Symbol(`keypress-decoder`),jl=Symbol(`escape-decoder`)}),Nl,Pl=__esmMin(()=>{Xc(),Bc(),Vc(),Zc(),tl(),Dl(),ll(),dl(),fl(),pt(),Rr(),lt(),Ml(),Nl=class FileHandle{options;_gFile;_pathStr;_spec;_pos=0;_closed=!1;_webStreamLocked=!1;static instances={};constructor(n){this.options=n,this.options.flags??=`r`;let S=normalizePath(n.path);this._spec=parseOpenFlags(this.options.flags),this.options.mode??=438;let C=normalizeMode(this.options.mode,438);return this.fd=openFd(S,this._spec,C),this._pathStr=S,this._gFile=Lr.File.new_for_path(S),FileHandle.instances[this.fd]=this,FileHandle.getInstance(this.fd)}_readCore(n,S,C,N){if(this._assertOpen(`read`),!this._spec.readable)throw fsError(`EBADF`,`read`,this._pathStr);if(C>n.byteLength-S){let N=RangeError(`The value of "length" is out of range. It must be <= ${n.byteLength-S}. Received ${C}`);throw N.code=`ERR_OUT_OF_RANGE`,N}let F=N!=null&&N>=0,I=isSeekableFd(this.fd,this._pathStr);if(F&&!I)throw fsError(`ESPIPE`,`read`,this._pathStr);let H=F?N:this._pos;I&&seekFd(this.fd,H);let W=readFd(this.fd,C);return W.length>0&&new Uint8Array(n.buffer,n.byteOffset+S,W.length).set(W),!F&&I&&(this._pos=H+W.length),W.length}_writeCore(n,S){if(this._assertOpen(`write`),!this._spec.writable)throw fsError(`EBADF`,`write`,this._pathStr);if(this._spec.append){let S=writeFd(this.fd,n);return this._pos=tellFd(this.fd)??sizeOfFd(this.fd,this._pathStr),S}let C=S!=null&&S>=0,N=isSeekableFd(this.fd,this._pathStr);if(C&&!N)throw fsError(`ESPIPE`,`write`,this._pathStr);let F=C?S:this._pos;N&&seekFd(this.fd,F);let I=writeFd(this.fd,n);return!C&&N&&(this._pos=F+I),I}_assertOpen(n){if(this._closed)throw fsError(`EBADF`,n,this._pathStr)}_truncateCore(n){if(this._assertOpen(`ftruncate`),!this._spec.writable)throw fsError(`EINVAL`,`ftruncate`,this._pathStr);truncateFd(this.fd,Math.max(0,n),this._pathStr)}_readToEnd(){let n=[],S=0;for(;;){let C=new Uint8Array(64*1024),N=this._readCore(C,0,C.length,null);if(N===0)break;n.push(C.subarray(0,N)),S+=N}let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}_fdTarget(){return fdPath(this.fd)??this._pathStr}fd;static getInstance(n,S=`read`){let C=n instanceof FileHandle?n.fd:n,N=FileHandle.instances[C];if(!N)throw fsError(`EBADF`,S);return N}async appendFile(n,S){await this.writeFile(n,S)}async chown(n,S){this._assertOpen(`fchown`),chownSync(normalizePath(this.options.path),n,S)}async chmod(n){this._assertOpen(`fchmod`),chmodSync(this._fdTarget(),n)}createReadStream(n){return new ReadStream$1(this.options.path,{...n,fd:this.fd})}createWriteStream(n){return new WriteStream$1(this.options.path,{...n,fd:this.fd,fdFromHandle:!0})}async datasync(){this._assertOpen(`fdatasync`),fsyncFd(this.fd)}async sync(){this._assertOpen(`fsync`),fsyncFd(this.fd)}async read(...n){let S,C,N,F;if(typeof n[0]==`object`&&!(n[0]instanceof Uint8Array)&&!(n[0]instanceof $e)){let I=n[0];S=I.buffer,C=I.offset,N=I.length,F=I.position}else S=n[0],C=n[1],N=n[2],F=n[3];let I=S,H=C??0,W=N??(I?I.byteLength-H:65536);return{bytesRead:this._readCore(S,H,W,F??null),buffer:S}}readableWebStream(){if(this._closed)throw invalidState(`The FileHandle is closed`);if(this._webStreamLocked)throw invalidState(`The FileHandle is locked`);let n=globalThis.ReadableStream;if(typeof n!=`function`)throw Error(`readableWebStream() requires a global ReadableStream. Import "node:stream/web" or "@gjsify/web-streams/register" before calling this method.`);return this._webStreamLocked=!0,new n({type:`bytes`,pull:n=>{if(this._closed){n.close(),n.byobRequest?.respond(0);return}let S=n.byobRequest?.view,C=S?new Uint8Array(S.buffer,S.byteOffset,S.byteLength):new Uint8Array(64*1024),N;try{N=this._readCore(C,0,C.length,null)}catch(S){n.error(S);return}if(N===0){n.close(),n.byobRequest?.respond(0);return}if(n.byobRequest){n.byobRequest.respond(N);return}n.enqueue(C.subarray(0,N))}})}async readFile(n){return encodeUint8Array(getEncodingFromOptions(n,`buffer`),this._readToEnd())}readLines(n){return createInterface$1({input:this.createReadStream(n),crlfDelay:1/0})}async stat(n){this._assertOpen(`fstat`);let S=Lr.File.new_for_path(this._fdTarget());return statsFrom(await new Promise((n,C)=>{S.query_info_async(ul,Lr.FileQueryInfoFlags.NONE,ft.PRIORITY_DEFAULT,null,(N,F)=>{try{n(S.query_info_finish(F))}catch(n){C(n)}})}),this._pathStr,`fstat`,n?.bigint)}async truncate(n=0){this._truncateCore(n)}async utimes(n,S){this._assertOpen(`futimes`);let{utimesSync:C}=await Promise.resolve().then(()=>(Kc(),Gc));C(normalizePath(this.options.path),n,S)}async writeFile(n,S){let C=getEncodingFromOptions(S),N;N=typeof n==`string`?$e.from(n,C||`utf8`):n,this._writeCore(N,null)}async write(n,...S){let C=null,N=null,F=null,I=null;typeof n==`string`?(C=S[0],N=S[1]):(F=S[0],I=S[1],C=S[2]),N=getEncodingFromOptions(N,typeof n==`string`?`utf8`:null);let H;H=typeof n==`string`?new TextEncoder().encode(n):n;let W=F??0,q=I??H.byteLength-W,Y=H.subarray(W,W+q);return{bytesWritten:this._writeCore(Y,C??null),buffer:n}}async writev(n,S){let C=0;for(let N of n){let n=$e.from(N.buffer,N.byteOffset,N.byteLength),F=await this.write(n,0,n.byteLength,S==null?null:S+C);C+=F.bytesWritten}return{bytesWritten:C,buffers:n}}async readv(n,S){let C=0;for(let N of n){let n=await this.read({buffer:$e.from(N.buffer,N.byteOffset,N.byteLength),position:S==null?null:S+C});if(C+=n.bytesRead,n.bytesRead<N.byteLength)break}return{bytesRead:C,buffers:n}}_flushSync(){fsyncFd(this.fd)}_closeSync(){this._teardown()}_readSync(n,S,C,N){return this._readCore(n,S,C,N)}_writeSync(n,S){return this._writeCore(n,S)}_readToEndSync(){return this._readToEnd()}_truncateSync(n){this._truncateCore(n)}_fdStatTarget(){return this._fdTarget()}_teardown(){if(this._closed)return;this._closed=!0,releaseFd(this.fd),closeFd(this.fd);let n=FileHandle;delete n.instances[this.fd]}async close(){this._teardown()}async[Symbol.asyncDispose](){await this.close()}pull(...n){throw Error('FileHandle.pull() is not implemented in @gjsify/fs yet — requires `node:stream/iter` (Node 25.9+) which @gjsify/stream has not ported. Track gjsify Open TODO "Node 25 stream/iter integration".')}writer(n){throw Error('FileHandle.writer() is not implemented in @gjsify/fs yet — requires `node:stream/iter` (Node 25.9+) which @gjsify/stream has not ported. Track gjsify Open TODO "Node 25 stream/iter integration".')}}});function getFH(n,S){return Nl.getInstance(n,S)}function fstatSync(n,S){return statSync(getFH(n,`fstat`)._fdStatTarget(),S)}function fstat(n,S,C){let N=typeof S==`function`?S:requireCallback(C);fstatAsync(n,typeof S==`function`?{}:S).then(n=>N(null,n),n=>N(n,void 0))}async function fstatAsync(n,S){return S?.bigint,fstatSync(n,S)}function ftruncateSync(n,S=0){getFH(n,`ftruncate`)._truncateSync(S)}function ftruncate(n,S,C){let N=typeof S==`function`?S:requireCallback(C);ftruncateAsync(n,typeof S==`function`?0:S).then(()=>N(null),N)}async function ftruncateAsync(n,S=0){ftruncateSync(n,S)}function fdatasyncSync(n){getFH(n,`fdatasync`)._flushSync()}function fdatasync(n,S){requireCallback(S),Promise.resolve().then(()=>fdatasyncSync(n)).then(()=>S(null),S)}async function fdatasyncAsync(n){fdatasyncSync(n)}function fsyncSync(n){getFH(n,`fsync`)._flushSync()}function fsync(n,S){requireCallback(S),Promise.resolve().then(()=>fsyncSync(n)).then(()=>S(null),S)}async function fsyncAsync(n){fsyncSync(n)}function fchmodSync(n,S){chmodSync(getFH(n,`fchmod`)._fdStatTarget(),S)}function fchmod(n,S,C){requireCallback(C),Promise.resolve().then(()=>fchmodSync(n,S)).then(()=>C(null),C)}async function fchmodAsync(n,S){fchmodSync(n,S)}function fchownSync(n,S,C){chownSync(normalizePath(getFH(n,`fchown`).options.path),S,C)}function fchown(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>fchownSync(n,S,C)).then(()=>N(null),N)}async function fchownAsync(n,S,C){fchownSync(n,S,C)}function futimesSync(n,S,C){utimesSync(normalizePath(getFH(n,`futimes`).options.path),S,C)}function futimes(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>futimesSync(n,S,C)).then(()=>N(null),N)}async function futimesAsync(n,S,C){futimesSync(n,S,C)}function closeSync(n){isStdFd(n)||getFH(n,`close`)._closeSync()}function readSync(n,S,C,N,F){let I=0;return typeof C==`object`&&C?(I=C.offset??0,N=C.length??S.byteLength-I,F=C.position??null):(I=C??0,N??=S.byteLength-I),isStdFd(n)?readStdFdSync(n,S,I,N):getFH(n,`read`)._readSync(S,I,N,F??null)}function writeSync(n,S,C,N,F){let I;if(typeof S==`string`)I=new TextEncoder().encode(S),typeof C==`number`&&(F=C);else{let n=typeof C==`number`?C:0,F=typeof N==`number`?N:S.byteLength-n;I=new Uint8Array(S.buffer,S.byteOffset+n,F)}return isStdFd(n)?writeStdFdSync(n,I):getFH(n,`write`)._writeSync(I,F??null)}function readvSync(n,S,C){let N=0;for(let F of S){let S=readSync(n,F,0,F.byteLength,C==null?null:C+N);if(N+=S,S<F.byteLength)break}return N}function readv(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);readvAsync(n,S,typeof C==`function`?null:C).then(n=>F(null,n.bytesRead,n.buffers),n=>F(n,0,S))}async function readvAsync(n,S,C){return{bytesRead:readvSync(n,S,C),buffers:S}}function writevSync(n,S,C){let N=0;for(let F of S){let S=writeSync(n,F,0,F.byteLength,C==null?null:C+N);N+=S}return N}function writev(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);writevAsync(n,S,typeof C==`function`?null:C).then(n=>F(null,n.bytesWritten,n.buffers),n=>F(n,0,S))}async function writevAsync(n,S,C){return{bytesWritten:writevSync(n,S,C),buffers:S}}function exists(n,S){requireCallback(S);try{statSync(normalizePath(n)),S(!0)}catch{S(!1)}}async function openAsBlob(n,S){let C=readFileSync(normalizePath(n));return new Blob([C],{type:S?.type??``})}var Fl=__esmMin(()=>{Bc(),Vc(),Kc(),Yc(),Pl(),fl()});function zeroedStat(){return{dev:0,ino:0,mode:0,nlink:0,uid:0,gid:0,rdev:0,size:0,blksize:0,blocks:0,atimeMs:0,mtimeMs:0,ctimeMs:0,birthtimeMs:0,atime:new Date(0),mtime:new Date(0),ctime:new Date(0),birthtime:new Date(0),isFile:()=>!1,isDirectory:()=>!1,isBlockDevice:()=>!1,isCharacterDevice:()=>!1,isSymbolicLink:()=>!1,isFIFO:()=>!1,isSocket:()=>!1}}function watchFile(n,S,C){typeof S==`function`&&(C=S,S={}),requireCallback(C,`listener`);let N=S.interval??5007,F=n.toString(),I=Il.get(F);return I||(I=new StatWatcher(F,N),I.start(),Il.set(F,I)),C&&I.addChangeListener(C),I}function unwatchFile(n,S){let C=n.toString(),N=Il.get(C);N&&(S?N.removeChangeListener(S):N.removeAllChangeListeners(),N.changeListenerCount===0&&(N.stop(),Il.delete(C)))}var StatWatcher,Il,Ll=__esmMin(()=>{Vc(),fl(),Kt(),StatWatcher=class extends Ft{_path;_interval;_timerId=null;_prev;_changeCount=0;constructor(n,S){super(),this._path=n,this._interval=S,this._prev=zeroedStat()}start(){try{this._prev=statSync(this._path)}catch{}this._timerId=setInterval(()=>{let n;try{n=statSync(this._path)}catch{n=zeroedStat()}let S=this._prev;(n.mtimeMs!==S.mtimeMs||n.size!==S.size||n.ino!==S.ino)&&(this._prev=n,this.emit(`change`,n,S))},this._interval)}stop(){this._timerId!==null&&(clearInterval(this._timerId),this._timerId=null),this.emit(`stop`)}addChangeListener(n){this._changeCount++,this.on(`change`,n)}removeChangeListener(n){this._changeCount--,this.removeListener(`change`,n)}removeAllChangeListeners(){this._changeCount=0,this.removeAllListeners(`change`)}get changeListenerCount(){return this._changeCount}},Il=new Map}),Rl=__exportAll$4({BigIntStats:()=>BigIntStats,Dir:()=>Dir,Dirent:()=>Dirent,FSWatcher:()=>FSWatcher,ReadStream:()=>ReadStream$1,StatWatcher:()=>StatWatcher,Stats:()=>Stats,WriteStream:()=>WriteStream$1,access:()=>access,accessSync:()=>accessSync,appendFile:()=>appendFile,appendFileSync:()=>appendFileSync,chmod:()=>chmod,chmodSync:()=>chmodSync,chown:()=>chown,chownSync:()=>chownSync,close:()=>close$1,closeSync:()=>closeSync,constants:()=>zl,copyFile:()=>copyFile,copyFileSync:()=>copyFileSync,cp:()=>cp,cpSync:()=>cpSync,createReadStream:()=>createReadStream,createWriteStream:()=>createWriteStream,default:()=>Bl,exists:()=>exists,existsSync:()=>existsSync,fchmod:()=>fchmod,fchmodSync:()=>fchmodSync,fchown:()=>fchown,fchownSync:()=>fchownSync,fdatasync:()=>fdatasync,fdatasyncSync:()=>fdatasyncSync,fstat:()=>fstat,fstatSync:()=>fstatSync,fsync:()=>fsync,fsyncSync:()=>fsyncSync,ftruncate:()=>ftruncate,ftruncateSync:()=>ftruncateSync,futimes:()=>futimes,futimesSync:()=>futimesSync,glob:()=>glob,globSync:()=>globSync,lchmod:()=>void 0,lchmodSync:()=>void 0,lchown:()=>lchown,lchownSync:()=>lchownSync,link:()=>link,linkSync:()=>linkSync,lstat:()=>lstat,lstatSync:()=>lstatSync,lutimes:()=>lutimes,lutimesSync:()=>lutimesSync,mkdir:()=>mkdir,mkdirSync:()=>mkdirSync,mkdtemp:()=>mkdtemp,mkdtempSync:()=>mkdtempSync,open:()=>open$1,openAsBlob:()=>openAsBlob,openSync:()=>openSync,opendir:()=>opendir,opendirSync:()=>opendirSync,promises:()=>xl,read:()=>read$1,readFile:()=>readFile,readFileSync:()=>readFileSync,readSync:()=>readSync,readdir:()=>readdir,readdirSync:()=>readdirSync,readlink:()=>readlink,readlinkSync:()=>readlinkSync,readv:()=>readv,readvSync:()=>readvSync,realpath:()=>realpath,realpathSync:()=>realpathSync,rename:()=>rename,renameSync:()=>renameSync,rm:()=>rm,rmSync:()=>rmSync,rmdir:()=>rmdir,rmdirSync:()=>rmdirSync,stat:()=>stat,statSync:()=>statSync,statfs:()=>statfs,statfsSync:()=>statfsSync,symlink:()=>symlink,symlinkSync:()=>symlinkSync,truncate:()=>truncate,truncateSync:()=>truncateSync,unlink:()=>unlink,unlinkSync:()=>unlinkSync,unwatchFile:()=>unwatchFile,utimes:()=>utimes,utimesSync:()=>utimesSync,watch:()=>watch,watchFile:()=>watchFile,write:()=>write,writeFile:()=>writeFile,writeFileSync:()=>writeFileSync,writeSync:()=>writeSync,writev:()=>writev,writevSync:()=>writevSync});function openFlagDescriptors(){let n={};for(let S of Object.keys(openFlagValues()))n[S]={enumerable:!0,configurable:!0,get:()=>openFlagValues()[S]};return n}var zl,Bl,Vl=__esmMin(()=>{Wc(),Kc(),Fl(),Zc(),tl(),Dl(),nl(),dl(),fl(),pl(),hl(),gl(),yl(),Cl(),wl(),Ll(),zl=Object.defineProperties({F_OK:0,R_OK:4,W_OK:2,X_OK:1,COPYFILE_EXCL:1,COPYFILE_FICLONE:2,COPYFILE_FICLONE_FORCE:4,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1},openFlagDescriptors()),Bl={FSWatcher,StatWatcher,Stats,BigIntStats,Dirent,Dir,constants:zl,existsSync,readdirSync,readFileSync,writeFileSync,mkdirSync,rmdirSync,unlinkSync,mkdtemp,mkdtempSync,rmSync,statSync,openSync,realpathSync,symlinkSync,lstatSync,renameSync,copyFileSync,accessSync,appendFileSync,readlinkSync,linkSync,truncateSync,chmodSync,chownSync,cpSync,opendirSync,globSync,glob,watch,watchFile,unwatchFile,statfsSync,statfs,utimesSync,utimes,lutimesSync,lutimes,lchownSync,lchown,lchmodSync:void 0,lchmod:void 0,fstatSync,fstat,ftruncateSync,ftruncate,fdatasyncSync,fdatasync,fsyncSync,fsync,fchmodSync,fchmod,fchownSync,fchown,futimesSync,futimes,closeSync,readSync,writeSync,readvSync,readv,writevSync,writev,exists,openAsBlob,createReadStream,ReadStream:ReadStream$1,createWriteStream,WriteStream:WriteStream$1,promises:xl,open:open$1,close:close$1,read:read$1,write,rm,realpath,readdir,symlink,lstat,stat,rename,copyFile,cp,access,appendFile,readlink,truncate,chmod,chown,mkdir,rmdir,readFile,writeFile,unlink,link,opendir}}),Hl,Ul,Wl,Gl,Kl,ql,Jl=__esmMin(()=>{
|
|
42
|
+
`?(F.name=`enter`,F.meta=N):S===` `?(F.name=`tab`,F.meta=N):S===`\b`||S===``?(F.name=`backspace`,F.meta=N):S===`\x1B`?(F.name=`escape`,F.meta=N):S===` `?(F.name=`space`,F.meta=N):!N&&S<=``?(F.name=String.fromCharCode(S.charCodeAt(0)+97-1),F.ctrl=!0):/^[0-9A-Za-z]$/.test(S)?(F.name=S.toLowerCase(),F.shift=/^[A-Z]$/.test(S),F.meta=N):N&&(F.name=S.length?void 0:`escape`,F.meta=!0);F.sequence=C,C.length!==0&&(F.name!==void 0||N)?n.emit(`keypress`,N?void 0:C,F):C.length===1&&n.emit(`keypress`,C,F)}}function emitKeypressEvents(n,S={}){let C=n;if(C[Al])return;C[Al]=new qt(`utf8`),C[jl]=emitKeys(n),C[jl].next();let N=S.escapeCodeTimeout??500,F,triggerEscape=()=>C[jl].next(``);function onData(S){if(n.listenerCount(`keypress`)>0){let I=C[Al].write(typeof S==`string`?Buffer.from(S):S);if(I){clearTimeout(F);for(let S of I)try{C[jl].next(S),S===`\x1B`&&(F=setTimeout(triggerEscape,N))}catch{C[jl]=emitKeys(n),C[jl].next()}}}else n.removeListener(`data`,onData),delete C[Al],delete C[jl]}n.on(`data`,onData)}var Ol,Interface$1,kl,Al,jl,Ml=__esmMin(()=>{Kt(),Jt(),Ol=/\r\n|\r|\n/,Interface$1=class extends Ft{static{__name$1(this,`Interface`)}terminal;line=``;cursor=0;escapeCodeTimeout;_input;_output;get input(){return this._input}get output(){return this._output}_prompt;_closed=!1;_paused=!1;history;_historySize;_crlfDelay;_lineBuffer=``;_questionCallback=null;_boundOnData=null;_boundOnEnd=null;_boundOnError=null;_boundOnKeypress=null;constructor(n,S){super();let C;if(C=n&&typeof n==`object`&&!(`read`in n&&typeof n.read==`function`)?n:{input:n,output:S},this._input=C.input||null,this._output=C.output||null,this._prompt=C.prompt||`> `,this.terminal=C.terminal??this._output!==null,this._historySize=C.historySize??30,this.history=[],this._crlfDelay=C.crlfDelay??100,this.escapeCodeTimeout=C.escapeCodeTimeout,this._input&&(this._boundOnData=n=>this._onData(n),this._boundOnEnd=()=>this._onEnd(),this._boundOnError=n=>this.emit(`error`,n),this._input.on(`data`,this._boundOnData),this._input.on(`end`,this._boundOnEnd),this._input.on(`error`,this._boundOnError),`setEncoding`in this._input&&typeof this._input.setEncoding==`function`&&this._input.setEncoding(`utf8`),this.terminal)){emitKeypressEvents(this._input,this);let n=this._input;typeof n.setRawMode==`function`&&(n.isRaw||n.setRawMode(!0)),typeof this._input.resume==`function`&&this._input.resume(),this._boundOnKeypress=(n,S)=>{S&&(S.name===`backspace`||S.name===`delete`?this.cursor>0&&(this.line=this.line.slice(0,this.cursor-1)+this.line.slice(this.cursor),this.cursor--):n&&n.length===1&&!S.ctrl&&!S.meta&&S.name!==`return`&&S.name!==`enter`&&S.name!==`escape`&&(this.line=this.line.slice(0,this.cursor)+n+this.line.slice(this.cursor),this.cursor++))},this._input.on(`keypress`,this._boundOnKeypress)}}_onData(n){if(this._closed||this._paused)return;let S=typeof n==`string`?n:n.toString(`utf8`);this._lineBuffer+=S;let C;for(;(C=Ol.exec(this._lineBuffer))!==null;){let n=this._lineBuffer.substring(0,C.index);this._lineBuffer=this._lineBuffer.substring(C.index+C[0].length),this._onLine(n)}}_onLine(n){if(n.length>0&&this._historySize>0&&(this.history.length===0||this.history[0]!==n)&&(this.history.unshift(n),this.history.length>this._historySize&&this.history.pop()),this._questionCallback){let S=this._questionCallback;this._questionCallback=null,S(n)}this.emit(`line`,n)}_onEnd(){this._lineBuffer.length>0&&(this._onLine(this._lineBuffer),this._lineBuffer=``),this.close()}setPrompt(n){this._prompt=n}getPrompt(){return this._prompt}prompt(n){if(this._closed)throw Error(`readline was closed`);this._output?.write(this._prompt)}question(n,S,C){if(this._closed)throw Error(`readline was closed`);let N=typeof S==`function`?S:C;this._questionCallback=N,this._output?.write(n)}clearLine(n,S){return this.line=``,this.cursor=0,S&&S(),!0}write(n,S){if(!this._closed){if(S){this._input&&this._input.emit(`keypress`,n??``,S);return}if(n!=null){let S=typeof n==`string`?n:n.toString(`utf8`);S&&(this.line=this.line.slice(0,this.cursor)+S+this.line.slice(this.cursor),this.cursor+=S.length),this._output?.write(n)}}}close(){if(!this._closed){if(this._closed=!0,this._input){this._boundOnData&&this._input.removeListener(`data`,this._boundOnData),this._boundOnEnd&&this._input.removeListener(`end`,this._boundOnEnd),this._boundOnError&&this._input.removeListener(`error`,this._boundOnError),this._boundOnKeypress&&this._input.removeListener(`keypress`,this._boundOnKeypress),this._boundOnData=null,this._boundOnEnd=null,this._boundOnError=null,this._boundOnKeypress=null;let n=this._input;this.terminal&&n.isRaw&&typeof n.setRawMode==`function`&&n.setRawMode(!1),typeof this._input.pause==`function`&&this._input.pause()}this.emit(`close`)}}pause(){return this._closed?this:(this._paused=!0,this._input&&`pause`in this._input&&typeof this._input.pause==`function`&&this._input.pause(),this.emit(`pause`),this)}resume(){return this._closed?this:(this._paused=!1,this._input&&`resume`in this._input&&typeof this._input.resume==`function`&&this._input.resume(),this.emit(`resume`),this)}getCursorPos(){let n=this._output?.columns??80,S=this._prompt.length+this.cursor;return{rows:Math.floor(S/n),cols:S%n}}[Symbol.asyncIterator](){let n=[],S=null,C=!1,onLine=C=>{if(S){let n=S;S=null,n({value:C,done:!1})}else n.push(C)},onClose=()=>{if(C=!0,S){let n=S;S=null,n({value:void 0,done:!0})}};return this.on(`line`,onLine),this.on(`close`,onClose),{next:()=>n.length>0?Promise.resolve({value:n.shift(),done:!1}):C?Promise.resolve({value:void 0,done:!0}):new Promise(n=>{S=n}),return:()=>(C=!0,this.removeListener(`line`,onLine),this.removeListener(`close`,onClose),Promise.resolve({value:void 0,done:!0})),[Symbol.asyncIterator](){return this}}}},kl=Symbol.dispose??Symbol.for(`Symbol.dispose`),Interface$1.prototype[kl]=function(){this.close()},__name$1(createInterface$1,`createInterface`),Al=Symbol(`keypress-decoder`),jl=Symbol(`escape-decoder`)}),Nl,Pl=__esmMin(()=>{Xc(),Bc(),Vc(),Zc(),tl(),Dl(),ll(),dl(),fl(),pt(),Rr(),lt(),Ml(),Nl=class FileHandle{options;_gFile;_pathStr;_spec;_pos=0;_closed=!1;_webStreamLocked=!1;static instances={};constructor(n){this.options=n,this.options.flags??=`r`;let S=normalizePath(n.path);this._spec=parseOpenFlags(this.options.flags),this.options.mode??=438;let C=normalizeMode(this.options.mode,438);return this.fd=openFd(S,this._spec,C),this._pathStr=S,this._gFile=Lr.File.new_for_path(S),FileHandle.instances[this.fd]=this,FileHandle.getInstance(this.fd)}_readCore(n,S,C,N){if(this._assertOpen(`read`),!this._spec.readable)throw fsError(`EBADF`,`read`,this._pathStr);if(C>n.byteLength-S){let N=RangeError(`The value of "length" is out of range. It must be <= ${n.byteLength-S}. Received ${C}`);throw N.code=`ERR_OUT_OF_RANGE`,N}let F=N!=null&&N>=0,I=isSeekableFd(this.fd,this._pathStr);if(F&&!I)throw fsError(`ESPIPE`,`read`,this._pathStr);let H=F?N:this._pos;I&&seekFd(this.fd,H);let W=readFd(this.fd,C);return W.length>0&&new Uint8Array(n.buffer,n.byteOffset+S,W.length).set(W),!F&&I&&(this._pos=H+W.length),W.length}_writeCore(n,S){if(this._assertOpen(`write`),!this._spec.writable)throw fsError(`EBADF`,`write`,this._pathStr);if(this._spec.append){let S=writeFd(this.fd,n);return this._pos=tellFd(this.fd)??sizeOfFd(this.fd,this._pathStr),S}let C=S!=null&&S>=0,N=isSeekableFd(this.fd,this._pathStr);if(C&&!N)throw fsError(`ESPIPE`,`write`,this._pathStr);let F=C?S:this._pos;N&&seekFd(this.fd,F);let I=writeFd(this.fd,n);return!C&&N&&(this._pos=F+I),I}_assertOpen(n){if(this._closed)throw fsError(`EBADF`,n,this._pathStr)}_truncateCore(n){if(this._assertOpen(`ftruncate`),!this._spec.writable)throw fsError(`EINVAL`,`ftruncate`,this._pathStr);truncateFd(this.fd,Math.max(0,n),this._pathStr)}_readToEnd(){let n=[],S=0;for(;;){let C=new Uint8Array(64*1024),N=this._readCore(C,0,C.length,null);if(N===0)break;n.push(C.subarray(0,N)),S+=N}let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.length;return C}_fdTarget(){return fdPath(this.fd)??this._pathStr}fd;static getInstance(n,S=`read`){let C=n instanceof FileHandle?n.fd:n,N=FileHandle.instances[C];if(!N)throw fsError(`EBADF`,S);return N}async appendFile(n,S){await this.writeFile(n,S)}async chown(n,S){this._assertOpen(`fchown`),chownSync(normalizePath(this.options.path),n,S)}async chmod(n){this._assertOpen(`fchmod`),chmodSync(this._fdTarget(),n)}createReadStream(n){return new ReadStream$1(this.options.path,{...n,fd:this.fd})}createWriteStream(n){return new WriteStream$1(this.options.path,{...n,fd:this.fd,fdFromHandle:!0})}async datasync(){this._assertOpen(`fdatasync`),fsyncFd(this.fd)}async sync(){this._assertOpen(`fsync`),fsyncFd(this.fd)}async read(...n){let S,C,N,F;if(typeof n[0]==`object`&&!(n[0]instanceof Uint8Array)&&!(n[0]instanceof $e)){let I=n[0];S=I.buffer,C=I.offset,N=I.length,F=I.position}else S=n[0],C=n[1],N=n[2],F=n[3];let I=S,H=C??0,W=N??(I?I.byteLength-H:65536);return{bytesRead:this._readCore(S,H,W,F??null),buffer:S}}readableWebStream(){if(this._closed)throw invalidState(`The FileHandle is closed`);if(this._webStreamLocked)throw invalidState(`The FileHandle is locked`);let n=globalThis.ReadableStream;if(typeof n!=`function`)throw Error(`readableWebStream() requires a global ReadableStream. Import "node:stream/web" or "@gjsify/web-streams/register" before calling this method.`);return this._webStreamLocked=!0,new n({type:`bytes`,pull:n=>{if(this._closed){n.close(),n.byobRequest?.respond(0);return}let S=n.byobRequest?.view,C=S?new Uint8Array(S.buffer,S.byteOffset,S.byteLength):new Uint8Array(64*1024),N;try{N=this._readCore(C,0,C.length,null)}catch(S){n.error(S);return}if(N===0){n.close(),n.byobRequest?.respond(0);return}if(n.byobRequest){n.byobRequest.respond(N);return}n.enqueue(C.subarray(0,N))}})}async readFile(n){return encodeUint8Array(getEncodingFromOptions(n,`buffer`),this._readToEnd())}readLines(n){return createInterface$1({input:this.createReadStream(n),crlfDelay:1/0})}async stat(n){this._assertOpen(`fstat`);let S=Lr.File.new_for_path(this._fdTarget());return statsFrom(await new Promise((n,C)=>{S.query_info_async(ul,Lr.FileQueryInfoFlags.NONE,ft.PRIORITY_DEFAULT,null,(N,F)=>{try{n(S.query_info_finish(F))}catch(n){C(n)}})}),this._pathStr,`fstat`,n?.bigint)}async truncate(n=0){this._truncateCore(n)}async utimes(n,S){this._assertOpen(`futimes`);let{utimesSync:C}=await Promise.resolve().then(()=>(Kc(),Gc));C(normalizePath(this.options.path),n,S)}async writeFile(n,S){let C=getEncodingFromOptions(S),N;N=typeof n==`string`?$e.from(n,C||`utf8`):n,this._writeCore(N,null)}async write(n,...S){let C=null,N=null,F=null,I=null;typeof n==`string`?(C=S[0],N=S[1]):(F=S[0],I=S[1],C=S[2]),N=getEncodingFromOptions(N,typeof n==`string`?`utf8`:null);let H;H=typeof n==`string`?new TextEncoder().encode(n):n;let W=F??0,q=I??H.byteLength-W,Y=H.subarray(W,W+q);return{bytesWritten:this._writeCore(Y,C??null),buffer:n}}async writev(n,S){let C=0;for(let N of n){let n=$e.from(N.buffer,N.byteOffset,N.byteLength),F=await this.write(n,0,n.byteLength,S==null?null:S+C);C+=F.bytesWritten}return{bytesWritten:C,buffers:n}}async readv(n,S){let C=0;for(let N of n){let n=await this.read({buffer:$e.from(N.buffer,N.byteOffset,N.byteLength),position:S==null?null:S+C});if(C+=n.bytesRead,n.bytesRead<N.byteLength)break}return{bytesRead:C,buffers:n}}_flushSync(){fsyncFd(this.fd)}_closeSync(){this._teardown()}_readSync(n,S,C,N){return this._readCore(n,S,C,N)}_writeSync(n,S){return this._writeCore(n,S)}_readToEndSync(){return this._readToEnd()}_truncateSync(n){this._truncateCore(n)}_fdStatTarget(){return this._fdTarget()}_teardown(){if(this._closed)return;this._closed=!0,releaseFd(this.fd),closeFd(this.fd);let n=FileHandle;delete n.instances[this.fd]}async close(){this._teardown()}async[Symbol.asyncDispose](){await this.close()}pull(...n){throw Error('FileHandle.pull() is not implemented in @gjsify/fs yet — requires `node:stream/iter` (Node 25.9+) which @gjsify/stream has not ported. Track gjsify Open TODO "Node 25 stream/iter integration".')}writer(n){throw Error('FileHandle.writer() is not implemented in @gjsify/fs yet — requires `node:stream/iter` (Node 25.9+) which @gjsify/stream has not ported. Track gjsify Open TODO "Node 25 stream/iter integration".')}}});function getFH(n,S){return Nl.getInstance(n,S)}function fstatSync(n,S){return statSync(getFH(n,`fstat`)._fdStatTarget(),S)}function fstat(n,S,C){let N=typeof S==`function`?S:requireCallback(C);fstatAsync(n,typeof S==`function`?{}:S).then(n=>N(null,n),n=>N(n,void 0))}async function fstatAsync(n,S){return S?.bigint,fstatSync(n,S)}function ftruncateSync(n,S=0){getFH(n,`ftruncate`)._truncateSync(S)}function ftruncate(n,S,C){let N=typeof S==`function`?S:requireCallback(C);ftruncateAsync(n,typeof S==`function`?0:S).then(()=>N(null),N)}async function ftruncateAsync(n,S=0){ftruncateSync(n,S)}function fdatasyncSync(n){getFH(n,`fdatasync`)._flushSync()}function fdatasync(n,S){requireCallback(S),Promise.resolve().then(()=>fdatasyncSync(n)).then(()=>S(null),S)}async function fdatasyncAsync(n){fdatasyncSync(n)}function fsyncSync(n){getFH(n,`fsync`)._flushSync()}function fsync(n,S){requireCallback(S),Promise.resolve().then(()=>fsyncSync(n)).then(()=>S(null),S)}async function fsyncAsync(n){fsyncSync(n)}function fchmodSync(n,S){chmodSync(getFH(n,`fchmod`)._fdStatTarget(),S)}function fchmod(n,S,C){requireCallback(C),Promise.resolve().then(()=>fchmodSync(n,S)).then(()=>C(null),C)}async function fchmodAsync(n,S){fchmodSync(n,S)}function fchownSync(n,S,C){chownSync(normalizePath(getFH(n,`fchown`).options.path),S,C)}function fchown(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>fchownSync(n,S,C)).then(()=>N(null),N)}async function fchownAsync(n,S,C){fchownSync(n,S,C)}function futimesSync(n,S,C){utimesSync(normalizePath(getFH(n,`futimes`).options.path),S,C)}function futimes(n,S,C,N){requireCallback(N),Promise.resolve().then(()=>futimesSync(n,S,C)).then(()=>N(null),N)}async function futimesAsync(n,S,C){futimesSync(n,S,C)}function closeSync(n){isStdFd(n)||getFH(n,`close`)._closeSync()}function readSync(n,S,C,N,F){let I=0;return typeof C==`object`&&C?(I=C.offset??0,N=C.length??S.byteLength-I,F=C.position??null):(I=C??0,N??=S.byteLength-I),isStdFd(n)?readStdFdSync(n,S,I,N):getFH(n,`read`)._readSync(S,I,N,F??null)}function writeSync(n,S,C,N,F){let I;if(typeof S==`string`)I=new TextEncoder().encode(S),typeof C==`number`&&(F=C);else{let n=typeof C==`number`?C:0,F=typeof N==`number`?N:S.byteLength-n;I=new Uint8Array(S.buffer,S.byteOffset+n,F)}return isStdFd(n)?writeStdFdSync(n,I):getFH(n,`write`)._writeSync(I,F??null)}function readvSync(n,S,C){let N=0;for(let F of S){let S=readSync(n,F,0,F.byteLength,C==null?null:C+N);if(N+=S,S<F.byteLength)break}return N}function readv(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);readvAsync(n,S,typeof C==`function`?null:C).then(n=>F(null,n.bytesRead,n.buffers),n=>F(n,0,S))}async function readvAsync(n,S,C){return{bytesRead:readvSync(n,S,C),buffers:S}}function writevSync(n,S,C){let N=0;for(let F of S){let S=writeSync(n,F,0,F.byteLength,C==null?null:C+N);N+=S}return N}function writev(n,S,C,N){let F=typeof C==`function`?C:requireCallback(N);writevAsync(n,S,typeof C==`function`?null:C).then(n=>F(null,n.bytesWritten,n.buffers),n=>F(n,0,S))}async function writevAsync(n,S,C){return{bytesWritten:writevSync(n,S,C),buffers:S}}function exists(n,S){requireCallback(S);let C;try{statSync(normalizePath(n)),C=!0}catch{C=!1}Promise.resolve().then(()=>S(C))}async function openAsBlob(n,S){let C=readFileSync(normalizePath(n));return new Blob([C],{type:S?.type??``})}var Fl=__esmMin(()=>{Bc(),Vc(),Kc(),Yc(),Pl(),fl(),Object.defineProperty(exists,Symbol.for(`nodejs.util.promisify.custom`),{value:n=>new Promise(S=>exists(n,S))})});function zeroedStat(){return{dev:0,ino:0,mode:0,nlink:0,uid:0,gid:0,rdev:0,size:0,blksize:0,blocks:0,atimeMs:0,mtimeMs:0,ctimeMs:0,birthtimeMs:0,atime:new Date(0),mtime:new Date(0),ctime:new Date(0),birthtime:new Date(0),isFile:()=>!1,isDirectory:()=>!1,isBlockDevice:()=>!1,isCharacterDevice:()=>!1,isSymbolicLink:()=>!1,isFIFO:()=>!1,isSocket:()=>!1}}function watchFile(n,S,C){typeof S==`function`&&(C=S,S={}),requireCallback(C,`listener`);let N=S.interval??5007,F=n.toString(),I=Il.get(F);return I||(I=new StatWatcher(F,N),I.start(),Il.set(F,I)),C&&I.addChangeListener(C),I}function unwatchFile(n,S){let C=n.toString(),N=Il.get(C);N&&(S?N.removeChangeListener(S):N.removeAllChangeListeners(),N.changeListenerCount===0&&(N.stop(),Il.delete(C)))}var StatWatcher,Il,Ll=__esmMin(()=>{Vc(),fl(),Kt(),StatWatcher=class extends Ft{_path;_interval;_timerId=null;_prev;_changeCount=0;constructor(n,S){super(),this._path=n,this._interval=S,this._prev=zeroedStat()}start(){try{this._prev=statSync(this._path)}catch{}this._timerId=setInterval(()=>{let n;try{n=statSync(this._path)}catch{n=zeroedStat()}let S=this._prev;(n.mtimeMs!==S.mtimeMs||n.size!==S.size||n.ino!==S.ino)&&(this._prev=n,this.emit(`change`,n,S))},this._interval)}stop(){this._timerId!==null&&(clearInterval(this._timerId),this._timerId=null),this.emit(`stop`)}addChangeListener(n){this._changeCount++,this.on(`change`,n)}removeChangeListener(n){this._changeCount--,this.removeListener(`change`,n)}removeAllChangeListeners(){this._changeCount=0,this.removeAllListeners(`change`)}get changeListenerCount(){return this._changeCount}},Il=new Map}),Rl=__exportAll$4({BigIntStats:()=>BigIntStats,Dir:()=>Dir,Dirent:()=>Dirent,FSWatcher:()=>FSWatcher,ReadStream:()=>ReadStream$1,StatWatcher:()=>StatWatcher,Stats:()=>Stats,WriteStream:()=>WriteStream$1,access:()=>access,accessSync:()=>accessSync,appendFile:()=>appendFile,appendFileSync:()=>appendFileSync,chmod:()=>chmod,chmodSync:()=>chmodSync,chown:()=>chown,chownSync:()=>chownSync,close:()=>close$1,closeSync:()=>closeSync,constants:()=>zl,copyFile:()=>copyFile,copyFileSync:()=>copyFileSync,cp:()=>cp,cpSync:()=>cpSync,createReadStream:()=>createReadStream,createWriteStream:()=>createWriteStream,default:()=>Bl,exists:()=>exists,existsSync:()=>existsSync,fchmod:()=>fchmod,fchmodSync:()=>fchmodSync,fchown:()=>fchown,fchownSync:()=>fchownSync,fdatasync:()=>fdatasync,fdatasyncSync:()=>fdatasyncSync,fstat:()=>fstat,fstatSync:()=>fstatSync,fsync:()=>fsync,fsyncSync:()=>fsyncSync,ftruncate:()=>ftruncate,ftruncateSync:()=>ftruncateSync,futimes:()=>futimes,futimesSync:()=>futimesSync,glob:()=>glob,globSync:()=>globSync,lchmod:()=>void 0,lchmodSync:()=>void 0,lchown:()=>lchown,lchownSync:()=>lchownSync,link:()=>link,linkSync:()=>linkSync,lstat:()=>lstat,lstatSync:()=>lstatSync,lutimes:()=>lutimes,lutimesSync:()=>lutimesSync,mkdir:()=>mkdir,mkdirSync:()=>mkdirSync,mkdtemp:()=>mkdtemp,mkdtempSync:()=>mkdtempSync,open:()=>open$1,openAsBlob:()=>openAsBlob,openSync:()=>openSync,opendir:()=>opendir,opendirSync:()=>opendirSync,promises:()=>xl,read:()=>read$1,readFile:()=>readFile,readFileSync:()=>readFileSync,readSync:()=>readSync,readdir:()=>readdir,readdirSync:()=>readdirSync,readlink:()=>readlink,readlinkSync:()=>readlinkSync,readv:()=>readv,readvSync:()=>readvSync,realpath:()=>realpath,realpathSync:()=>realpathSync,rename:()=>rename,renameSync:()=>renameSync,rm:()=>rm,rmSync:()=>rmSync,rmdir:()=>rmdir,rmdirSync:()=>rmdirSync,stat:()=>stat,statSync:()=>statSync,statfs:()=>statfs,statfsSync:()=>statfsSync,symlink:()=>symlink,symlinkSync:()=>symlinkSync,truncate:()=>truncate,truncateSync:()=>truncateSync,unlink:()=>unlink,unlinkSync:()=>unlinkSync,unwatchFile:()=>unwatchFile,utimes:()=>utimes,utimesSync:()=>utimesSync,watch:()=>watch,watchFile:()=>watchFile,write:()=>write,writeFile:()=>writeFile,writeFileSync:()=>writeFileSync,writeSync:()=>writeSync,writev:()=>writev,writevSync:()=>writevSync});function openFlagDescriptors(){let n={};for(let S of Object.keys(openFlagValues()))n[S]={enumerable:!0,configurable:!0,get:()=>openFlagValues()[S]};return n}var zl,Bl,Vl=__esmMin(()=>{Wc(),Kc(),Fl(),Zc(),tl(),Dl(),nl(),dl(),fl(),pl(),hl(),gl(),yl(),Cl(),wl(),Ll(),zl=Object.defineProperties({F_OK:0,R_OK:4,W_OK:2,X_OK:1,COPYFILE_EXCL:1,COPYFILE_FICLONE:2,COPYFILE_FICLONE_FORCE:4,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1},openFlagDescriptors()),Bl={FSWatcher,StatWatcher,Stats,BigIntStats,Dirent,Dir,constants:zl,existsSync,readdirSync,readFileSync,writeFileSync,mkdirSync,rmdirSync,unlinkSync,mkdtemp,mkdtempSync,rmSync,statSync,openSync,realpathSync,symlinkSync,lstatSync,renameSync,copyFileSync,accessSync,appendFileSync,readlinkSync,linkSync,truncateSync,chmodSync,chownSync,cpSync,opendirSync,globSync,glob,watch,watchFile,unwatchFile,statfsSync,statfs,utimesSync,utimes,lutimesSync,lutimes,lchownSync,lchown,lchmodSync:void 0,lchmod:void 0,fstatSync,fstat,ftruncateSync,ftruncate,fdatasyncSync,fdatasync,fsyncSync,fsync,fchmodSync,fchmod,fchownSync,fchown,futimesSync,futimes,closeSync,readSync,writeSync,readvSync,readv,writevSync,writev,exists,openAsBlob,createReadStream,ReadStream:ReadStream$1,createWriteStream,WriteStream:WriteStream$1,promises:xl,open:open$1,close:close$1,read:read$1,write,rm,realpath,readdir,symlink,lstat,stat,rename,copyFile,cp,access,appendFile,readlink,truncate,chmod,chown,mkdir,rmdir,readFile,writeFile,unlink,link,opendir}}),Hl,Ul,Wl,Gl,Kl,ql,Jl=__esmMin(()=>{
|
|
43
43
|
/**
|
|
44
44
|
* @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
|
|
45
45
|
*
|
|
@@ -119,7 +119,7 @@ fi
|
|
|
119
119
|
`)}`:``;S.fail(F(`Missing required argument: %s`,`Missing required arguments: %s`,Object.keys(N).length,Object.keys(N).join(`, `)+C))}},I.unknownArguments=function unknownArguments(C,N,H,W,q=!0){let Y=n.getInternalMethods().getCommandInstance().getCommands(),X=[],Z=n.getInternalMethods().getContext();if(Object.keys(C).forEach(S=>{!bd.includes(S)&&!Object.prototype.hasOwnProperty.call(H,S)&&!Object.prototype.hasOwnProperty.call(n.getInternalMethods().getParseContext(),S)&&!I.isValidAndSomeAliasIsNotNew(S,N)&&X.push(S)}),q&&(Z.commands.length>0||Y.length>0||W)&&C._.slice(Z.commands.length).forEach(n=>{Y.includes(``+n)||X.push(``+n)}),q){let S=n.getDemandedCommands()._?.max||0,N=Z.commands.length+S;N<C._.length&&C._.slice(N).forEach(n=>{n=String(n),!Z.commands.includes(n)&&!X.includes(n)&&X.push(n)})}X.length&&S.fail(F(`Unknown argument: %s`,`Unknown arguments: %s`,X.length,X.map(n=>n.trim()?n:`"${n}"`).join(`, `)))},I.unknownCommands=function unknownCommands(C){let N=n.getInternalMethods().getCommandInstance().getCommands(),I=[],H=n.getInternalMethods().getContext();return(H.commands.length>0||N.length>0)&&C._.slice(H.commands.length).forEach(n=>{N.includes(``+n)||I.push(``+n)}),I.length>0?(S.fail(F(`Unknown command: %s`,`Unknown commands: %s`,I.length,I.join(`, `))),!0):!1},I.isValidAndSomeAliasIsNotNew=function isValidAndSomeAliasIsNotNew(S,C){if(!Object.prototype.hasOwnProperty.call(C,S))return!1;let N=n.parsed.newAliases;return[S,...C[S]].some(n=>!Object.prototype.hasOwnProperty.call(N,n)||!N[S])},I.limitedChoices=function limitedChoices(C){let F=n.getOptions(),I={};if(!Object.keys(F.choices).length)return;Object.keys(C).forEach(n=>{bd.indexOf(n)===-1&&Object.prototype.hasOwnProperty.call(F.choices,n)&&[].concat(C[n]).forEach(S=>{F.choices[n].indexOf(S)===-1&&S!==void 0&&(I[n]=(I[n]||[]).concat(S))})});let H=Object.keys(I);if(!H.length)return;let W=N(`Invalid values:`);H.forEach(n=>{W+=`\n ${N(`Argument: %s, Given: %s, Choices: %s`,n,S.stringifiedValues(I[n]),S.stringifiedValues(F.choices[n]))}`}),S.fail(W)};let H={};I.implies=function implies(S,N){argsert(`<string|object> [array|number|string]`,[S,N],arguments.length),typeof S==`object`?Object.keys(S).forEach(n=>{I.implies(n,S[n])}):(n.global(S),H[S]||(H[S]=[]),Array.isArray(N)?N.forEach(n=>I.implies(S,n)):(assertNotStrictEqual(N,void 0,C),H[S].push(N)))},I.getImplied=function getImplied(){return H};function keyExists(n,S){let C=Number(S);return S=isNaN(C)?S:C,typeof S==`number`?S=n._.length>=S:S.match(/^--no-.+/)?(S=S.match(/^--no-(.+)/)[1],S=!Object.prototype.hasOwnProperty.call(n,S)):S=Object.prototype.hasOwnProperty.call(n,S),S}I.implications=function implications(n){let C=[];if(Object.keys(H).forEach(S=>{let N=S;(H[S]||[]).forEach(S=>{let F=N,I=S;F=keyExists(n,F),S=keyExists(n,S),F&&!S&&C.push(` ${N} -> ${I}`)})}),C.length){let n=`${N(`Implications failed:`)}\n`;C.forEach(S=>{n+=S}),S.fail(n)}};let W={};I.conflicts=function conflicts(S,C){argsert(`<string|object> [array|string]`,[S,C],arguments.length),typeof S==`object`?Object.keys(S).forEach(n=>{I.conflicts(n,S[n])}):(n.global(S),W[S]||(W[S]=[]),Array.isArray(C)?C.forEach(n=>I.conflicts(S,n)):W[S].push(C))},I.getConflicting=()=>W,I.conflicting=function conflictingFn(F){Object.keys(F).forEach(n=>{W[n]&&W[n].forEach(C=>{C&&F[n]!==void 0&&F[C]!==void 0&&S.fail(N(`Arguments %s and %s are mutually exclusive`,n,C))})}),n.getInternalMethods().getParserConfiguration()[`strip-dashed`]&&Object.keys(W).forEach(n=>{W[n].forEach(I=>{I&&F[C.Parser.camelCase(n)]!==void 0&&F[C.Parser.camelCase(I)]!==void 0&&S.fail(N(`Arguments %s and %s are mutually exclusive`,n,I))})})},I.recommendCommands=function recommendCommands(n,C){C=C.sort((n,S)=>S.length-n.length);let F=null,I=1/0;for(let S=0,N;(N=C[S])!==void 0;S++){let S=levenshtein(n,N);S<=3&&S<I&&(I=S,F=N)}F&&S.fail(N(`Did you mean %s?`,F))},I.reset=function reset(n){return H=objFilter(H,S=>!n[S]),W=objFilter(W,S=>!n[S]),I};let q=[];return I.freeze=function freeze(){q.push({implied:H,conflicting:W})},I.unfreeze=function unfreeze(){let n=q.pop();assertNotStrictEqual(n,void 0,C),{implied:H,conflicting:W}=n},I}var bd,xd=__esmMin(()=>{sd(),rd(),yd(),fd(),bd=[`$0`,`--`,`_`]});function YargsFactory(n){return(S=[],C=n.process.cwd(),N)=>{let F=new YargsInstance(S,C,N,n);return Object.defineProperty(F,"argv",{get:()=>F.parse(),enumerable:!0}),F.help(),F.version(),F}}function isYargsInstance(n){return!!n&&typeof n.getInternalMethods==`function`}var __classPrivateFieldSet,__classPrivateFieldGet,Sd,Cd,wd,Td,Ed,Dd,Od,kd,Ad,jd,Md,Nd,Pd,Fd,Id,Ld,Rd,zd,Bd,Vd,Hd,Ud,Wd,Gd,Kd,qd,Jd,Yd,Xd,Zd,Qd,$d,ef,tf,nf,rf,af,of,sf,cf,lf,uf,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,YargsInstance,Vf=__esmMin(()=>{ye(),dd(),rd(),rs(),md(),sd(),vd(),xd(),fd(),os(),cd(),id(),ld(),pd(),__classPrivateFieldSet=function(n,S,C,N,F){if(N===`m`)throw TypeError(`Private method is not writable`);if(N===`a`&&!F)throw TypeError(`Private accessor was defined without a setter`);if(typeof S==`function`?n!==S||!F:!S.has(n))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return N===`a`?F.call(n,C):F?F.value=C:S.set(n,C),C},__classPrivateFieldGet=function(n,S,C,N){if(C===`a`&&!N)throw TypeError(`Private accessor was defined without a getter`);if(typeof S==`function`?n!==S||!N:!S.has(n))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return C===`m`?N:C===`a`?N.call(n):N?N.value:S.get(n)},rf=Symbol(`copyDoubleDash`),af=Symbol(`copyDoubleDash`),of=Symbol(`deleteFromParserHintObject`),sf=Symbol(`emitWarning`),cf=Symbol(`freeze`),lf=Symbol(`getDollarZero`),uf=Symbol(`getParserConfiguration`),df=Symbol(`getUsageConfiguration`),ff=Symbol(`guessLocale`),pf=Symbol(`guessVersion`),mf=Symbol(`parsePositionalNumbers`),hf=Symbol(`pkgUp`),gf=Symbol(`populateParserHintArray`),_f=Symbol(`populateParserHintSingleValueDictionary`),vf=Symbol(`populateParserHintArrayDictionary`),yf=Symbol(`populateParserHintDictionary`),bf=Symbol(`sanitizeKey`),xf=Symbol(`setKey`),Sf=Symbol(`unfreeze`),Cf=Symbol(`validateAsync`),wf=Symbol(`getCommandInstance`),Tf=Symbol(`getContext`),Ef=Symbol(`getHasOutput`),Df=Symbol(`getLoggerInstance`),Of=Symbol(`getParseContext`),kf=Symbol(`getUsageInstance`),Af=Symbol(`getValidationInstance`),jf=Symbol(`hasParseCallback`),Mf=Symbol(`isGlobalContext`),Nf=Symbol(`postProcess`),Pf=Symbol(`rebase`),Ff=Symbol(`reset`),If=Symbol(`runYargsParserAndExecuteCommands`),Lf=Symbol(`runValidation`),Rf=Symbol(`setHasOutput`),zf=Symbol(`kTrackManuallySetKeys`),Bf=`en_US`,YargsInstance=class{constructor(n=[],S,C,N){this.customScriptName=!1,this.parsed=!1,Sd.set(this,void 0),Cd.set(this,void 0),wd.set(this,{commands:[],fullCommands:[]}),Td.set(this,null),Ed.set(this,null),Dd.set(this,`show-hidden`),Od.set(this,null),kd.set(this,!0),Ad.set(this,{}),jd.set(this,!0),Md.set(this,[]),Nd.set(this,void 0),Pd.set(this,{}),Fd.set(this,!1),Id.set(this,null),Ld.set(this,!0),Rd.set(this,void 0),zd.set(this,``),Bd.set(this,void 0),Vd.set(this,void 0),Hd.set(this,{}),Ud.set(this,null),Wd.set(this,null),Gd.set(this,{}),Kd.set(this,{}),qd.set(this,void 0),Jd.set(this,!1),Yd.set(this,void 0),Xd.set(this,!1),Zd.set(this,!1),Qd.set(this,!1),$d.set(this,void 0),ef.set(this,{}),tf.set(this,null),nf.set(this,void 0),__classPrivateFieldSet(this,Yd,N,`f`),__classPrivateFieldSet(this,qd,n,`f`),__classPrivateFieldSet(this,Cd,S,`f`),__classPrivateFieldSet(this,Vd,C,`f`),__classPrivateFieldSet(this,Nd,new GlobalMiddleware(this),`f`),this.$0=this[lf](),this[Ff](),__classPrivateFieldSet(this,Sd,__classPrivateFieldGet(this,Sd,`f`),`f`),__classPrivateFieldSet(this,$d,__classPrivateFieldGet(this,$d,`f`),`f`),__classPrivateFieldSet(this,nf,__classPrivateFieldGet(this,nf,`f`),`f`),__classPrivateFieldSet(this,Bd,__classPrivateFieldGet(this,Bd,`f`),`f`),__classPrivateFieldGet(this,Bd,`f`).showHiddenOpt=__classPrivateFieldGet(this,Dd,`f`),__classPrivateFieldSet(this,Rd,this[af](),`f`),__classPrivateFieldGet(this,Yd,`f`).y18n.setLocale(Bf)}addHelpOpt(n,S){return argsert(`[string|boolean] [string]`,[n,S],arguments.length),__classPrivateFieldGet(this,Id,`f`)&&(this[of](__classPrivateFieldGet(this,Id,`f`)),__classPrivateFieldSet(this,Id,null,`f`)),n===!1&&S===void 0?this:(__classPrivateFieldSet(this,Id,typeof n==`string`?n:`help`,`f`),this.boolean(__classPrivateFieldGet(this,Id,`f`)),this.describe(__classPrivateFieldGet(this,Id,`f`),S||__classPrivateFieldGet(this,$d,`f`).deferY18nLookup(`Show help`)),this)}help(n,S){return this.addHelpOpt(n,S)}addShowHiddenOpt(n,S){if(argsert(`[string|boolean] [string]`,[n,S],arguments.length),n===!1&&S===void 0)return this;let C=typeof n==`string`?n:__classPrivateFieldGet(this,Dd,`f`);return this.boolean(C),this.describe(C,S||__classPrivateFieldGet(this,$d,`f`).deferY18nLookup(`Show hidden options`)),__classPrivateFieldGet(this,Bd,`f`).showHiddenOpt=C,this}showHidden(n,S){return this.addShowHiddenOpt(n,S)}alias(n,S){return argsert(`<object|string|array> [string|array]`,[n,S],arguments.length),this[vf](this.alias.bind(this),`alias`,n,S),this}array(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`array`,n),this[zf](n),this}boolean(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`boolean`,n),this[zf](n),this}check(n,S){return argsert(`<function> [boolean]`,[n,S],arguments.length),this.middleware((S,C)=>maybeAsyncResult(()=>n(S,C.getOptions()),C=>(C?(typeof C==`string`||C instanceof Error)&&__classPrivateFieldGet(this,$d,`f`).fail(C.toString(),C):__classPrivateFieldGet(this,$d,`f`).fail(__classPrivateFieldGet(this,Yd,`f`).y18n.__(`Argument check failed: %s`,n.toString())),S),n=>(__classPrivateFieldGet(this,$d,`f`).fail(n.message?n.message:n.toString(),n),S)),!1,S),this}choices(n,S){return argsert(`<object|string|array> [string|array]`,[n,S],arguments.length),this[vf](this.choices.bind(this),`choices`,n,S),this}coerce(n,S){if(argsert(`<object|string|array> [function]`,[n,S],arguments.length),Array.isArray(n)){if(!S)throw new ns(`coerce callback must be provided`);for(let C of n)this.coerce(C,S);return this}else if(typeof n==`object`){for(let S of Object.keys(n))this.coerce(S,n[S]);return this}if(!S)throw new ns(`coerce callback must be provided`);let C=n;return __classPrivateFieldGet(this,Bd,`f`).key[C]=!0,__classPrivateFieldGet(this,Nd,`f`).addCoerceMiddleware((n,N)=>{let F=N.getAliases()[C]??[],I=[C,...F].filter(S=>Object.prototype.hasOwnProperty.call(n,S));return I.length===0?n:maybeAsyncResult(()=>S(n[I[0]]),S=>(I.forEach(C=>{n[C]=S}),n),n=>{throw new ns(n.message)})},C),this}conflicts(n,S){return argsert(`<string|object> [string|array]`,[n,S],arguments.length),__classPrivateFieldGet(this,nf,`f`).conflicts(n,S),this}config(n=`config`,S,C){return argsert(`[object|string] [string|function] [function]`,[n,S,C],arguments.length),typeof n==`object`&&!Array.isArray(n)?(n=applyExtends(n,__classPrivateFieldGet(this,Cd,`f`),this[uf]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Yd,`f`)),__classPrivateFieldGet(this,Bd,`f`).configObjects=(__classPrivateFieldGet(this,Bd,`f`).configObjects||[]).concat(n),this):(typeof S==`function`&&(C=S,S=void 0),this.describe(n,S||__classPrivateFieldGet(this,$d,`f`).deferY18nLookup(`Path to JSON config file`)),(Array.isArray(n)?n:[n]).forEach(n=>{__classPrivateFieldGet(this,Bd,`f`).config[n]=C||!0}),this)}completion(n,S,C){return argsert(`[string] [string|boolean|function] [function]`,[n,S,C],arguments.length),typeof S==`function`&&(C=S,S=void 0),__classPrivateFieldSet(this,Ed,n||__classPrivateFieldGet(this,Ed,`f`)||`completion`,`f`),!S&&S!==!1&&(S=`generate completion script`),this.command(__classPrivateFieldGet(this,Ed,`f`),S),C&&__classPrivateFieldGet(this,Td,`f`).registerFunction(C),this}command(n,S,C,N,F,I){return argsert(`<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]`,[n,S,C,N,F,I],arguments.length),__classPrivateFieldGet(this,Sd,`f`).addHandler(n,S,C,N,F,I),this}commands(n,S,C,N,F,I){return this.command(n,S,C,N,F,I)}commandDir(n,S){argsert(`<string> [object]`,[n,S],arguments.length);let C=__classPrivateFieldGet(this,Vd,`f`)||__classPrivateFieldGet(this,Yd,`f`).require;return __classPrivateFieldGet(this,Sd,`f`).addDirectory(n,C,__classPrivateFieldGet(this,Yd,`f`).getCallerFile(),S),this}count(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`count`,n),this[zf](n),this}default(n,S,C){return argsert(`<object|string|array> [*] [string]`,[n,S,C],arguments.length),C&&(assertSingleKey(n,__classPrivateFieldGet(this,Yd,`f`)),__classPrivateFieldGet(this,Bd,`f`).defaultDescription[n]=C),typeof S==`function`&&(assertSingleKey(n,__classPrivateFieldGet(this,Yd,`f`)),__classPrivateFieldGet(this,Bd,`f`).defaultDescription[n]||(__classPrivateFieldGet(this,Bd,`f`).defaultDescription[n]=__classPrivateFieldGet(this,$d,`f`).functionDescription(S)),S=S.call()),this[_f](this.default.bind(this),`default`,n,S),this}defaults(n,S,C){return this.default(n,S,C)}demandCommand(n=1,S,C,N){return argsert(`[number] [number|string] [string|null|undefined] [string|null|undefined]`,[n,S,C,N],arguments.length),typeof S!=`number`&&(C=S,S=1/0),this.global(`_`,!1),__classPrivateFieldGet(this,Bd,`f`).demandedCommands._={min:n,max:S,minMsg:C,maxMsg:N},this}demand(n,S,C){return Array.isArray(S)?(S.forEach(n=>{assertNotStrictEqual(C,!0,__classPrivateFieldGet(this,Yd,`f`)),this.demandOption(n,C)}),S=1/0):typeof S!=`number`&&(C=S,S=1/0),typeof n==`number`?(assertNotStrictEqual(C,!0,__classPrivateFieldGet(this,Yd,`f`)),this.demandCommand(n,S,C,C)):Array.isArray(n)?n.forEach(n=>{assertNotStrictEqual(C,!0,__classPrivateFieldGet(this,Yd,`f`)),this.demandOption(n,C)}):typeof C==`string`?this.demandOption(n,C):(C===!0||C===void 0)&&this.demandOption(n),this}demandOption(n,S){return argsert(`<object|string|array> [string]`,[n,S],arguments.length),this[_f](this.demandOption.bind(this),`demandedOptions`,n,S),this}deprecateOption(n,S){return argsert(`<string> [string|boolean]`,[n,S],arguments.length),__classPrivateFieldGet(this,Bd,`f`).deprecatedOptions[n]=S,this}describe(n,S){return argsert(`<object|string|array> [string]`,[n,S],arguments.length),this[xf](n,!0),__classPrivateFieldGet(this,$d,`f`).describe(n,S),this}detectLocale(n){return argsert(`<boolean>`,[n],arguments.length),__classPrivateFieldSet(this,kd,n,`f`),this}env(n){return argsert(`[string|boolean]`,[n],arguments.length),n===!1?delete __classPrivateFieldGet(this,Bd,`f`).envPrefix:__classPrivateFieldGet(this,Bd,`f`).envPrefix=n||``,this}epilogue(n){return argsert(`<string>`,[n],arguments.length),__classPrivateFieldGet(this,$d,`f`).epilog(n),this}epilog(n){return this.epilogue(n)}example(n,S){return argsert(`<string|array> [string]`,[n,S],arguments.length),Array.isArray(n)?n.forEach(n=>this.example(...n)):__classPrivateFieldGet(this,$d,`f`).example(n,S),this}exit(n,S){__classPrivateFieldSet(this,Fd,!0,`f`),__classPrivateFieldSet(this,Od,S,`f`),__classPrivateFieldGet(this,jd,`f`)&&__classPrivateFieldGet(this,Yd,`f`).process.exit(n)}exitProcess(n=!0){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,jd,n,`f`),this}fail(n){if(argsert(`<function|boolean>`,[n],arguments.length),typeof n==`boolean`&&n!==!1)throw new ns(`Invalid first argument. Expected function or boolean 'false'`);return __classPrivateFieldGet(this,$d,`f`).failFn(n),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(n,S){return argsert(`<array> [function]`,[n,S],arguments.length),S?__classPrivateFieldGet(this,Td,`f`).getCompletion(n,S):new Promise((S,C)=>{__classPrivateFieldGet(this,Td,`f`).getCompletion(n,(n,N)=>{n?C(n):S(N)})})}getDemandedOptions(){return argsert([],0),__classPrivateFieldGet(this,Bd,`f`).demandedOptions}getDemandedCommands(){return argsert([],0),__classPrivateFieldGet(this,Bd,`f`).demandedCommands}getDeprecatedOptions(){return argsert([],0),__classPrivateFieldGet(this,Bd,`f`).deprecatedOptions}getDetectLocale(){return __classPrivateFieldGet(this,kd,`f`)}getExitProcess(){return __classPrivateFieldGet(this,jd,`f`)}getGroups(){return Object.assign({},__classPrivateFieldGet(this,Pd,`f`),__classPrivateFieldGet(this,Kd,`f`))}getHelp(){if(__classPrivateFieldSet(this,Fd,!0,`f`),!__classPrivateFieldGet(this,$d,`f`).hasCachedHelpMessage()){if(!this.parsed){let n=this[If](__classPrivateFieldGet(this,qd,`f`),void 0,void 0,0,!0);if(isPromise(n))return n.then(()=>__classPrivateFieldGet(this,$d,`f`).help())}let n=__classPrivateFieldGet(this,Sd,`f`).runDefaultBuilderOn(this);if(isPromise(n))return n.then(()=>__classPrivateFieldGet(this,$d,`f`).help())}return Promise.resolve(__classPrivateFieldGet(this,$d,`f`).help())}getOptions(){return __classPrivateFieldGet(this,Bd,`f`)}getStrict(){return __classPrivateFieldGet(this,Xd,`f`)}getStrictCommands(){return __classPrivateFieldGet(this,Zd,`f`)}getStrictOptions(){return __classPrivateFieldGet(this,Qd,`f`)}global(n,S){return argsert(`<string|array> [boolean]`,[n,S],arguments.length),n=[].concat(n),S===!1?n.forEach(n=>{__classPrivateFieldGet(this,Bd,`f`).local.includes(n)||__classPrivateFieldGet(this,Bd,`f`).local.push(n)}):__classPrivateFieldGet(this,Bd,`f`).local=__classPrivateFieldGet(this,Bd,`f`).local.filter(S=>n.indexOf(S)===-1),this}group(n,S){argsert(`<string|array> <string>`,[n,S],arguments.length);let C=__classPrivateFieldGet(this,Kd,`f`)[S]||__classPrivateFieldGet(this,Pd,`f`)[S];__classPrivateFieldGet(this,Kd,`f`)[S]&&delete __classPrivateFieldGet(this,Kd,`f`)[S];let N={};return __classPrivateFieldGet(this,Pd,`f`)[S]=(C||[]).concat(n).filter(n=>N[n]?!1:N[n]=!0),this}hide(n){return argsert(`<string>`,[n],arguments.length),__classPrivateFieldGet(this,Bd,`f`).hiddenOptions.push(n),this}implies(n,S){return argsert(`<string|object> [number|string|array]`,[n,S],arguments.length),__classPrivateFieldGet(this,nf,`f`).implies(n,S),this}locale(n){return argsert(`[string]`,[n],arguments.length),n===void 0?(this[ff](),__classPrivateFieldGet(this,Yd,`f`).y18n.getLocale()):(__classPrivateFieldSet(this,kd,!1,`f`),__classPrivateFieldGet(this,Yd,`f`).y18n.setLocale(n),this)}middleware(n,S,C){return __classPrivateFieldGet(this,Nd,`f`).addMiddleware(n,!!S,C)}nargs(n,S){return argsert(`<string|object|array> [number]`,[n,S],arguments.length),this[_f](this.nargs.bind(this),`narg`,n,S),this}normalize(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`normalize`,n),this}number(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`number`,n),this[zf](n),this}option(n,S){if(argsert(`<string|object> [object]`,[n,S],arguments.length),typeof n==`object`)Object.keys(n).forEach(S=>{this.options(S,n[S])});else{typeof S!=`object`&&(S={}),this[zf](n),__classPrivateFieldGet(this,tf,`f`)&&(n===`version`||S?.alias===`version`)&&this[sf]([`"version" is a reserved word.`,`Please do one of the following:`,'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)",`- Use a different option key`,`https://yargs.js.org/docs/#api-reference-version`].join(`
|
|
120
120
|
`),void 0,`versionWarning`),__classPrivateFieldGet(this,Bd,`f`).key[n]=!0,S.alias&&this.alias(n,S.alias);let C=S.deprecate||S.deprecated;C&&this.deprecateOption(n,C);let N=S.demand||S.required||S.require;N&&this.demand(n,N),S.demandOption&&this.demandOption(n,typeof S.demandOption==`string`?S.demandOption:void 0),S.conflicts&&this.conflicts(n,S.conflicts),`default`in S&&this.default(n,S.default),S.implies!==void 0&&this.implies(n,S.implies),S.nargs!==void 0&&this.nargs(n,S.nargs),S.config&&this.config(n,S.configParser),S.normalize&&this.normalize(n),S.choices&&this.choices(n,S.choices),S.coerce&&this.coerce(n,S.coerce),S.group&&this.group(n,S.group),(S.boolean||S.type===`boolean`)&&(this.boolean(n),S.alias&&this.boolean(S.alias)),(S.array||S.type===`array`)&&(this.array(n),S.alias&&this.array(S.alias)),(S.number||S.type===`number`)&&(this.number(n),S.alias&&this.number(S.alias)),(S.string||S.type===`string`)&&(this.string(n),S.alias&&this.string(S.alias)),(S.count||S.type===`count`)&&this.count(n),typeof S.global==`boolean`&&this.global(n,S.global),S.defaultDescription&&(__classPrivateFieldGet(this,Bd,`f`).defaultDescription[n]=S.defaultDescription),S.skipValidation&&this.skipValidation(n);let F=S.describe||S.description||S.desc,I=__classPrivateFieldGet(this,$d,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(I,n)||typeof F==`string`)&&this.describe(n,F),S.hidden&&this.hide(n),S.requiresArg&&this.requiresArg(n)}return this}options(n,S){return this.option(n,S)}parse(n,S,C){argsert(`[string|array] [function|boolean|object] [function]`,[n,S,C],arguments.length),this[cf](),n===void 0&&(n=__classPrivateFieldGet(this,qd,`f`)),typeof S==`object`&&(__classPrivateFieldSet(this,Wd,S,`f`),S=C),typeof S==`function`&&(__classPrivateFieldSet(this,Ud,S,`f`),S=!1),S||__classPrivateFieldSet(this,qd,n,`f`),__classPrivateFieldGet(this,Ud,`f`)&&__classPrivateFieldSet(this,jd,!1,`f`);let N=this[If](n,!!S),F=this.parsed;return __classPrivateFieldGet(this,Td,`f`).setParsed(this.parsed),isPromise(N)?N.then(n=>(__classPrivateFieldGet(this,Ud,`f`)&&__classPrivateFieldGet(this,Ud,`f`).call(this,__classPrivateFieldGet(this,Od,`f`),n,__classPrivateFieldGet(this,zd,`f`)),n)).catch(n=>{throw __classPrivateFieldGet(this,Ud,`f`)&&__classPrivateFieldGet(this,Ud,`f`)(n,this.parsed.argv,__classPrivateFieldGet(this,zd,`f`)),n}).finally(()=>{this[Sf](),this.parsed=F}):(__classPrivateFieldGet(this,Ud,`f`)&&__classPrivateFieldGet(this,Ud,`f`).call(this,__classPrivateFieldGet(this,Od,`f`),N,__classPrivateFieldGet(this,zd,`f`)),this[Sf](),this.parsed=F,N)}parseAsync(n,S,C){let N=this.parse(n,S,C);return isPromise(N)?N:Promise.resolve(N)}parseSync(n,S,C){let N=this.parse(n,S,C);if(isPromise(N))throw new ns(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return N}parserConfiguration(n){return argsert(`<object>`,[n],arguments.length),__classPrivateFieldSet(this,Hd,n,`f`),this}pkgConf(n,S){argsert(`<string> [string]`,[n,S],arguments.length);let C=null,N=this[hf](S||__classPrivateFieldGet(this,Cd,`f`));return N[n]&&typeof N[n]==`object`&&(C=applyExtends(N[n],S||__classPrivateFieldGet(this,Cd,`f`),this[uf]()[`deep-merge-config`]||!1,__classPrivateFieldGet(this,Yd,`f`)),__classPrivateFieldGet(this,Bd,`f`).configObjects=(__classPrivateFieldGet(this,Bd,`f`).configObjects||[]).concat(C)),this}positional(n,S){argsert(`<string> <object>`,[n,S],arguments.length);let C=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];S=objFilter(S,(n,S)=>n===`type`&&![`string`,`number`,`boolean`].includes(S)?!1:C.includes(n));let N=__classPrivateFieldGet(this,wd,`f`).fullCommands[__classPrivateFieldGet(this,wd,`f`).fullCommands.length-1],F=N?__classPrivateFieldGet(this,Sd,`f`).cmdToParseOptions(N):{array:[],alias:{},default:{},demand:{}};return objectKeys(F).forEach(C=>{let N=F[C];Array.isArray(N)?N.indexOf(n)!==-1&&(S[C]=!0):N[n]&&!(C in S)&&(S[C]=N[n])}),this.group(n,__classPrivateFieldGet(this,$d,`f`).getPositionalGroupName()),this.option(n,S)}recommendCommands(n=!0){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,Jd,n,`f`),this}required(n,S,C){return this.demand(n,S,C)}require(n,S,C){return this.demand(n,S,C)}requiresArg(n){return argsert(`<array|string|object> [number]`,[n],arguments.length),typeof n==`string`&&__classPrivateFieldGet(this,Bd,`f`).narg[n]||this[_f](this.requiresArg.bind(this),`narg`,n,NaN),this}showCompletionScript(n,S){return argsert(`[string] [string]`,[n,S],arguments.length),n||=this.$0,__classPrivateFieldGet(this,Rd,`f`).log(__classPrivateFieldGet(this,Td,`f`).generateCompletionScript(n,S||__classPrivateFieldGet(this,Ed,`f`)||`completion`)),this}showHelp(n){if(argsert(`[string|function]`,[n],arguments.length),__classPrivateFieldSet(this,Fd,!0,`f`),!__classPrivateFieldGet(this,$d,`f`).hasCachedHelpMessage()){if(!this.parsed){let S=this[If](__classPrivateFieldGet(this,qd,`f`),void 0,void 0,0,!0);if(isPromise(S))return S.then(()=>{__classPrivateFieldGet(this,$d,`f`).showHelp(n)}),this}let S=__classPrivateFieldGet(this,Sd,`f`).runDefaultBuilderOn(this);if(isPromise(S))return S.then(()=>{__classPrivateFieldGet(this,$d,`f`).showHelp(n)}),this}return __classPrivateFieldGet(this,$d,`f`).showHelp(n),this}scriptName(n){return this.customScriptName=!0,this.$0=n,this}showHelpOnFail(n,S){return argsert(`[boolean|string] [string]`,[n,S],arguments.length),__classPrivateFieldGet(this,$d,`f`).showHelpOnFail(n,S),this}showVersion(n){return argsert(`[string|function]`,[n],arguments.length),__classPrivateFieldGet(this,$d,`f`).showVersion(n),this}skipValidation(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`skipValidation`,n),this}strict(n){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,Xd,n!==!1,`f`),this}strictCommands(n){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,Zd,n!==!1,`f`),this}strictOptions(n){return argsert(`[boolean]`,[n],arguments.length),__classPrivateFieldSet(this,Qd,n!==!1,`f`),this}string(n){return argsert(`<array|string>`,[n],arguments.length),this[gf](`string`,n),this[zf](n),this}terminalWidth(){return argsert([],0),__classPrivateFieldGet(this,Yd,`f`).process.stdColumns}updateLocale(n){return this.updateStrings(n)}updateStrings(n){return argsert(`<object>`,[n],arguments.length),__classPrivateFieldSet(this,kd,!1,`f`),__classPrivateFieldGet(this,Yd,`f`).y18n.updateLocale(n),this}usage(n,S,C,N){if(argsert(`<string|null|undefined> [string|boolean] [function|object] [function]`,[n,S,C,N],arguments.length),S!==void 0){if(assertNotStrictEqual(n,null,__classPrivateFieldGet(this,Yd,`f`)),(n||``).match(/^\$0( |$)/))return this.command(n,S,C,N);throw new ns(`.usage() description must start with $0 if being used as alias for .command()`)}else return __classPrivateFieldGet(this,$d,`f`).usage(n),this}usageConfiguration(n){return argsert(`<object>`,[n],arguments.length),__classPrivateFieldSet(this,ef,n,`f`),this}version(n,S,C){let N=`version`;if(argsert(`[boolean|string] [string] [string]`,[n,S,C],arguments.length),__classPrivateFieldGet(this,tf,`f`)&&(this[of](__classPrivateFieldGet(this,tf,`f`)),__classPrivateFieldGet(this,$d,`f`).version(void 0),__classPrivateFieldSet(this,tf,null,`f`)),arguments.length===0)C=this[pf](),n=N;else if(arguments.length===1){if(n===!1)return this;C=n,n=N}else arguments.length===2&&(C=S,S=void 0);return __classPrivateFieldSet(this,tf,typeof n==`string`?n:N,`f`),S||=__classPrivateFieldGet(this,$d,`f`).deferY18nLookup(`Show version number`),__classPrivateFieldGet(this,$d,`f`).version(C||void 0),this.boolean(__classPrivateFieldGet(this,tf,`f`)),this.describe(__classPrivateFieldGet(this,tf,`f`),S),this}wrap(n){return argsert(`<number|null|undefined>`,[n],arguments.length),__classPrivateFieldGet(this,$d,`f`).wrap(n),this}[(Sd=new WeakMap,Cd=new WeakMap,wd=new WeakMap,Td=new WeakMap,Ed=new WeakMap,Dd=new WeakMap,Od=new WeakMap,kd=new WeakMap,Ad=new WeakMap,jd=new WeakMap,Md=new WeakMap,Nd=new WeakMap,Pd=new WeakMap,Fd=new WeakMap,Id=new WeakMap,Ld=new WeakMap,Rd=new WeakMap,zd=new WeakMap,Bd=new WeakMap,Vd=new WeakMap,Hd=new WeakMap,Ud=new WeakMap,Wd=new WeakMap,Gd=new WeakMap,Kd=new WeakMap,qd=new WeakMap,Jd=new WeakMap,Yd=new WeakMap,Xd=new WeakMap,Zd=new WeakMap,Qd=new WeakMap,$d=new WeakMap,ef=new WeakMap,tf=new WeakMap,nf=new WeakMap,rf)](n){if(!n._||!n[`--`])return n;n._.push.apply(n._,n[`--`]);try{delete n[`--`]}catch{}return n}[af](){return{log:(...n)=>{this[jf]()||ve.log(...n),__classPrivateFieldSet(this,Fd,!0,`f`),__classPrivateFieldGet(this,zd,`f`).length&&__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+`
|
|
121
121
|
`,`f`),__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+n.join(` `),`f`)},error:(...n)=>{this[jf]()||ve.error(...n),__classPrivateFieldSet(this,Fd,!0,`f`),__classPrivateFieldGet(this,zd,`f`).length&&__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+`
|
|
122
|
-
`,`f`),__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+n.join(` `),`f`)}}}[of](n){objectKeys(__classPrivateFieldGet(this,Bd,`f`)).forEach(S=>{if((n=>n===`configObjects`)(S))return;let C=__classPrivateFieldGet(this,Bd,`f`)[S];Array.isArray(C)?C.includes(n)&&C.splice(C.indexOf(n),1):typeof C==`object`&&delete C[n]}),delete __classPrivateFieldGet(this,$d,`f`).getDescriptions()[n]}[sf](n,S,C){__classPrivateFieldGet(this,Ad,`f`)[C]||(__classPrivateFieldGet(this,Yd,`f`).process.emitWarning(n,S),__classPrivateFieldGet(this,Ad,`f`)[C]=!0)}[cf](){__classPrivateFieldGet(this,Md,`f`).push({options:__classPrivateFieldGet(this,Bd,`f`),configObjects:__classPrivateFieldGet(this,Bd,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,jd,`f`),groups:__classPrivateFieldGet(this,Pd,`f`),strict:__classPrivateFieldGet(this,Xd,`f`),strictCommands:__classPrivateFieldGet(this,Zd,`f`),strictOptions:__classPrivateFieldGet(this,Qd,`f`),completionCommand:__classPrivateFieldGet(this,Ed,`f`),output:__classPrivateFieldGet(this,zd,`f`),exitError:__classPrivateFieldGet(this,Od,`f`),hasOutput:__classPrivateFieldGet(this,Fd,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Ud,`f`),parseContext:__classPrivateFieldGet(this,Wd,`f`)}),__classPrivateFieldGet(this,$d,`f`).freeze(),__classPrivateFieldGet(this,nf,`f`).freeze(),__classPrivateFieldGet(this,Sd,`f`).freeze(),__classPrivateFieldGet(this,Nd,`f`).freeze()}[lf](){let n=``,S;return S=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Yd,`f`).process.argv()[0])?__classPrivateFieldGet(this,Yd,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Yd,`f`).process.argv().slice(0,1),n=S.map(n=>{let S=this[Pf](__classPrivateFieldGet(this,Cd,`f`),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&S.length<n.length?S:n}).join(` `).trim(),__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Yd,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`)&&(n=__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Yd,`f`).path.dirname(__classPrivateFieldGet(this,Yd,`f`).process.execPath())}/`,``)),n}[uf](){return __classPrivateFieldGet(this,Hd,`f`)}[df](){return __classPrivateFieldGet(this,ef,`f`)}[ff](){if(!__classPrivateFieldGet(this,kd,`f`))return;let n=__classPrivateFieldGet(this,Yd,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(n.replace(/[.:].*/,``))}[pf](){return this[hf]().version||`unknown`}[mf](n){let S=n[`--`]?n[`--`]:n._;for(let n=0,C;(C=S[n])!==void 0;n++)__classPrivateFieldGet(this,Yd,`f`).Parser.looksLikeNumber(C)&&Number.isSafeInteger(Math.floor(parseFloat(`${C}`)))&&(S[n]=Number(C));return n}[hf](n){let S=n||`*`;if(__classPrivateFieldGet(this,Gd,`f`)[S])return __classPrivateFieldGet(this,Gd,`f`)[S];let C={};try{let S=n||__classPrivateFieldGet(this,Yd,`f`).mainFilename;__classPrivateFieldGet(this,Yd,`f`).path.extname(S)&&(S=__classPrivateFieldGet(this,Yd,`f`).path.dirname(S));let N=__classPrivateFieldGet(this,Yd,`f`).findUp(S,(n,S)=>{if(S.includes(`package.json`))return`package.json`});assertNotStrictEqual(N,void 0,__classPrivateFieldGet(this,Yd,`f`)),C=JSON.parse(__classPrivateFieldGet(this,Yd,`f`).readFileSync(N,`utf8`))}catch{}return __classPrivateFieldGet(this,Gd,`f`)[S]=C||{},__classPrivateFieldGet(this,Gd,`f`)[S]}[gf](n,S){S=[].concat(S),S.forEach(S=>{S=this[bf](S),__classPrivateFieldGet(this,Bd,`f`)[n].push(S)})}[_f](n,S,C,N){this[yf](n,S,C,N,(n,S,C)=>{__classPrivateFieldGet(this,Bd,`f`)[n][S]=C})}[vf](n,S,C,N){this[yf](n,S,C,N,(n,S,C)=>{__classPrivateFieldGet(this,Bd,`f`)[n][S]=(__classPrivateFieldGet(this,Bd,`f`)[n][S]||[]).concat(C)})}[yf](n,S,C,N,F){if(Array.isArray(C))C.forEach(S=>{n(S,N)});else if((n=>typeof n==`object`)(C))for(let S of objectKeys(C))n(S,C[S]);else F(S,this[bf](C),N)}[bf](n){return n===`__proto__`?`___proto___`:n}[xf](n,S){return this[_f](this[xf].bind(this),`key`,n,S),this}[Sf](){var n,S,C,N,F,I,H,W,q,Y,X,Z;let te=__classPrivateFieldGet(this,Md,`f`).pop();assertNotStrictEqual(te,void 0,__classPrivateFieldGet(this,Yd,`f`));let ne;n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,Z=this,{options:{set value(S){__classPrivateFieldSet(n,Bd,S,`f`)}}.value,configObjects:ne,exitProcess:{set value(n){__classPrivateFieldSet(S,jd,n,`f`)}}.value,groups:{set value(n){__classPrivateFieldSet(C,Pd,n,`f`)}}.value,output:{set value(n){__classPrivateFieldSet(N,zd,n,`f`)}}.value,exitError:{set value(n){__classPrivateFieldSet(F,Od,n,`f`)}}.value,hasOutput:{set value(n){__classPrivateFieldSet(I,Fd,n,`f`)}}.value,parsed:this.parsed,strict:{set value(n){__classPrivateFieldSet(H,Xd,n,`f`)}}.value,strictCommands:{set value(n){__classPrivateFieldSet(W,Zd,n,`f`)}}.value,strictOptions:{set value(n){__classPrivateFieldSet(q,Qd,n,`f`)}}.value,completionCommand:{set value(n){__classPrivateFieldSet(Y,Ed,n,`f`)}}.value,parseFn:{set value(n){__classPrivateFieldSet(X,Ud,n,`f`)}}.value,parseContext:{set value(n){__classPrivateFieldSet(Z,Wd,n,`f`)}}.value}=te,__classPrivateFieldGet(this,Bd,`f`).configObjects=ne,__classPrivateFieldGet(this,$d,`f`).unfreeze(),__classPrivateFieldGet(this,nf,`f`).unfreeze(),__classPrivateFieldGet(this,Sd,`f`).unfreeze(),__classPrivateFieldGet(this,Nd,`f`).unfreeze()}[Cf](n,S){return maybeAsyncResult(S,S=>(n(S),S))}getInternalMethods(){return{getCommandInstance:this[wf].bind(this),getContext:this[Tf].bind(this),getHasOutput:this[Ef].bind(this),getLoggerInstance:this[Df].bind(this),getParseContext:this[Of].bind(this),getParserConfiguration:this[uf].bind(this),getUsageConfiguration:this[df].bind(this),getUsageInstance:this[kf].bind(this),getValidationInstance:this[Af].bind(this),hasParseCallback:this[jf].bind(this),isGlobalContext:this[Mf].bind(this),postProcess:this[Nf].bind(this),reset:this[Ff].bind(this),runValidation:this[Lf].bind(this),runYargsParserAndExecuteCommands:this[If].bind(this),setHasOutput:this[Rf].bind(this)}}[wf](){return __classPrivateFieldGet(this,Sd,`f`)}[Tf](){return __classPrivateFieldGet(this,wd,`f`)}[Ef](){return __classPrivateFieldGet(this,Fd,`f`)}[Df](){return __classPrivateFieldGet(this,Rd,`f`)}[Of](){return __classPrivateFieldGet(this,Wd,`f`)||{}}[kf](){return __classPrivateFieldGet(this,$d,`f`)}[Af](){return __classPrivateFieldGet(this,nf,`f`)}[jf](){return!!__classPrivateFieldGet(this,Ud,`f`)}[Mf](){return __classPrivateFieldGet(this,Ld,`f`)}[Nf](n,S,C,N){return C||isPromise(n)?n:(S||(n=this[rf](n)),(this[uf]()[`parse-positional-numbers`]||this[uf]()[`parse-positional-numbers`]===void 0)&&(n=this[mf](n)),N&&(n=applyMiddleware(n,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!1)),n)}[Ff](n={}){__classPrivateFieldSet(this,Bd,__classPrivateFieldGet(this,Bd,`f`)||{},`f`);let S={};S.local=__classPrivateFieldGet(this,Bd,`f`).local||[],S.configObjects=__classPrivateFieldGet(this,Bd,`f`).configObjects||[];let C={};return S.local.forEach(S=>{C[S]=!0,(n[S]||[]).forEach(n=>{C[n]=!0})}),Object.assign(__classPrivateFieldGet(this,Kd,`f`),Object.keys(__classPrivateFieldGet(this,Pd,`f`)).reduce((n,S)=>{let N=__classPrivateFieldGet(this,Pd,`f`)[S].filter(n=>!(n in C));return N.length>0&&(n[S]=N),n},{})),__classPrivateFieldSet(this,Pd,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(n=>{S[n]=(__classPrivateFieldGet(this,Bd,`f`)[n]||[]).filter(n=>!C[n])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(n=>{S[n]=objFilter(__classPrivateFieldGet(this,Bd,`f`)[n],n=>!C[n])}),S.envPrefix=__classPrivateFieldGet(this,Bd,`f`).envPrefix,__classPrivateFieldSet(this,Bd,S,`f`),__classPrivateFieldSet(this,$d,__classPrivateFieldGet(this,$d,`f`)?__classPrivateFieldGet(this,$d,`f`).reset(C):usage(this,__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldSet(this,nf,__classPrivateFieldGet(this,nf,`f`)?__classPrivateFieldGet(this,nf,`f`).reset(C):validation(this,__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldSet(this,Sd,__classPrivateFieldGet(this,Sd,`f`)?__classPrivateFieldGet(this,Sd,`f`).reset():command(__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,nf,`f`),__classPrivateFieldGet(this,Nd,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldGet(this,Td,`f`)||__classPrivateFieldSet(this,Td,completion(this,__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,Sd,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldGet(this,Nd,`f`).reset(),__classPrivateFieldSet(this,Ed,null,`f`),__classPrivateFieldSet(this,zd,``,`f`),__classPrivateFieldSet(this,Od,null,`f`),__classPrivateFieldSet(this,Fd,!1,`f`),this.parsed=!1,this}[Pf](n,S){return __classPrivateFieldGet(this,Yd,`f`).path.relative(n,S)}[If](n,S,C,N=0,F=!1){let I=!!C||F;n||=__classPrivateFieldGet(this,qd,`f`),__classPrivateFieldGet(this,Bd,`f`).__=__classPrivateFieldGet(this,Yd,`f`).y18n.__,__classPrivateFieldGet(this,Bd,`f`).configuration=this[uf]();let H=!!__classPrivateFieldGet(this,Bd,`f`).configuration[`populate--`],W=Object.assign({},__classPrivateFieldGet(this,Bd,`f`).configuration,{"populate--":!0}),q=__classPrivateFieldGet(this,Yd,`f`).Parser.detailed(n,Object.assign({},__classPrivateFieldGet(this,Bd,`f`),{configuration:{"parse-positional-numbers":!1,...W}})),Y=Object.assign(q.argv,__classPrivateFieldGet(this,Wd,`f`)),X,Z=q.aliases,te=!1,ne=!1;Object.keys(Y).forEach(n=>{n===__classPrivateFieldGet(this,Id,`f`)&&Y[n]?te=!0:n===__classPrivateFieldGet(this,tf,`f`)&&Y[n]&&(ne=!0)}),Y.$0=this.$0,this.parsed=q,N===0&&__classPrivateFieldGet(this,$d,`f`).clearCachedHelpMessage();try{if(this[ff](),S)return this[Nf](Y,H,!!C,!1);__classPrivateFieldGet(this,Id,`f`)&&[__classPrivateFieldGet(this,Id,`f`)].concat(Z[__classPrivateFieldGet(this,Id,`f`)]||[]).filter(n=>n.length>1).includes(``+Y._[Y._.length-1])&&(Y._.pop(),te=!0),__classPrivateFieldSet(this,Ld,!1,`f`);let W=__classPrivateFieldGet(this,Sd,`f`).getCommands(),re=__classPrivateFieldGet(this,Td,`f`)?.completionKey?[__classPrivateFieldGet(this,Td,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Td,`f`)?.completionKey]??[]].some(n=>Object.prototype.hasOwnProperty.call(Y,n)):!1,ie=te||re||F;if(Y._.length){if(W.length){let n;for(let S=N||0,I;Y._[S]!==void 0;S++)if(I=String(Y._[S]),W.includes(I)&&I!==__classPrivateFieldGet(this,Ed,`f`)){let n=__classPrivateFieldGet(this,Sd,`f`).runCommand(I,this,q,S+1,F,te||ne||F);return this[Nf](n,H,!!C,!1)}else if(!n&&I!==__classPrivateFieldGet(this,Ed,`f`)){n=I;break}!__classPrivateFieldGet(this,Sd,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Jd,`f`)&&n&&!ie&&__classPrivateFieldGet(this,nf,`f`).recommendCommands(n,W)}__classPrivateFieldGet(this,Ed,`f`)&&Y._.includes(__classPrivateFieldGet(this,Ed,`f`))&&!re&&(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Sd,`f`).hasDefaultCommand()&&!ie){let n=__classPrivateFieldGet(this,Sd,`f`).runCommand(null,this,q,0,F,te||ne||F);return this[Nf](n,H,!!C,!1)}if(re){__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),n=[].concat(n);let S=n.slice(n.indexOf(`--${__classPrivateFieldGet(this,Td,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Td,`f`).getCompletion(S,(n,S)=>{if(n)throw new ns(n.message);(S||[]).forEach(n=>{__classPrivateFieldGet(this,Rd,`f`).log(n)}),this.exit(0)}),this[Nf](Y,!H,!!C,!1)}if(__classPrivateFieldGet(this,Fd,`f`)||(te?(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),I=!0,this.showHelp(n=>{__classPrivateFieldGet(this,Rd,`f`).log(n),this.exit(0)})):ne&&(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),I=!0,__classPrivateFieldGet(this,$d,`f`).showVersion(`log`),this.exit(0))),!I&&__classPrivateFieldGet(this,Bd,`f`).skipValidation.length>0&&(I=Object.keys(Y).some(n=>__classPrivateFieldGet(this,Bd,`f`).skipValidation.indexOf(n)>=0&&Y[n]===!0)),!I){if(q.error)throw new ns(q.error.message);if(!re){let n=this[Lf](Z,{},q.error);C||(X=applyMiddleware(Y,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!0)),X=this[Cf](n,X??Y),isPromise(X)&&!C&&(X=X.then(()=>applyMiddleware(Y,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!1)))}}}catch(n){if(n instanceof ns)__classPrivateFieldGet(this,$d,`f`).fail(n.message,n);else throw n}return this[Nf](X??Y,H,!!C,!0)}[Lf](n,S,C,N){let F={...this.getDemandedOptions()};return I=>{if(C)throw new ns(C.message);__classPrivateFieldGet(this,nf,`f`).nonOptionCount(I),__classPrivateFieldGet(this,nf,`f`).requiredArguments(I,F);let H=!1;__classPrivateFieldGet(this,Zd,`f`)&&(H=__classPrivateFieldGet(this,nf,`f`).unknownCommands(I)),__classPrivateFieldGet(this,Xd,`f`)&&!H?__classPrivateFieldGet(this,nf,`f`).unknownArguments(I,n,S,!!N):__classPrivateFieldGet(this,Qd,`f`)&&__classPrivateFieldGet(this,nf,`f`).unknownArguments(I,n,{},!1,!1),__classPrivateFieldGet(this,nf,`f`).limitedChoices(I),__classPrivateFieldGet(this,nf,`f`).implications(I),__classPrivateFieldGet(this,nf,`f`).conflicting(I)}}[Rf](){__classPrivateFieldSet(this,Fd,!0,`f`)}[zf](n){if(typeof n==`string`)__classPrivateFieldGet(this,Bd,`f`).key[n]=!0;else for(let S of n)__classPrivateFieldGet(this,Bd,`f`).key[S]=!0}}}),Hf,Uf=__esmMin(()=>{nd(),Vf(),Hf=YargsFactory(td)});function classifyCliFailure(n,S){return typeof n==`string`&&n.length>0?{kind:`usage`,message:n}:{kind:`runtime`}}var Wf=__esmMin(()=>{});function buildHeaders(n,S){let C={"user-agent":`gjsify-install/0.46.0`,"accept-encoding":S.acceptEncoding??`identity`};if(S.npmrc){let N=resolveAuthForUrl(n,S.npmrc);N&&(C.authorization=N)}if(S.headers)for(let[n,N]of Object.entries(S.headers))C[n.toLowerCase()]=N;return C}function resolveAuthForUrl(n,S){let C=pathPrefixes(new URL(n));for(let n of C){let C=S.authTokens[n];if(C)return`Bearer ${C}`;let N=S.basicAuth[n];if(N)return`Basic ${btoa(`${N.username}:${N.password}`)}`}return null}function pathPrefixes(n){let S=n.pathname.split(`/`).filter(Boolean),C=[];for(let N=S.length;N>=0;N--){let F=S.slice(0,N).join(`/`);C.push(F?`//${n.host}/${F}`:`//${n.host}`)}return C}var Gf=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,Kf=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(n,S){super(`Package not found in registry: ${n} (${S})`),this.name=n,this.url=S,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(n,S){super(`Tarball integrity mismatch for ${n} (expected ${S})`),this.url=n,this.integrity=S,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(n,S,C){let N=Math.round(S/100)/10,F=Math.round(S*C/100)/10;super(`@gjsify/npm-registry: GET ${n} timed out after ${N}s × ${C} attempt(s) (total ~${F}s). This usually means the registry CDN is slow or unreachable.`),this.url=n,this.timeoutMs=S,this.attempts=C,this.name=`RegistryTimeoutError`}}});function registryFor(n,S){if(S&&n.startsWith(`@`)){let C=n.slice(0,n.indexOf(`/`)),N=S.scopes[C];if(N)return ensureTrailingSlash$1(N)}return S?.registry?ensureTrailingSlash$1(S.registry):qf}function parseNpmrc(n){let S={registry:qf,scopes:{},authTokens:{},basicAuth:{}},C=n.split(/\r?\n/),N={};for(let n of C){let C=n.replace(/^\s+|\s+$/g,``);if(!C||C.startsWith(`#`)||C.startsWith(`;`))continue;let F=C.indexOf(`=`);if(F<0)continue;let I=C.slice(0,F).trim(),H=expandEnv(stripQuotes(C.slice(F+1).trim()));if(I===`registry`){S.registry=ensureTrailingSlash$1(H);continue}let W=I.match(/^(@[^:]+):registry$/);if(W){S.scopes[W[1]]=ensureTrailingSlash$1(H);continue}let q=I.match(/^\/\/(.+):_authToken$/);if(q){S.authTokens[normalizeAuthHost(q[1])]=H;continue}let Y=I.match(/^\/\/(.+):username$/);if(Y){(N[normalizeAuthHost(Y[1])]??={}).user=H;continue}let X=I.match(/^\/\/(.+):_password$/);if(X){let n=base64Decode(H);(N[normalizeAuthHost(X[1])]??={}).pass=n;continue}}for(let[n,C]of Object.entries(N))C.user&&C.pass!==void 0&&(S.basicAuth[n]={username:C.user,password:C.pass});return S}function normalizeAuthHost(n){return`//${n.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(n){return n.endsWith(`/`)?n:n+`/`}function stripQuotes(n){return n.startsWith(`"`)&&n.endsWith(`"`)||n.startsWith(`'`)&&n.endsWith(`'`)?n.slice(1,-1):n}function expandEnv(n){return n.replace(/\$\{([A-Z0-9_]+)\}/gi,(n,S)=>globalThis.process?.env?.[S]??``)}function base64Decode(n){return atob(n)}var qf,Jf=__esmMin(()=>{qf=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`)});async function fetchWithRetry(n,S,C){let N=C.fetch??globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=Math.max(0,C.retries??3),I=Math.max(0,C.retryDelayMs??250),H=Math.max(0,C.timeoutMs??3e4),W=C.retryNotFound??!1,q=0,Y,X=0;for(;;){if(S.signal?.aborted)throw signalAbortError(S.signal);let Z=H>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${H}ms`)),H),ne=composeSignals(S.signal,Z?.signal);try{let C=await N(n,{...S,signal:ne}),I=isRetryableStatus(C.status)||W&&C.status===404;if(C.ok||!I||q>=F)return C;try{await C.arrayBuffer()}catch{}Y=Error(`HTTP ${C.status} ${C.statusText}`)}catch(C){let N=Z!==null&&Z.signal.aborted,I=S.signal?.aborted===!0;if(N&&!I){if(X++,q>=F)throw new RegistryTimeoutError(n,H,X);Y=C}else if(I)throw signalAbortError(S.signal);else{if(!isRetryableError(C)||q>=F)throw C;Y=C}}finally{te!==null&&clearTimeout(te)}let re=Math.min(I*2**q,8e3);C.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,S.signal),q++}}function composeSignals(n,S){return n?S?AbortSignal.any([n,S]):n:S}function isRetryableStatus(n){return n===408||n===425||n===429||n===500||n===502||n===503||n===504||n===521||n===522||n===524||n===525}function isRetryableError(n){if(n&&typeof n==`object`&&`name`in n&&n.name===`AbortError`)return!1;if(n instanceof TypeError)return!0;if(n&&typeof n==`object`&&`name`in n){let S=n.name;if(S===`FetchError`)return!0;if(S===`AbortError`)return!1}let S=n?.cause;if(S&&typeof S==`object`&&`code`in S){let n=S.code;if(typeof n==`string`)return n===`ECONNRESET`||n===`ECONNREFUSED`||n===`ENETUNREACH`||n===`ENOTFOUND`||n===`ETIMEDOUT`||n===`EAI_AGAIN`||n===`UND_ERR_SOCKET`||n===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(n,S){return n<=0?Promise.resolve():new Promise((C,N)=>{let F=setTimeout(()=>{S?.removeEventListener?.(`abort`,onAbort),C()},n),onAbort=()=>{clearTimeout(F),N(signalAbortError(S))};if(S?.aborted){clearTimeout(F),N(signalAbortError(S));return}S?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(n){let S=n&&`reason`in n?n.reason:void 0;if(S instanceof Error)return S;let C=Error(`Aborted`);return C.name=`AbortError`,C}var Yf=__esmMin(()=>{Kf(),__name$1(delay$1,`delay`)});async function verifyIntegrity(n,S){let C=S.trim().split(/\s+/);for(let S of C){let C=S.indexOf(`-`);if(C<0)continue;let N=S.slice(0,C).toLowerCase(),F=S.slice(C+1),I=globalThis.crypto?.subtle;if(!I)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let H=subriToWebCryptoAlgo(N);if(!H)continue;let W=await I.digest(H,dataAsArrayBuffer(n));if(bytesToBase64(new Uint8Array(W))===F)return!0}return!1}function subriToWebCryptoAlgo(n){switch(n){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(n){if(n.byteOffset===0&&n.byteLength===n.buffer.byteLength)return n.buffer;let S=new Uint8Array(n.byteLength);return S.set(n),S.buffer}function bytesToBase64(n){let S=``;for(let C=0;C<n.length;C++)S+=String.fromCharCode(n[C]);return btoa(S)}var Xf=__esmMin(()=>{});function assertPackument(n,S){if(!S||typeof S!=`object`)throw TypeError(`registry: ${n} packument is not an object`);let C=S;if(typeof C.name!=`string`)throw TypeError(`registry: ${n} packument missing string name`);if(!C.versions||typeof C.versions!=`object`)throw TypeError(`registry: ${n} packument missing versions map`)}function packumentUrl(n,S){let C=ensureTrailingSlash$1(S);if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S<0)throw TypeError(`Invalid scoped package name: ${n}`);let N=n.slice(0,S),F=n.slice(S+1);return`${C}${encodeURIComponent(N)}/${encodeURIComponent(F)}`}return`${C}${encodeURIComponent(n)}`}async function fetchPackumentConditional(n,S={}){let C=packumentUrl(n,S.registry??registryFor(n,S.npmrc)),N=buildHeaders(C,{...S,acceptEncoding:`gzip`});N.accept??=S.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,S.ifNoneMatch&&(N[`if-none-match`]=S.ifNoneMatch);let F=await fetchWithRetry(C,{headers:N,signal:S.signal},{fetch:S.fetch,retries:S.retries,retryDelayMs:S.retryDelayMs,timeoutMs:S.timeoutMs,onRetry:S.onRetry});if(F.status===304){try{await F.arrayBuffer()}catch{}return{status:`not-modified`,etag:S.ifNoneMatch}}if(!F.ok)throw F.status===404||F.status===406?new PackageNotFoundError(n,C):Error(`registry GET ${C} -> ${F.status} ${F.statusText}`);let I=F.headers.get(`etag`)??void 0,H=await decodeJsonBody(F);return assertPackument(n,H),{status:`fresh`,packument:H,etag:I}}async function decodeJsonBody(n){return n.json()}async function fetchPackument(n,S={}){let C=await fetchPackumentConditional(n,S);if(!C.packument)throw Error(`registry: ${n} returned 304 Not Modified to an unconditional request`);return C.packument}var Zf=__esmMin(()=>{Gf(),Kf(),Jf(),Yf()});async function fetchTarball(n,S={}){let C=buildHeaders(n,{...S,acceptEncoding:`identity`});C.accept??=`application/octet-stream`;let N=await fetchWithRetry(n,{headers:C,signal:S.signal},{fetch:S.fetch,retries:S.retries,retryDelayMs:S.retryDelayMs,timeoutMs:S.timeoutMs,onRetry:S.onRetry,retryNotFound:S.retryNotFound??!0});if(!N.ok)throw Error(`tarball GET ${n} -> ${N.status} ${N.statusText}`);let F=new Uint8Array(await N.arrayBuffer());if(S.integrity&&!await verifyIntegrity(F,S.integrity))throw new IntegrityError(n,S.integrity);return F}var Qf=__esmMin(()=>{Gf(),Kf(),Yf(),Xf()});async function whoami(n,S){let C=`${ensureTrailingSlash$1(n)}-/whoami`,N=buildHeaders(C,{npmrc:S});N.accept=`application/json`;let F=globalThis.fetch;if(!F)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let I=await F(C,{method:`GET`,headers:N});if(!I.ok)throw Error(`whoami GET ${C} -> ${I.status} ${I.statusText}`);let H=await I.json();if(H&&typeof H==`object`&&`username`in H){let n=H.username;if(typeof n==`string`&&n.length>0)return{username:n}}return{}}var $f=__esmMin(()=>{Gf(),Jf()}),ep=__esmMin(()=>{Gf(),Jf(),Zf(),Qf(),$f()});function escapePackageName(n){return n.replace(`/`,`%2f`)}function buildPublishHeaders(n,S){let C=buildHeaders(n,{npmrc:S.npmrc});return C[`content-type`]=`application/json`,C[`npm-command`]=`publish`,C[`npm-auth-type`]=S.otp?`legacy`:`web`,C[`user-agent`]=S.userAgent??defaultUserAgent(),S.otp&&(C[`npm-otp`]=S.otp),S.authorization&&(C.authorization=S.authorization),C}function cliVersion(){return tp===void 0&&(tp=`0.46.0`),tp}function cliPackageDir(){let n=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,S;try{S=Ps(n||fileURLToPath(import.meta.url))}catch{return null}for(let n=0;n<12;n++){try{if(JSON.parse(readFileSync(`${S}/package.json`,`utf8`)).name===`@gjsify/cli`)return S}catch{}let n=Ps(S);if(n===S)break;S=n}return null}function defaultUserAgent(){let n=globalThis.process,S=n?.arch??`x64`,C=n?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${C} ${S})`}var tp,np=__esmMin(()=>{Vl(),Hs(),gn(),ep()}),rp,ip=__esmMin(()=>{rp=`gjsify`}),ap=__commonJSMin(((n,S)=>{let C=(Hs(),__toCommonJS(Es)),N=(gs(),__toCommonJS(fs)),F=(Vl(),__toCommonJS(Rl)),resolveFrom=(n,S,I)=>{if(typeof n!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof n}\``);if(typeof S!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof S}\``);try{n=F.realpathSync(n)}catch(S){if(S.code===`ENOENT`)n=C.resolve(n);else if(I)return null;else throw S}let H=C.join(n,`noop.js`),resolveFileName=()=>N._resolveFilename(S,{id:H,filename:H,paths:N._nodeModulePaths(n)});if(I)try{return resolveFileName()}catch{return null}return resolveFileName()};S.exports=(n,S)=>resolveFrom(n,S),S.exports.silent=(n,S)=>resolveFrom(n,S,!0)})),op=__commonJSMin(((n,S)=>{let callsites=()=>{let n=Error.prepareStackTrace;Error.prepareStackTrace=(n,S)=>S;let S=Error().stack.slice(1);return Error.prepareStackTrace=n,S};S.exports=callsites,S.exports.default=callsites})),sp=__commonJSMin(((n,S)=>{let C=op();S.exports=n=>{let S=C();if(!n)return S[2].getFileName();let N=!1;S.shift();for(let C of S){let S=C.getFileName();if(typeof S==`string`){if(S===n){N=!0;continue}if(S!==`module.js`&&N&&S!==n)return S}}}})),lp=__commonJSMin(((n,S)=>{var{__gjsifyModuleDir:C,__gjsifyModuleFile:N}=(Ks(),__toCommonJS(Us)),F=C(`import-fresh/index.js`),I=N(`import-fresh/index.js`);let H=(Hs(),__toCommonJS(Es)),W=ap(),q=sp();S.exports=n=>{if(typeof n!=`string`)throw TypeError(`Expected a string`);let S=q(I),C=S?H.dirname(S):F,N=W(C,n),Y=X.cache[N];if(Y&&Y.parent){let n=Y.parent.children.length;for(;n--;)Y.parent.children[n].id===N&&Y.parent.children.splice(n,1)}delete X.cache[N];let Z=X.cache[S];return Z===void 0||Z.require===void 0?X(N):Z.require(N)}})),up=__commonJSMin(((n,S)=>{S.exports=function isArrayish(n){return n?n instanceof Array||Array.isArray(n)||n.length>=0&&n.splice instanceof Function:!1}})),dp=__commonJSMin(((n,S)=>{var C=(Ac(),__toCommonJS(Ec)),N=up(),F=function errorEx(n,S){(!n||n.constructor!==String)&&(S=n||{},n=Error.name);var F=function ErrorEXError(C){if(!this)return new ErrorEXError(C);C=C instanceof Error?C.message:C||this.message,Error.call(this,C),Error.captureStackTrace(this,F),this.name=n,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var n=C.split(/\r?\n/g);for(var F in S)if(S.hasOwnProperty(F)){var I=S[F];`message`in I&&(n=I.message(this[F],n)||n,N(n)||(n=[n]))}return n.join(`
|
|
122
|
+
`,`f`),__classPrivateFieldSet(this,zd,__classPrivateFieldGet(this,zd,`f`)+n.join(` `),`f`)}}}[of](n){objectKeys(__classPrivateFieldGet(this,Bd,`f`)).forEach(S=>{if((n=>n===`configObjects`)(S))return;let C=__classPrivateFieldGet(this,Bd,`f`)[S];Array.isArray(C)?C.includes(n)&&C.splice(C.indexOf(n),1):typeof C==`object`&&delete C[n]}),delete __classPrivateFieldGet(this,$d,`f`).getDescriptions()[n]}[sf](n,S,C){__classPrivateFieldGet(this,Ad,`f`)[C]||(__classPrivateFieldGet(this,Yd,`f`).process.emitWarning(n,S),__classPrivateFieldGet(this,Ad,`f`)[C]=!0)}[cf](){__classPrivateFieldGet(this,Md,`f`).push({options:__classPrivateFieldGet(this,Bd,`f`),configObjects:__classPrivateFieldGet(this,Bd,`f`).configObjects.slice(0),exitProcess:__classPrivateFieldGet(this,jd,`f`),groups:__classPrivateFieldGet(this,Pd,`f`),strict:__classPrivateFieldGet(this,Xd,`f`),strictCommands:__classPrivateFieldGet(this,Zd,`f`),strictOptions:__classPrivateFieldGet(this,Qd,`f`),completionCommand:__classPrivateFieldGet(this,Ed,`f`),output:__classPrivateFieldGet(this,zd,`f`),exitError:__classPrivateFieldGet(this,Od,`f`),hasOutput:__classPrivateFieldGet(this,Fd,`f`),parsed:this.parsed,parseFn:__classPrivateFieldGet(this,Ud,`f`),parseContext:__classPrivateFieldGet(this,Wd,`f`)}),__classPrivateFieldGet(this,$d,`f`).freeze(),__classPrivateFieldGet(this,nf,`f`).freeze(),__classPrivateFieldGet(this,Sd,`f`).freeze(),__classPrivateFieldGet(this,Nd,`f`).freeze()}[lf](){let n=``,S;return S=/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this,Yd,`f`).process.argv()[0])?__classPrivateFieldGet(this,Yd,`f`).process.argv().slice(1,2):__classPrivateFieldGet(this,Yd,`f`).process.argv().slice(0,1),n=S.map(n=>{let S=this[Pf](__classPrivateFieldGet(this,Cd,`f`),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&S.length<n.length?S:n}).join(` `).trim(),__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`)&&__classPrivateFieldGet(this,Yd,`f`).getProcessArgvBin()===__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`)&&(n=__classPrivateFieldGet(this,Yd,`f`).getEnv(`_`).replace(`${__classPrivateFieldGet(this,Yd,`f`).path.dirname(__classPrivateFieldGet(this,Yd,`f`).process.execPath())}/`,``)),n}[uf](){return __classPrivateFieldGet(this,Hd,`f`)}[df](){return __classPrivateFieldGet(this,ef,`f`)}[ff](){if(!__classPrivateFieldGet(this,kd,`f`))return;let n=__classPrivateFieldGet(this,Yd,`f`).getEnv(`LC_ALL`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LC_MESSAGES`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LANG`)||__classPrivateFieldGet(this,Yd,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(n.replace(/[.:].*/,``))}[pf](){return this[hf]().version||`unknown`}[mf](n){let S=n[`--`]?n[`--`]:n._;for(let n=0,C;(C=S[n])!==void 0;n++)__classPrivateFieldGet(this,Yd,`f`).Parser.looksLikeNumber(C)&&Number.isSafeInteger(Math.floor(parseFloat(`${C}`)))&&(S[n]=Number(C));return n}[hf](n){let S=n||`*`;if(__classPrivateFieldGet(this,Gd,`f`)[S])return __classPrivateFieldGet(this,Gd,`f`)[S];let C={};try{let S=n||__classPrivateFieldGet(this,Yd,`f`).mainFilename;__classPrivateFieldGet(this,Yd,`f`).path.extname(S)&&(S=__classPrivateFieldGet(this,Yd,`f`).path.dirname(S));let N=__classPrivateFieldGet(this,Yd,`f`).findUp(S,(n,S)=>{if(S.includes(`package.json`))return`package.json`});assertNotStrictEqual(N,void 0,__classPrivateFieldGet(this,Yd,`f`)),C=JSON.parse(__classPrivateFieldGet(this,Yd,`f`).readFileSync(N,`utf8`))}catch{}return __classPrivateFieldGet(this,Gd,`f`)[S]=C||{},__classPrivateFieldGet(this,Gd,`f`)[S]}[gf](n,S){S=[].concat(S),S.forEach(S=>{S=this[bf](S),__classPrivateFieldGet(this,Bd,`f`)[n].push(S)})}[_f](n,S,C,N){this[yf](n,S,C,N,(n,S,C)=>{__classPrivateFieldGet(this,Bd,`f`)[n][S]=C})}[vf](n,S,C,N){this[yf](n,S,C,N,(n,S,C)=>{__classPrivateFieldGet(this,Bd,`f`)[n][S]=(__classPrivateFieldGet(this,Bd,`f`)[n][S]||[]).concat(C)})}[yf](n,S,C,N,F){if(Array.isArray(C))C.forEach(S=>{n(S,N)});else if((n=>typeof n==`object`)(C))for(let S of objectKeys(C))n(S,C[S]);else F(S,this[bf](C),N)}[bf](n){return n===`__proto__`?`___proto___`:n}[xf](n,S){return this[_f](this[xf].bind(this),`key`,n,S),this}[Sf](){var n,S,C,N,F,I,H,W,q,Y,X,Z;let te=__classPrivateFieldGet(this,Md,`f`).pop();assertNotStrictEqual(te,void 0,__classPrivateFieldGet(this,Yd,`f`));let ne;n=this,S=this,C=this,N=this,F=this,I=this,H=this,W=this,q=this,Y=this,X=this,Z=this,{options:{set value(S){__classPrivateFieldSet(n,Bd,S,`f`)}}.value,configObjects:ne,exitProcess:{set value(n){__classPrivateFieldSet(S,jd,n,`f`)}}.value,groups:{set value(n){__classPrivateFieldSet(C,Pd,n,`f`)}}.value,output:{set value(n){__classPrivateFieldSet(N,zd,n,`f`)}}.value,exitError:{set value(n){__classPrivateFieldSet(F,Od,n,`f`)}}.value,hasOutput:{set value(n){__classPrivateFieldSet(I,Fd,n,`f`)}}.value,parsed:this.parsed,strict:{set value(n){__classPrivateFieldSet(H,Xd,n,`f`)}}.value,strictCommands:{set value(n){__classPrivateFieldSet(W,Zd,n,`f`)}}.value,strictOptions:{set value(n){__classPrivateFieldSet(q,Qd,n,`f`)}}.value,completionCommand:{set value(n){__classPrivateFieldSet(Y,Ed,n,`f`)}}.value,parseFn:{set value(n){__classPrivateFieldSet(X,Ud,n,`f`)}}.value,parseContext:{set value(n){__classPrivateFieldSet(Z,Wd,n,`f`)}}.value}=te,__classPrivateFieldGet(this,Bd,`f`).configObjects=ne,__classPrivateFieldGet(this,$d,`f`).unfreeze(),__classPrivateFieldGet(this,nf,`f`).unfreeze(),__classPrivateFieldGet(this,Sd,`f`).unfreeze(),__classPrivateFieldGet(this,Nd,`f`).unfreeze()}[Cf](n,S){return maybeAsyncResult(S,S=>(n(S),S))}getInternalMethods(){return{getCommandInstance:this[wf].bind(this),getContext:this[Tf].bind(this),getHasOutput:this[Ef].bind(this),getLoggerInstance:this[Df].bind(this),getParseContext:this[Of].bind(this),getParserConfiguration:this[uf].bind(this),getUsageConfiguration:this[df].bind(this),getUsageInstance:this[kf].bind(this),getValidationInstance:this[Af].bind(this),hasParseCallback:this[jf].bind(this),isGlobalContext:this[Mf].bind(this),postProcess:this[Nf].bind(this),reset:this[Ff].bind(this),runValidation:this[Lf].bind(this),runYargsParserAndExecuteCommands:this[If].bind(this),setHasOutput:this[Rf].bind(this)}}[wf](){return __classPrivateFieldGet(this,Sd,`f`)}[Tf](){return __classPrivateFieldGet(this,wd,`f`)}[Ef](){return __classPrivateFieldGet(this,Fd,`f`)}[Df](){return __classPrivateFieldGet(this,Rd,`f`)}[Of](){return __classPrivateFieldGet(this,Wd,`f`)||{}}[kf](){return __classPrivateFieldGet(this,$d,`f`)}[Af](){return __classPrivateFieldGet(this,nf,`f`)}[jf](){return!!__classPrivateFieldGet(this,Ud,`f`)}[Mf](){return __classPrivateFieldGet(this,Ld,`f`)}[Nf](n,S,C,N){return C||isPromise(n)?n:(S||(n=this[rf](n)),(this[uf]()[`parse-positional-numbers`]||this[uf]()[`parse-positional-numbers`]===void 0)&&(n=this[mf](n)),N&&(n=applyMiddleware(n,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!1)),n)}[Ff](n={}){__classPrivateFieldSet(this,Bd,__classPrivateFieldGet(this,Bd,`f`)||{},`f`);let S={};S.local=__classPrivateFieldGet(this,Bd,`f`).local||[],S.configObjects=__classPrivateFieldGet(this,Bd,`f`).configObjects||[];let C={};return S.local.forEach(S=>{C[S]=!0,(n[S]||[]).forEach(n=>{C[n]=!0})}),Object.assign(__classPrivateFieldGet(this,Kd,`f`),Object.keys(__classPrivateFieldGet(this,Pd,`f`)).reduce((n,S)=>{let N=__classPrivateFieldGet(this,Pd,`f`)[S].filter(n=>!(n in C));return N.length>0&&(n[S]=N),n},{})),__classPrivateFieldSet(this,Pd,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(n=>{S[n]=(__classPrivateFieldGet(this,Bd,`f`)[n]||[]).filter(n=>!C[n])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(n=>{S[n]=objFilter(__classPrivateFieldGet(this,Bd,`f`)[n],n=>!C[n])}),S.envPrefix=__classPrivateFieldGet(this,Bd,`f`).envPrefix,__classPrivateFieldSet(this,Bd,S,`f`),__classPrivateFieldSet(this,$d,__classPrivateFieldGet(this,$d,`f`)?__classPrivateFieldGet(this,$d,`f`).reset(C):usage(this,__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldSet(this,nf,__classPrivateFieldGet(this,nf,`f`)?__classPrivateFieldGet(this,nf,`f`).reset(C):validation(this,__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldSet(this,Sd,__classPrivateFieldGet(this,Sd,`f`)?__classPrivateFieldGet(this,Sd,`f`).reset():command(__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,nf,`f`),__classPrivateFieldGet(this,Nd,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldGet(this,Td,`f`)||__classPrivateFieldSet(this,Td,completion(this,__classPrivateFieldGet(this,$d,`f`),__classPrivateFieldGet(this,Sd,`f`),__classPrivateFieldGet(this,Yd,`f`)),`f`),__classPrivateFieldGet(this,Nd,`f`).reset(),__classPrivateFieldSet(this,Ed,null,`f`),__classPrivateFieldSet(this,zd,``,`f`),__classPrivateFieldSet(this,Od,null,`f`),__classPrivateFieldSet(this,Fd,!1,`f`),this.parsed=!1,this}[Pf](n,S){return __classPrivateFieldGet(this,Yd,`f`).path.relative(n,S)}[If](n,S,C,N=0,F=!1){let I=!!C||F;n||=__classPrivateFieldGet(this,qd,`f`),__classPrivateFieldGet(this,Bd,`f`).__=__classPrivateFieldGet(this,Yd,`f`).y18n.__,__classPrivateFieldGet(this,Bd,`f`).configuration=this[uf]();let H=!!__classPrivateFieldGet(this,Bd,`f`).configuration[`populate--`],W=Object.assign({},__classPrivateFieldGet(this,Bd,`f`).configuration,{"populate--":!0}),q=__classPrivateFieldGet(this,Yd,`f`).Parser.detailed(n,Object.assign({},__classPrivateFieldGet(this,Bd,`f`),{configuration:{"parse-positional-numbers":!1,...W}})),Y=Object.assign(q.argv,__classPrivateFieldGet(this,Wd,`f`)),X,Z=q.aliases,te=!1,ne=!1;Object.keys(Y).forEach(n=>{n===__classPrivateFieldGet(this,Id,`f`)&&Y[n]?te=!0:n===__classPrivateFieldGet(this,tf,`f`)&&Y[n]&&(ne=!0)}),Y.$0=this.$0,this.parsed=q,N===0&&__classPrivateFieldGet(this,$d,`f`).clearCachedHelpMessage();try{if(this[ff](),S)return this[Nf](Y,H,!!C,!1);__classPrivateFieldGet(this,Id,`f`)&&[__classPrivateFieldGet(this,Id,`f`)].concat(Z[__classPrivateFieldGet(this,Id,`f`)]||[]).filter(n=>n.length>1).includes(``+Y._[Y._.length-1])&&(Y._.pop(),te=!0),__classPrivateFieldSet(this,Ld,!1,`f`);let W=__classPrivateFieldGet(this,Sd,`f`).getCommands(),re=__classPrivateFieldGet(this,Td,`f`)?.completionKey?[__classPrivateFieldGet(this,Td,`f`)?.completionKey,...this.getAliases()[__classPrivateFieldGet(this,Td,`f`)?.completionKey]??[]].some(n=>Object.prototype.hasOwnProperty.call(Y,n)):!1,ie=te||re||F;if(Y._.length){if(W.length){let n;for(let S=N||0,I;Y._[S]!==void 0;S++)if(I=String(Y._[S]),W.includes(I)&&I!==__classPrivateFieldGet(this,Ed,`f`)){let n=__classPrivateFieldGet(this,Sd,`f`).runCommand(I,this,q,S+1,F,te||ne||F);return this[Nf](n,H,!!C,!1)}else if(!n&&I!==__classPrivateFieldGet(this,Ed,`f`)){n=I;break}!__classPrivateFieldGet(this,Sd,`f`).hasDefaultCommand()&&__classPrivateFieldGet(this,Jd,`f`)&&n&&!ie&&__classPrivateFieldGet(this,nf,`f`).recommendCommands(n,W)}__classPrivateFieldGet(this,Ed,`f`)&&Y._.includes(__classPrivateFieldGet(this,Ed,`f`))&&!re&&(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),this.showCompletionScript(),this.exit(0))}if(__classPrivateFieldGet(this,Sd,`f`).hasDefaultCommand()&&!ie){let n=__classPrivateFieldGet(this,Sd,`f`).runCommand(null,this,q,0,F,te||ne||F);return this[Nf](n,H,!!C,!1)}if(re){__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),n=[].concat(n);let S=n.slice(n.indexOf(`--${__classPrivateFieldGet(this,Td,`f`).completionKey}`)+1);return __classPrivateFieldGet(this,Td,`f`).getCompletion(S,(n,S)=>{if(n)throw new ns(n.message);(S||[]).forEach(n=>{__classPrivateFieldGet(this,Rd,`f`).log(n)}),this.exit(0)}),this[Nf](Y,!H,!!C,!1)}if(__classPrivateFieldGet(this,Fd,`f`)||(te?(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),I=!0,this.showHelp(n=>{__classPrivateFieldGet(this,Rd,`f`).log(n),this.exit(0)})):ne&&(__classPrivateFieldGet(this,jd,`f`)&&setBlocking(!0),I=!0,__classPrivateFieldGet(this,$d,`f`).showVersion(`log`),this.exit(0))),!I&&__classPrivateFieldGet(this,Bd,`f`).skipValidation.length>0&&(I=Object.keys(Y).some(n=>__classPrivateFieldGet(this,Bd,`f`).skipValidation.indexOf(n)>=0&&Y[n]===!0)),!I){if(q.error)throw new ns(q.error.message);if(!re){let n=this[Lf](Z,{},q.error);C||(X=applyMiddleware(Y,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!0)),X=this[Cf](n,X??Y),isPromise(X)&&!C&&(X=X.then(()=>applyMiddleware(Y,this,__classPrivateFieldGet(this,Nd,`f`).getMiddleware(),!1)))}}}catch(n){if(n instanceof ns)__classPrivateFieldGet(this,$d,`f`).fail(n.message,n);else throw n}return this[Nf](X??Y,H,!!C,!0)}[Lf](n,S,C,N){let F={...this.getDemandedOptions()};return I=>{if(C)throw new ns(C.message);__classPrivateFieldGet(this,nf,`f`).nonOptionCount(I),__classPrivateFieldGet(this,nf,`f`).requiredArguments(I,F);let H=!1;__classPrivateFieldGet(this,Zd,`f`)&&(H=__classPrivateFieldGet(this,nf,`f`).unknownCommands(I)),__classPrivateFieldGet(this,Xd,`f`)&&!H?__classPrivateFieldGet(this,nf,`f`).unknownArguments(I,n,S,!!N):__classPrivateFieldGet(this,Qd,`f`)&&__classPrivateFieldGet(this,nf,`f`).unknownArguments(I,n,{},!1,!1),__classPrivateFieldGet(this,nf,`f`).limitedChoices(I),__classPrivateFieldGet(this,nf,`f`).implications(I),__classPrivateFieldGet(this,nf,`f`).conflicting(I)}}[Rf](){__classPrivateFieldSet(this,Fd,!0,`f`)}[zf](n){if(typeof n==`string`)__classPrivateFieldGet(this,Bd,`f`).key[n]=!0;else for(let S of n)__classPrivateFieldGet(this,Bd,`f`).key[S]=!0}}}),Hf,Uf=__esmMin(()=>{nd(),Vf(),Hf=YargsFactory(td)});function classifyCliFailure(n,S){return typeof n==`string`&&n.length>0?{kind:`usage`,message:n}:{kind:`runtime`}}var Wf=__esmMin(()=>{});function buildHeaders(n,S){let C={"user-agent":`gjsify-install/0.48.0`,"accept-encoding":S.acceptEncoding??`identity`};if(S.npmrc){let N=resolveAuthForUrl(n,S.npmrc);N&&(C.authorization=N)}if(S.headers)for(let[n,N]of Object.entries(S.headers))C[n.toLowerCase()]=N;return C}function resolveAuthForUrl(n,S){let C=pathPrefixes(new URL(n));for(let n of C){let C=S.authTokens[n];if(C)return`Bearer ${C}`;let N=S.basicAuth[n];if(N)return`Basic ${btoa(`${N.username}:${N.password}`)}`}return null}function pathPrefixes(n){let S=n.pathname.split(`/`).filter(Boolean),C=[];for(let N=S.length;N>=0;N--){let F=S.slice(0,N).join(`/`);C.push(F?`//${n.host}/${F}`:`//${n.host}`)}return C}var Gf=__esmMin(()=>{}),PackageNotFoundError,IntegrityError,RegistryTimeoutError,Kf=__esmMin(()=>{PackageNotFoundError=class extends Error{name;url;constructor(n,S){super(`Package not found in registry: ${n} (${S})`),this.name=n,this.url=S,this.name=`PackageNotFoundError`}},IntegrityError=class extends Error{url;integrity;constructor(n,S){super(`Tarball integrity mismatch for ${n} (expected ${S})`),this.url=n,this.integrity=S,this.name=`IntegrityError`}},RegistryTimeoutError=class extends Error{url;timeoutMs;attempts;constructor(n,S,C){let N=Math.round(S/100)/10,F=Math.round(S*C/100)/10;super(`@gjsify/npm-registry: GET ${n} timed out after ${N}s × ${C} attempt(s) (total ~${F}s). This usually means the registry CDN is slow or unreachable.`),this.url=n,this.timeoutMs=S,this.attempts=C,this.name=`RegistryTimeoutError`}}});function registryFor(n,S){if(S&&n.startsWith(`@`)){let C=n.slice(0,n.indexOf(`/`)),N=S.scopes[C];if(N)return ensureTrailingSlash$1(N)}return S?.registry?ensureTrailingSlash$1(S.registry):qf}function parseNpmrc(n){let S={registry:qf,scopes:{},authTokens:{},basicAuth:{}},C=n.split(/\r?\n/),N={};for(let n of C){let C=n.replace(/^\s+|\s+$/g,``);if(!C||C.startsWith(`#`)||C.startsWith(`;`))continue;let F=C.indexOf(`=`);if(F<0)continue;let I=C.slice(0,F).trim(),H=expandEnv(stripQuotes(C.slice(F+1).trim()));if(I===`registry`){S.registry=ensureTrailingSlash$1(H);continue}let W=I.match(/^(@[^:]+):registry$/);if(W){S.scopes[W[1]]=ensureTrailingSlash$1(H);continue}let q=I.match(/^\/\/(.+):_authToken$/);if(q){S.authTokens[normalizeAuthHost(q[1])]=H;continue}let Y=I.match(/^\/\/(.+):username$/);if(Y){(N[normalizeAuthHost(Y[1])]??={}).user=H;continue}let X=I.match(/^\/\/(.+):_password$/);if(X){let n=base64Decode$1(H);(N[normalizeAuthHost(X[1])]??={}).pass=n;continue}}for(let[n,C]of Object.entries(N))C.user&&C.pass!==void 0&&(S.basicAuth[n]={username:C.user,password:C.pass});return S}function normalizeAuthHost(n){return`//${n.replace(/\/+$/,``)}`}function ensureTrailingSlash$1(n){return n.endsWith(`/`)?n:n+`/`}function stripQuotes(n){return n.startsWith(`"`)&&n.endsWith(`"`)||n.startsWith(`'`)&&n.endsWith(`'`)?n.slice(1,-1):n}function expandEnv(n){return n.replace(/\$\{([A-Z0-9_]+)\}/gi,(n,S)=>globalThis.process?.env?.[S]??``)}function base64Decode$1(n){return atob(n)}var qf,Jf=__esmMin(()=>{qf=`https://registry.npmjs.org/`,__name$1(ensureTrailingSlash$1,`ensureTrailingSlash`),__name$1(base64Decode$1,`base64Decode`)});async function fetchWithRetry(n,S,C){let N=C.fetch??globalThis.fetch;if(!N)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let F=Math.max(0,C.retries??3),I=Math.max(0,C.retryDelayMs??250),H=Math.max(0,C.timeoutMs??3e4),W=C.retryNotFound??!1,q=0,Y,X=0;for(;;){if(S.signal?.aborted)throw signalAbortError(S.signal);let Z=H>0?new AbortController:null,te=Z===null?null:setTimeout(()=>Z.abort(Error(`@gjsify/npm-registry: per-request timeout ${H}ms`)),H),ne=composeSignals(S.signal,Z?.signal);try{let C=await N(n,{...S,signal:ne}),I=isRetryableStatus(C.status)||W&&C.status===404;if(C.ok||!I||q>=F)return C;try{await C.arrayBuffer()}catch{}Y=Error(`HTTP ${C.status} ${C.statusText}`)}catch(C){let N=Z!==null&&Z.signal.aborted,I=S.signal?.aborted===!0;if(N&&!I){if(X++,q>=F)throw new RegistryTimeoutError(n,H,X);Y=C}else if(I)throw signalAbortError(S.signal);else{if(!isRetryableError(C)||q>=F)throw C;Y=C}}finally{te!==null&&clearTimeout(te)}let re=Math.min(I*2**q,8e3);C.onRetry?.({attempt:q+1,error:Y,delayMs:re}),await delay$1(re,S.signal),q++}}function composeSignals(n,S){return n?S?AbortSignal.any([n,S]):n:S}function isRetryableStatus(n){return n===408||n===425||n===429||n===500||n===502||n===503||n===504||n===521||n===522||n===524||n===525}function isRetryableError(n){if(n&&typeof n==`object`&&`name`in n&&n.name===`AbortError`)return!1;if(n instanceof TypeError)return!0;if(n&&typeof n==`object`&&`name`in n){let S=n.name;if(S===`FetchError`)return!0;if(S===`AbortError`)return!1}let S=n?.cause;if(S&&typeof S==`object`&&`code`in S){let n=S.code;if(typeof n==`string`)return n===`ECONNRESET`||n===`ECONNREFUSED`||n===`ENETUNREACH`||n===`ENOTFOUND`||n===`ETIMEDOUT`||n===`EAI_AGAIN`||n===`UND_ERR_SOCKET`||n===`UND_ERR_CONNECT_TIMEOUT`}return!1}function delay$1(n,S){return n<=0?Promise.resolve():new Promise((C,N)=>{let F=setTimeout(()=>{S?.removeEventListener?.(`abort`,onAbort),C()},n),onAbort=()=>{clearTimeout(F),N(signalAbortError(S))};if(S?.aborted){clearTimeout(F),N(signalAbortError(S));return}S?.addEventListener?.(`abort`,onAbort,{once:!0})})}function signalAbortError(n){let S=n&&`reason`in n?n.reason:void 0;if(S instanceof Error)return S;let C=Error(`Aborted`);return C.name=`AbortError`,C}var Yf=__esmMin(()=>{Kf(),__name$1(delay$1,`delay`)});async function verifyIntegrity(n,S){let C=S.trim().split(/\s+/);for(let S of C){let C=S.indexOf(`-`);if(C<0)continue;let N=S.slice(0,C).toLowerCase(),F=S.slice(C+1),I=globalThis.crypto?.subtle;if(!I)throw Error(`@gjsify/npm-registry: globalThis.crypto.subtle is missing`);let H=subriToWebCryptoAlgo(N);if(!H)continue;let W=await I.digest(H,dataAsArrayBuffer(n));if(bytesToBase64(new Uint8Array(W))===F)return!0}return!1}function subriToWebCryptoAlgo(n){switch(n){case`sha1`:return`SHA-1`;case`sha256`:return`SHA-256`;case`sha384`:return`SHA-384`;case`sha512`:return`SHA-512`;default:return null}}function dataAsArrayBuffer(n){if(n.byteOffset===0&&n.byteLength===n.buffer.byteLength)return n.buffer;let S=new Uint8Array(n.byteLength);return S.set(n),S.buffer}function bytesToBase64(n){let S=``;for(let C=0;C<n.length;C++)S+=String.fromCharCode(n[C]);return btoa(S)}var Xf=__esmMin(()=>{});function assertPackument(n,S){if(!S||typeof S!=`object`)throw TypeError(`registry: ${n} packument is not an object`);let C=S;if(typeof C.name!=`string`)throw TypeError(`registry: ${n} packument missing string name`);if(!C.versions||typeof C.versions!=`object`)throw TypeError(`registry: ${n} packument missing versions map`)}function packumentUrl(n,S){let C=ensureTrailingSlash$1(S);if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S<0)throw TypeError(`Invalid scoped package name: ${n}`);let N=n.slice(0,S),F=n.slice(S+1);return`${C}${encodeURIComponent(N)}/${encodeURIComponent(F)}`}return`${C}${encodeURIComponent(n)}`}async function fetchPackumentConditional(n,S={}){let C=packumentUrl(n,S.registry??registryFor(n,S.npmrc)),N=buildHeaders(C,{...S,acceptEncoding:`gzip`});N.accept??=S.fullMetadata?`application/json`:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`,S.ifNoneMatch&&(N[`if-none-match`]=S.ifNoneMatch);let F=await fetchWithRetry(C,{headers:N,signal:S.signal},{fetch:S.fetch,retries:S.retries,retryDelayMs:S.retryDelayMs,timeoutMs:S.timeoutMs,onRetry:S.onRetry});if(F.status===304){try{await F.arrayBuffer()}catch{}return{status:`not-modified`,etag:S.ifNoneMatch}}if(!F.ok)throw F.status===404||F.status===406?new PackageNotFoundError(n,C):Error(`registry GET ${C} -> ${F.status} ${F.statusText}`);let I=F.headers.get(`etag`)??void 0,H=await decodeJsonBody(F);return assertPackument(n,H),{status:`fresh`,packument:H,etag:I}}async function decodeJsonBody(n){return n.json()}async function fetchPackument(n,S={}){let C=await fetchPackumentConditional(n,S);if(!C.packument)throw Error(`registry: ${n} returned 304 Not Modified to an unconditional request`);return C.packument}var Zf=__esmMin(()=>{Gf(),Kf(),Jf(),Yf()});async function fetchTarball(n,S={}){let C=buildHeaders(n,{...S,acceptEncoding:`identity`});C.accept??=`application/octet-stream`;let N=await fetchWithRetry(n,{headers:C,signal:S.signal},{fetch:S.fetch,retries:S.retries,retryDelayMs:S.retryDelayMs,timeoutMs:S.timeoutMs,onRetry:S.onRetry,retryNotFound:S.retryNotFound??!0});if(!N.ok)throw Error(`tarball GET ${n} -> ${N.status} ${N.statusText}`);let F=new Uint8Array(await N.arrayBuffer());if(S.integrity&&!await verifyIntegrity(F,S.integrity))throw new IntegrityError(n,S.integrity);return F}var Qf=__esmMin(()=>{Gf(),Kf(),Yf(),Xf()});async function whoami(n,S){let C=`${ensureTrailingSlash$1(n)}-/whoami`,N=buildHeaders(C,{npmrc:S});N.accept=`application/json`;let F=globalThis.fetch;if(!F)throw Error(`@gjsify/npm-registry: globalThis.fetch is missing`);let I=await F(C,{method:`GET`,headers:N});if(!I.ok)throw Error(`whoami GET ${C} -> ${I.status} ${I.statusText}`);let H=await I.json();if(H&&typeof H==`object`&&`username`in H){let n=H.username;if(typeof n==`string`&&n.length>0)return{username:n}}return{}}var $f=__esmMin(()=>{Gf(),Jf()}),ep=__esmMin(()=>{Gf(),Jf(),Zf(),Qf(),$f()});function escapePackageName(n){return n.replace(`/`,`%2f`)}function buildPublishHeaders(n,S){let C=buildHeaders(n,{npmrc:S.npmrc});return C[`content-type`]=`application/json`,C[`npm-command`]=`publish`,C[`npm-auth-type`]=S.otp?`legacy`:`web`,C[`user-agent`]=S.userAgent??defaultUserAgent(),S.otp&&(C[`npm-otp`]=S.otp),S.authorization&&(C.authorization=S.authorization),C}function cliVersion(){return tp===void 0&&(tp=`0.48.0`),tp}function cliPackageDir(){let n=globalThis.process?.env?.GJSIFY_CLI_PACKAGE_JSON,S;try{S=Ps(n||fileURLToPath(import.meta.url))}catch{return null}for(let n=0;n<12;n++){try{if(JSON.parse(readFileSync(`${S}/package.json`,`utf8`)).name===`@gjsify/cli`)return S}catch{}let n=Ps(S);if(n===S)break;S=n}return null}function defaultUserAgent(){let n=globalThis.process,S=n?.arch??`x64`,C=n?.platform??`linux`;return`gjsify-publish/${cliVersion()} (${C} ${S})`}var tp,np=__esmMin(()=>{Vl(),Hs(),gn(),ep()}),rp,ip=__esmMin(()=>{rp=`gjsify`}),ap=__commonJSMin(((n,S)=>{let C=(Hs(),__toCommonJS(Es)),N=(gs(),__toCommonJS(fs)),F=(Vl(),__toCommonJS(Rl)),resolveFrom=(n,S,I)=>{if(typeof n!=`string`)throw TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof n}\``);if(typeof S!=`string`)throw TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof S}\``);try{n=F.realpathSync(n)}catch(S){if(S.code===`ENOENT`)n=C.resolve(n);else if(I)return null;else throw S}let H=C.join(n,`noop.js`),resolveFileName=()=>N._resolveFilename(S,{id:H,filename:H,paths:N._nodeModulePaths(n)});if(I)try{return resolveFileName()}catch{return null}return resolveFileName()};S.exports=(n,S)=>resolveFrom(n,S),S.exports.silent=(n,S)=>resolveFrom(n,S,!0)})),op=__commonJSMin(((n,S)=>{let callsites=()=>{let n=Error.prepareStackTrace;Error.prepareStackTrace=(n,S)=>S;let S=Error().stack.slice(1);return Error.prepareStackTrace=n,S};S.exports=callsites,S.exports.default=callsites})),sp=__commonJSMin(((n,S)=>{let C=op();S.exports=n=>{let S=C();if(!n)return S[2].getFileName();let N=!1;S.shift();for(let C of S){let S=C.getFileName();if(typeof S==`string`){if(S===n){N=!0;continue}if(S!==`module.js`&&N&&S!==n)return S}}}})),lp=__commonJSMin(((n,S)=>{var{__gjsifyModuleDir:C,__gjsifyModuleFile:N}=(Ks(),__toCommonJS(Us)),F=C(`import-fresh/index.js`),I=N(`import-fresh/index.js`);let H=(Hs(),__toCommonJS(Es)),W=ap(),q=sp();S.exports=n=>{if(typeof n!=`string`)throw TypeError(`Expected a string`);let S=q(I),C=S?H.dirname(S):F,N=W(C,n),Y=X.cache[N];if(Y&&Y.parent){let n=Y.parent.children.length;for(;n--;)Y.parent.children[n].id===N&&Y.parent.children.splice(n,1)}delete X.cache[N];let Z=X.cache[S];return Z===void 0||Z.require===void 0?X(N):Z.require(N)}})),up=__commonJSMin(((n,S)=>{S.exports=function isArrayish(n){return n?n instanceof Array||Array.isArray(n)||n.length>=0&&n.splice instanceof Function:!1}})),dp=__commonJSMin(((n,S)=>{var C=(Ac(),__toCommonJS(Ec)),N=up(),F=function errorEx(n,S){(!n||n.constructor!==String)&&(S=n||{},n=Error.name);var F=function ErrorEXError(C){if(!this)return new ErrorEXError(C);C=C instanceof Error?C.message:C||this.message,Error.call(this,C),Error.captureStackTrace(this,F),this.name=n,Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,get:function(){var n=C.split(/\r?\n/g);for(var F in S)if(S.hasOwnProperty(F)){var I=S[F];`message`in I&&(n=I.message(this[F],n)||n,N(n)||(n=[n]))}return n.join(`
|
|
123
123
|
`)},set:function(n){C=n}});var I=null,H=Object.getOwnPropertyDescriptor(this,`stack`),W=H.get,q=H.value;delete H.value,delete H.writable,H.set=function(n){I=n},H.get=function(){var n=(I||(W?W.call(this):q)).split(/\r?\n+/g);I||(n[0]=this.name+`: `+this.message);var C=1;for(var N in S)if(S.hasOwnProperty(N)){var F=S[N];if(`line`in F){var H=F.line(this[N]);H&&n.splice(C++,0,` `+H)}`stack`in F&&F.stack(this[N],n)}return n.join(`
|
|
124
124
|
`)},Object.defineProperty(this,"stack",H)};return Object.setPrototypeOf?(Object.setPrototypeOf(F.prototype,Error.prototype),Object.setPrototypeOf(F,Error)):C.inherits(F,Error),F};F.append=function(n,S){return{message:function(C,N){return C||=S,C&&(N[0]+=` `+n.replace(`%s`,C.toString())),N}}},F.line=function(n,S){return{line:function(C){return C||=S,C?n.replace(`%s`,C.toString()):null}}},S.exports=F})),fp=__commonJSMin(((n,S)=>{let hexify=n=>{let S=n.charCodeAt(0).toString(16).toUpperCase();return`0x`+(S.length%2?`0`:``)+S},parseError=(n,S,C)=>{if(!S)return{message:n.message+` while parsing empty string`,position:0};let N=n.message.match(/^Unexpected token (.) .*position\s+(\d+)/i),F=N?+N[2]:n.message.match(/^Unexpected end of JSON.*/i)?S.length-1:null,I=N?n.message.replace(/^Unexpected token ./,`Unexpected token ${JSON.stringify(N[1])} (${hexify(N[1])})`):n.message;if(F!=null){let n=F<=C?0:F-C,N=F+C>=S.length?S.length:F+C,H=(n===0?``:`...`)+S.slice(n,N)+(N===S.length?``:`...`);return{message:I+` while parsing ${S===H?``:`near `}${JSON.stringify(H)}`,position:F}}else return{message:I+` while parsing '${S.slice(0,C*2)}'`,position:0}};var JSONParseError=class extends SyntaxError{constructor(n,S,C,N){C||=20;let F=parseError(n,S,C);super(F.message),Object.assign(this,F),this.code=`EJSONPARSE`,this.systemError=n,Error.captureStackTrace(this,N||this.constructor)}get name(){return this.constructor.name}set name(n){}get[Symbol.toStringTag](){return this.constructor.name}};let C=Symbol.for(`indent`),N=Symbol.for(`newline`),F=/^\s*[{\[]((?:\r?\n)+)([\s\t]*)/,I=/^(?:\{\}|\[\])((?:\r?\n)+)?$/,parseJson=(n,S,H)=>{let W=stripBOM(n);H||=20;try{let[,n=`
|
|
125
125
|
`,H=` `]=W.match(I)||W.match(F)||[,``,``],q=JSON.parse(W,S);return q&&typeof q==`object`&&(q[N]=n,q[C]=H),q}catch(S){if(typeof n!=`string`&&!Buffer.isBuffer(n)){let C=Array.isArray(n)&&n.length===0;throw Object.assign(TypeError(`Cannot parse ${C?`an empty array`:String(n)}`),{code:`EJSONPARSE`,systemError:S})}throw new JSONParseError(S,W,H,parseJson)}},stripBOM=n=>String(n).replace(/^\uFEFF/,``);S.exports=parseJson,parseJson.JSONParseError=JSONParseError,parseJson.noExceptions=(n,S)=>{try{return JSON.parse(stripBOM(n),S)}catch{}}})),pp=__commonJSMin((n=>{n.__esModule=!0,n.LinesAndColumns=void 0;var S=`
|
|
@@ -801,19 +801,19 @@ Configure one of:
|
|
|
801
801
|
[gjsify build --watch] stopping watcher…`);try{await I.close()}catch(n){ve.error(`[gjsify build --watch] watcher close error:`,n)}}};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),I.on(`event`,async n=>{switch(n.code){case`START`:F&&ve.log(`[gjsify build --watch] rebuild start`);break;case`BUNDLE_START`:ve.log(`[gjsify build --watch] building…`);break;case`BUNDLE_END`:ve.log(`[gjsify build --watch] built in ${n.duration}ms`);try{S===`gjs`&&await this.escapeRawNul(C,N,F),(S===`gjs`||S===`node`)&&this.configData.shebang&&await this.applyShebang(S,C,F)}finally{await n.result.close()}break;case`END`:ve.log(`[gjsify build --watch] waiting for changes…`);break;case`ERROR`:ve.error(`[gjsify build --watch] build failed:`,n.error?.message??n.error),F&&n.error?.stack&&ve.error(n.error.stack);try{await n.result.close()}catch{}break}}),F&&I.on(`change`,(n,S)=>{ve.log(`[gjsify build --watch] ${S.event}: ${n}`)}),await H}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})}}});function isModuleResolutionFailure(n){let S=n instanceof Error?n.message:String(n);return/Unsupported URI scheme|\bnode:|Cannot find (module|package)|Module not found|ERR_MODULE_NOT_FOUND|Failed to resolve/i.test(S)}async function loadConfigViaGjsBundle(n,S){let C;try{let{BuildAction:N}=await Promise.resolve().then(()=>($N(),YN));C=await N.bundleFileForGjsCached(n,{cacheSubdir:`config`,label:Fs(n),verbose:S,noCacheEnv:`GJSIFY_NO_CONFIG_CACHE`,define:{"import.meta.url":JSON.stringify(pathToFileURL(n).href)},resolveFromToolchain:!0})}catch(S){throw Error(`gjsify: failed to bundle the config ${n} for the GJS CLI. Fixes: run the build under Node (\`npx gjsify …\`), keep the config to plain values / \`process.env\`, or move settings into \`package.json#gjsify\`. (${S.message})`)}try{let n=await import(pathToFileURL(C).href);return n.default??n}catch(S){throw Error(`gjsify: bundled the config ${n} for GJS but could not import the result (${C}). (${S.message})`)}}function defaultSearchPlaces(n){return[`package.json`,`.${n}rc`,`.${n}rc.json`,`.${n}rc.yaml`,`.${n}rc.yml`,`.${n}rc.js`,`.${n}rc.ts`,`.${n}rc.mjs`,`.${n}rc.cjs`,`${n}.config.js`,`${n}.config.ts`,`${n}.config.mjs`,`${n}.config.cjs`]}function merge(n,...S){for(let C of S)if(C)for(let S of Object.keys(C)){let N=n[S],F=C[S];F!==void 0&&(isPlainObject(N)&&isPlainObject(F)?merge(N,F):n[S]=F)}return n}function isPlainObject(n){return typeof n==`object`&&!!n&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype}function readDottedPath(n,S){if(!S.includes(`.`))return n[S];let C=n;for(let n of S.split(`.`)){if(typeof C!=`object`||!C)return;C=C[n]}return C}var eP,gjsConfigLoader,tP,Config,nP=__esmMin(()=>{ye(),ip(),eP=eh(),Hs(),gn(),th(),Ah(),_A(),Sj(),BM(),gjsConfigLoader=async n=>{try{let S=await import(pathToFileURL(n).href);return S.default??S}catch(S){if(!isModuleResolutionFailure(S))throw S;return loadConfigViaGjsBundle(n,!!process.env.GJSIFY_DEBUG)}},tP=isGjs()?{".js":gjsConfigLoader,".mjs":gjsConfigLoader,".cjs":gjsConfigLoader}:{},Config=class{loadOptions={};constructor(n={}){Object.keys(n).length&&(this.loadOptions=n)}async load(n){let S=await(0,eP.cosmiconfig)(rp,{...this.loadOptions,searchPlaces:(this.loadOptions.searchPlaces??defaultSearchPlaces(`gjsify`)).filter(n=>n!==`package.json`),loaders:{...tP,...this.loadOptions.loaders}}).search(n),C={};try{let S=await this.readPackageJSON(n);isPlainObject(S?.gjsify)&&merge(C,S.gjsify)}catch{}return S?.config&&isPlainObject(S.config)&&merge(C,S.config),C.bundler||={},C.library||={},C.typescript||={},{config:C,filepath:S?.filepath??``,isEmpty:!S&&Object.keys(C).length===3}}async readPackageJSON(n){return n=await resolvePackageJSON(n),await readPackageJSON(n)}async readTSConfig(n){return PM(n)?.config||{}}async forNodeScript(n){let{config:S}=await this.load(Ps(n));return{globals:S.nodeScript?.globals??S.globals,excludeGlobals:S.nodeScript?.excludeGlobals??S.excludeGlobals}}async forCommand(n=process.cwd()){let{config:S}=await this.load(n);return S}async forBuild(n){let S=await this.load(process.cwd()),C={...S.config},N=S.filepath||process.cwd(),F=await this.readPackageJSON(N),I=await this.readTSConfig(N);if(I.reflection||=n.reflection,C.verbose=n.verbose||n.logLevel===`debug`||n.logLevel===`verbose`,C.exclude=n.exclude||[],n.consoleShim!==void 0&&(C.consoleShim=n.consoleShim),n.dialect!==void 0){if(!isSourceDialect(n.dialect))throw Error(`gjsify build: "${n.dialect}" is not a source dialect. Known: ${jh.join(`, `)}. This is the dialect the SOURCE is written in — not gjsify.runtimes, which declares the runtime a package RUNS on.`);C.dialect=n.dialect}if(n.app!==void 0&&(C.app=n.app),C.app??=buildAppForRuntime(hostRuntime$1()),C.dialect!==void 0&&!Mh.has(C.app))throw Error(`gjsify build: --dialect ${C.dialect} has no effect on --app ${C.app}. It composes on ${[...Mh].join(` and `)} only. Drop the dialect, or build one of those targets.`);if(n.globals!==void 0&&(C.globals=n.globals),C.globals??=`auto`,n.shebang!==void 0&&(C.shebang=n.shebang),n.excludeGlobals){let S=(Array.isArray(n.excludeGlobals)?n.excludeGlobals.join(`,`):String(n.excludeGlobals)).split(`,`).map(n=>n.trim()).filter(Boolean);S.length&&(C.excludeGlobals=[...C.excludeGlobals??[],...S])}merge(C.library??={},F,C.library),merge(C.typescript??={},I,C.typescript);let parseKvPairs=(n,S)=>{let C={};for(let N of n){let n=N.indexOf(`=`);if(n===-1)throw Error(`Invalid --${S} value '${N}'. Expected KEY=VALUE.`);let F=N.slice(0,n).trim(),I=N.slice(n+1);if(!F)throw Error(`Invalid --${S} value '${N}'. Empty key.`);C[F]=I}return C},H=parseKvPairs(n.define??[],`define`),W=parseKvPairs(n.alias??[],`alias`);Object.keys(W).length&&(C.aliases={...C.aliases,...W});let q={};if(C.defineFromPackageJson)for(let[n,S]of Object.entries(C.defineFromPackageJson)){if(!S||typeof S.field!=`string`||!S.field)throw Error(`gjsify config: defineFromPackageJson["${n}"] is missing a "field" string`);let C=readDottedPath(F,S.field);q[n]=C===void 0?`undefined`:JSON.stringify(C)}let Y={};if(C.defineFromEnv)for(let[n,S]of Object.entries(C.defineFromEnv)){if(!S||typeof S.env!=`string`||!S.env)throw Error(`gjsify config: defineFromEnv["${n}"] is missing an "env" string`);let C=process.env[S.env],N=C===void 0?S.default:C;Y[n]=N===void 0?`undefined`:JSON.stringify(N)}let X=C.bundler??={},Z=X.output??={},te=X.transform??={};return n.entryPoints?.length&&(X.input=n.entryPoints),X.input||=[`src/index.ts`],n.outfile!==void 0&&(Z.file=n.outfile),n.outdir!==void 0&&(Z.dir=n.outdir),n.format!==void 0&&(Z.format=n.format),n.minify!==void 0&&(Z.minify=n.minify),Z.minify===void 0&&(Z.minify=!0),Z.minify===!0&&(Z.keepNames=!0),n.logLevel&&(X.logLevel={silent:`silent`,error:`warn`,warning:`warn`,warn:`warn`,info:`info`,debug:`debug`,verbose:`debug`}[n.logLevel]??`warn`),n.external?.length&&(X.external=[...Array.isArray(X.external)?X.external:[],...n.external]),(Object.keys(H).length||Object.keys(q).length||Object.keys(Y).length)&&(te.define={...te.define,...q,...Y,...H}),C.verbose&&ve.debug(`configData`,C),C}}}),rP,iP=__esmMin(()=>{nP(),$N(),_A(),rP={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`,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`,default:[]}).option(`verbose`,{description:`Switch on the verbose mode`,type:`boolean`,default:!1}).option(`app`,{description:"Build target for an application. Defaults to the target of the HOST runtime running the CLI: gjs when run under gjs, node when run under node/bun/deno (both consume the --app node bundle). Set `gjsify.app` in package.json#gjsify to override the host default.",type:`string`,choices:[`gjs`,`node`,`browser`,`nativescript`],defaultDescription:`host runtime target (gjs on gjs, else node)`}).option(`format`,{description:`Override the default output format`,type:`string`,choices:[`iife`,`esm`,`cjs`]}).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`,defaultDescription:`true`}).option(`library`,{description:`Use this if you want to build a library for Gjsify`,type:`boolean`,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`,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`],default:`warning`}).option(`dialect`,{description:`The dialect the SOURCE is written in. 'react-native' aliases 'react-native' onto '@gjsify/react-native' and fails the build on an import whose ADR 0032 support-table status is not supported/partial. GJS and Node app builds. This is NOT gjsify.runtimes['react-native'], which declares the runtime a package RUNS on — the two answer opposite questions.`,type:`string`,choices:[...jh]}).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`,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`}).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`}).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`}).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`,default:!1}),handler:async n=>{let S=await new Config().forBuild(n);await new QN(S).start({library:n.library,app:S.app,watch:n.watch})}}});function hasWildcard(n){return n.includes(`*`)||n.includes(`?`)}function segmentToRegExp(n){let S=n.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/\\\\]*`).replace(/\?/g,`[^/\\\\]`);return RegExp(`^${S}$`)}function assertInsideCwd(n,S,C){let N=Ms(C,n);if(N===``)throw Error(`gjsify clear: refusing to delete the working directory itself ("${S}").`);if(N===`..`||N.startsWith(`..${zs}`)||As(N))throw Error(`gjsify clear: "${S}" resolves to ${n}, outside the working directory ${C}. Only paths inside the package may be cleared.`)}function resolveClearTargets(n,S){let C=[],N=new Set;for(let F of n)for(let n of expandTarget(F,S))assertInsideCwd(n,F,S.cwd),!N.has(n)&&(N.add(n),C.push(n));return C}function expandTarget(n,S){let C=Fs(n),N=Ps(n);if(hasWildcard(N))throw Error(`gjsify clear: a wildcard is only supported in the last path segment — got "${n}".`);if(!hasWildcard(C))return[Os(S.cwd,n)];let F=Os(S.cwd,N);assertInsideCwdOrSelf(F,n,S.cwd);let I=segmentToRegExp(C),H;try{H=S.readdir(F)}catch{return[]}return H.filter(n=>I.test(n)).sort().map(n=>js(F,n))}function assertInsideCwdOrSelf(n,S,C){Ms(C,n)!==``&&assertInsideCwd(n,S,C)}var aP=__esmMin(()=>{Hs()}),oP,sP=__esmMin(()=>{ye(),Cl(),Vl(),Hs(),aP(),oP={command:`clear [paths..]`,description:"Delete build output recursively. Portable replacement for `rm -rf` in package `clear` scripts.",builder:n=>n.positional(`paths`,{description:"Files and directories to delete, relative to the current package. A missing path is not an error. `*` and `?` are honoured in the last segment.",type:`string`,array:!0}).option(`dry-run`,{description:`Print what would be deleted and exit without touching anything.`,type:`boolean`,default:!1}).option(`verbose`,{alias:`v`,description:`Print each path as it is deleted.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=n.paths??[];if(C.length===0)throw Error(`gjsify clear: no paths given. Usage: gjsify clear <paths…>`);let N=resolveClearTargets(C,{cwd:S,readdir:readdirSync});for(let C of N){let N=Ms(S,C);if(n.dryRun){let n=await stat$1(C).then(()=>!0,()=>!1);ve.log(`gjsify clear: would remove ${N}${n?``:` (absent)`}`);continue}await rm$1(C,{recursive:!0,force:!0,maxRetries:3,retryDelay:100}),n.verbose&&ve.log(`gjsify clear: removed ${N}`)}}}});function isDirectoryDestination(n,S){return S.endsWith(`/`)||S.endsWith(`\\`)||n.length>1?!0:n.some(n=>hasWildcard(n))}function assertWritableDestination(n,S,C,N){let F=Ms(C,n);if(F===``){if(N)return;throw Error(`gjsify copy: "${S}" is the working directory itself. Name a file, or add a trailing "/" to copy INTO the directory.`)}if(F===`..`||F.startsWith(`..${zs}`)||As(F))throw Error(`gjsify copy: "${S}" resolves to ${n}, outside the working directory ${C}. Only paths inside the package may be written.`)}function expandSource(n,S){let C=Fs(n),N=Ps(n);if(hasWildcard(N))throw Error(`gjsify copy: a wildcard is only supported in the last path segment — got "${n}".`);if(!hasWildcard(C))return[Os(S.cwd,n)];let F=Os(S.cwd,N),I=segmentToRegExp(C),H;try{H=S.readdir(F)}catch{return[]}return H.filter(n=>I.test(n)).sort().map(n=>js(F,n))}function planCopy(n,S){if(n.length<2)throw Error(`gjsify copy: needs at least one source and a destination. Usage: gjsify copy <sources…> <dest>`);let C=n.slice(0,-1),N=n[n.length-1];if(N===``)throw Error(`gjsify copy: the destination is empty.`);let F=isDirectoryDestination(C,N),I=Os(S.cwd,N);assertWritableDestination(I,N,S.cwd,F);let H=[];for(let n of C){if(n===``)throw Error(`gjsify copy: a source path is empty.`);H.push(...expandSource(n,S))}if(!F&&H.length!==1)throw Error(`gjsify copy: "${N}" names a single destination, but ${H.length} sources resolved.`);let W=[],q=new Set;for(let n of H){let S=F?js(I,Fs(n)):I;if(n===S)throw Error(`gjsify copy: "${n}" is its own destination.`);if(q.has(S))throw Error(`gjsify copy: two sources would both be written to ${S}.`);q.add(S),W.push({from:n,to:S})}return W}var cP=__esmMin(()=>{Hs(),aP()}),lP,uP=__esmMin(()=>{ye(),Cl(),Vl(),Hs(),cP(),lP={command:`copy [paths..]`,description:"Copy files and directories into the build output. Portable replacement for `mkdir -p` + `cp -r` in package scripts.",builder:n=>n.positional(`paths`,{description:'One or more sources followed by the destination. The destination is a DIRECTORY when it ends with "/", when several sources are given, or when a source carries a wildcard; otherwise it is the exact target path. Missing parent directories are created. `*` and `?` are honoured in the last segment of a source.',type:`string`,array:!0}).option(`dry-run`,{description:`Print what would be copied and exit without touching anything.`,type:`boolean`,default:!1}).option(`verbose`,{alias:`v`,description:`Print each path as it is copied.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=n.paths??[];if(C.length<2)throw Error(`gjsify copy: needs at least one source and a destination. Usage: gjsify copy <sources…> <dest>`);let N=planCopy(C,{cwd:S,readdir:readdirSync}),show=n=>{let C=Ms(S,n);return C===``?`.`:C};for(let{from:S,to:C}of N){if(n.dryRun){ve.log(`gjsify copy: would copy ${show(S)} -> ${show(C)}`);continue}await mkdir$1(Ps(C),{recursive:!0}),await cpPromises(S,C,{recursive:!0,force:!0}),n.verbose&&ve.log(`gjsify copy: ${show(S)} -> ${show(C)}`)}}}});function lookupEnv(n,S){let C=S.toLowerCase();for(let S of Object.keys(n))if(S.toLowerCase()===C&&n[S]!==void 0)return n[S]}function escapeCmdCommand(n){return n.replace(mP,`^$1`)}function escapeCmdArgument(n,S=!1){let C=`${n}`;return C=C.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`),C=C.replace(/(?=(\\+?)?)\1$/,`$1$1`),C=`"${C}"`,C=C.replace(mP,`^$1`),S&&(C=C.replace(mP,`^$1`)),C}function buildCmdExeInvocation(n,S,C=`cmd.exe`){let N=pP.test(n);return{cmd:C,args:[`/d`,`/s`,`/c`,`"${[escapeCmdCommand(n),...S.map(n=>escapeCmdArgument(n,N))].join(` `)}"`],windowsVerbatimArguments:!0}}function isBareName(n){return!n.includes(`/`)&&!n.includes(`\\`)&&!/\.[^.]+$/.test(n)}function lookupOnPath(n,S){let C=(lookupEnv(S.env,`PATH`)??``).split(`;`).filter(Boolean),N=(lookupEnv(S.env,`PATHEXT`)??dP).split(`;`).filter(Boolean);for(let F of C)for(let C of N){let N=S.join(F,n+C);if(S.exists(N))return N}}function resolveWin32Command(n,S,C){if(C.platform!==`win32`||!isBareName(n))return;let N=lookupOnPath(n,C);if(N)return fP.test(N)?{cmd:N,args:[...S]}:buildCmdExeInvocation(N,S,lookupEnv(C.env,`COMSPEC`)??`cmd.exe`)}var dP,fP,pP,mP,hP=__esmMin(()=>{dP=`.COM;.EXE;.BAT;.CMD`,fP=/\.(?:com|exe)$/i,pP=/node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i,mP=/([()\][%!^"`<>&|;, *?])/g});function resolveEnv(n){if(!n.color)return n.env;let S=n.env??process.env,C=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`};return{...S,...C}}function forWin32(n,S,C){return resolveWin32Command(n,S,{platform:process.platform,env:C??process.env,exists:existsSync,join:js})??{cmd:n,args:[...S]}}function mapSpawnError(n,S){return n.code===`ENOENT`&&S.notFound?S.notFound(n):n}function mustBlock(n){return isGjs()&&n.completion===`return`}function spawnToCompletion(n,S,C){let N=resolveEnv(C),F=C.shell?{cmd:n,args:[...S],windowsVerbatimArguments:!1}:forWin32(n,S,N);if(mustBlock(C)){let n=spawnSync(F.cmd,F.args,{stdio:[`inherit`,`pipe`,`pipe`],cwd:C.cwd,env:N,shell:C.shell,maxBuffer:C.maxBuffer??gP,windowsVerbatimArguments:F.windowsVerbatimArguments});if(n.error)return Promise.reject(mapSpawnError(n.error,C));if(C.stdio===`capture`)return Promise.resolve({code:n.status,signal:n.signal??null,stdout:String(n.stdout??``),stderr:String(n.stderr??``)});let S=C.stdio===`inherit-stderr`?process.stderr:process.stdout;return n.stdout&&n.stdout.length>0&&S.write(n.stdout),n.stderr&&n.stderr.length>0&&process.stderr.write(n.stderr),Promise.resolve({code:n.status,signal:n.signal??null})}return new Promise((n,S)=>{let I=F,H={cwd:C.cwd,stdio:C.stdio===`pipe`?[`ignore`,`pipe`,`pipe`]:C.stdio===`capture`?[`inherit`,`pipe`,`pipe`]:C.stdio===`inherit-stderr`?[`inherit`,2,2]:`inherit`};C.shell&&(H.shell=!0),N&&(H.env=N),I.windowsVerbatimArguments&&(H.windowsVerbatimArguments=!0);let W=spawn(I.cmd,I.args,H);C.onSpawn?.(W);let q;if(C.stdio===`capture`){let n={stdout:``,stderr:``};q=n,W.stdout?.on(`data`,S=>n.stdout+=String(S)),W.stderr?.on(`data`,S=>n.stderr+=String(S))}W.on(`close`,(S,C)=>{n(q?{code:S,signal:C,...q}:{code:S,signal:C})}),W.on(`error`,n=>{S(mapSpawnError(n,C))})})}function describeExit(n){return n.signal===null?`code ${n.code}`:`signal ${n.signal}`}var gP,_P=__esmMin(()=>{Dh(),Vl(),Hs(),th(),hP(),gP=64*1024*1024}),vP=__exportAll$4({computeNativeEnvForBundle:()=>computeNativeEnvForBundle,runGjsBundle:()=>runGjsBundle});function computeNativeEnvForBundle(n,S=process.cwd(),C=process.env){let N=Os(n),F=detectNativePackages(S),I=detectNativePackages(Ps(N)),H=new Set(F.map(n=>n.name)),W=buildNativeEnv([...F,...I.filter(n=>!H.has(n.name))],{env:C});return{env:W,envPrefix:Object.entries(W).filter(([n,S])=>S!==void 0&&S!==``&&S!==C[n]).map(([n,S])=>`${n}=${S}`).join(` `)}}async function runGjsBundle(n,S=[],C){let{env:N,envPrefix:F}=computeNativeEnvForBundle(n),I={...process.env,...N},H=[`-m`,n,...S],W=[`gjs`,...H.map(n=>n.includes(` `)?`"${n}"`:n)].join(` `);C.quiet||ve.error(`$ ${F?`${F} `:``}${W}`);let failed=n=>(process.exitCode=n,process.exit(n)),q;try{q=await spawnToCompletion(`gjs`,H,{completion:C.completion,env:I})}catch(n){return ve.error(n.message),failed(1)}if(q.code!==0)return ve.error(`gjs exited with ${describeExit(q)}`),failed(q.code??1);if(C.exitOnSuccess)return process.exit(0)}var yP=__esmMin(()=>{ye(),Hs(),gN(),_P()}),bP=__exportAll$4({bundleRequiresNodeGi:()=>bundleRequiresNodeGi,nodeBinary:()=>nodeBinary,resolveNodeGi:()=>resolveNodeGi,resolveNodeGiForBundle:()=>resolveNodeGiForBundle,runNodeBundle:()=>runNodeBundle,runRuntimeBundle:()=>runRuntimeBundle});function resolveNodeGi(n){let S=Os(n);for(;;){if(existsSync(js(S,`node_modules`,`@gjsify`,`node-gi`,`package.json`)))return js(S,`node_modules`,`@gjsify`,`node-gi`);let n=Os(S,`..`);if(n===S)return null;S=n}}function resolveNodeGiForBundle(n,S){return resolveNodeGi(Ps(Os(n)))??resolveNodeGi(S)}function nodeBinary(){return isNode()&&process.execPath?process.execPath:`node`}async function runNodeBundle(n,S=[],C){let N=process.cwd();if(!resolveNodeGiForBundle(n,N))throw Error(`Cannot run the storybook on Node: \`@gjsify/node-gi\` is not installed.
|
|
802
802
|
Add @gjsify/node-gi as a dependency to run the storybook on Node, e.g.:
|
|
803
803
|
"devDependencies": { "@gjsify/node-gi": "^0.13.0" }`);let{env:F,envPrefix:I}=computeNativeEnvForBundle(n,N),H={...process.env,...F},W=nodeBinary(),q=[n,...S],Y=[W,...q.map(n=>n.includes(` `)?`"${n}"`:n)].join(` `);ve.error(`$ ${I?`${I} `:``}${Y}`);let X;try{X=await spawnToCompletion(W,q,{completion:C.completion,env:H})}catch(n){return ve.error(n.message),process.exit(1)}if(X.code!==0)return ve.error(`node exited with ${describeExit(X)}`),process.exit(X.code??1);if(C.exitOnSuccess)return process.exit(0)}function bundleRequiresNodeGi(n){try{return readFileSync(n,`utf-8`).includes(`@gjsify/node-gi`)}catch{return!1}}async function runRuntimeBundle(n,S,C=[],N){let F=process.cwd(),I=Os(S);if(bundleRequiresNodeGi(I)&&!resolveNodeGiForBundle(I,F))throw Error(`Cannot run this bundle on ${n}: it uses gi:// via \`@gjsify/node-gi\`, which is not installed.\nAdd @gjsify/node-gi as a dependency to run gi:// code off GJS, e.g.:
|
|
804
|
-
"dependencies": { "@gjsify/node-gi": "^0.13.0" }`);let{env:H,envPrefix:W}=computeNativeEnvForBundle(I,F),q={...process.env,...H},[,Y]=kh[n].launch(I,C),X=n===`node`?nodeBinary():kh[n].probe,Z=[X,...Y.map(n=>n.includes(` `)?`"${n}"`:n)].join(` `);N.quiet||ve.error(`$ ${W?`${W} `:``}${Z}`);let failed=n=>(process.exitCode=n,process.exit(n)),te;try{te=await spawnToCompletion(X,Y,{completion:N.completion,env:q})}catch(n){return ve.error(n.message),failed(1)}if(te.code!==0)return ve.error(`${n} exited with ${describeExit(te)}`),failed(te.code??1);if(N.exitOnSuccess)return process.exit(0)}var xP=__esmMin(()=>{ye(),Vl(),Hs(),th(),yP(),Ah(),_P()});async function buildTestBundle(n,S,C,N){let F=await new Config().forBuild({entryPoints:[n],outfile:S,app:C,verbose:N??!1,logLevel:`warning`,exclude:[]});F.library={...F.library},F.bundler={...F.bundler,input:[n],output:{...F.bundler?.output,file:S}},await new QN(F).start({app:C,library:!1})}async function runTestBundle(n,S){if(S===`gjs`){await runGjsBundle(n,[],{completion:`exit`});return}let C=await spawnToCompletion(nodeBinary(),[n],{completion:`exit`});if(C.code!==0)throw Error(`node exited with ${describeExit(C)}`)}function isFresh(n,S){if(!existsSync(n))return!1;let C=statSync(n).mtimeMs,N=Ps(S);try{return C>=newestMtimeUnder(existsSync(N)?N:S)}catch{return!1}}function newestMtimeUnder(n){let S=statSync(n);if(S.isFile())return S.mtimeMs;let C=S.mtimeMs;for(let S of readdirSync(n,{withFileTypes:!0})){if(S.name===`node_modules`||S.name===`dist`||S.name===`lib`||S.name.startsWith(`.`))continue;let N=newestMtimeUnder(js(n,S.name));N>C&&(C=N)}return C}var SP,CP=__esmMin(()=>{ye(),Vl(),Hs(),Ah(),xP(),_P(),nP(),$N(),yP(),SP={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 S=process.cwd(),C=(await new Config().forBuild({}).catch(()=>({}))).test??{},N=Os(S,n.entry??C.entry??`src/test.mts`),F=Os(S,n.outdir??C.outdir??`dist`);if(!existsSync(N))return ve.error(`[gjsify test] no test entry at ${Ms(S,N)} — add an \`src/test.mts\` that aggregates your \`@gjsify/unit\` suites, or set \`gjsify.test.entry\` in package.json.`),process.exit(1);let I=n.runtime===`gjs`||n.runtime===`node`,H=n.runtime===`gjs`?[`gjs`]:n.runtime===`node`?[`node`]:C.runtimes&&C.runtimes.length>0?C.runtimes:[`gjs`,`node`],W=I?H:H.filter(n=>isRuntimeAvailable(n));for(let n of H.filter(n=>!W.includes(n)))ve.log(`[gjsify test] skipping ${n} — no \`${kh[n].probe}\` on PATH (not requested explicitly)`);if(W.length===0)return ve.error(`[gjsify test] none of the default runtimes (${H.join(`, `)}) is available on this host.\n Install one, or pin the set: \`gjsify test --runtime <rt>\` / \`gjsify.test.runtimes\` in package.json.`),process.exit(1);let q=[];for(let C of W){let I=js(F,`test.${C}.mjs`);if(n.build!==!1)if(n.rebuild||!isFresh(I,N)){let F=Date.now();n.verbose&&ve.log(`[gjsify test] building → ${Ms(S,I)} (—app ${C})`);try{await buildTestBundle(N,I,C,n.verbose),n.verbose&&ve.log(`[gjsify test] built ${C} in ${Date.now()-F}ms`)}catch(n){ve.error(`[gjsify test] build failed for ${C}:`,n.message),q.push({runtime:C,ok:!1,durationMs:0,error:`build failed`});continue}}else n.verbose&&ve.log(`[gjsify test] ${C}: bundle is up-to-date — skipping build (use --rebuild to force)`);else if(!existsSync(I)){ve.error(`[gjsify test] --no-build but ${Ms(S,I)} doesn't exist. Build first or drop --no-build.`),q.push({runtime:C,ok:!1,durationMs:0,error:`no bundle`});continue}let H=Date.now();try{await runTestBundle(I,C),q.push({runtime:C,ok:!0,durationMs:Date.now()-H})}catch(n){q.push({runtime:C,ok:!1,durationMs:Date.now()-H,error:n.message})}}let Y=q.map(n=>`${n.ok?`✅`:`❌`} ${n.runtime} (${n.durationMs}ms)${n.error?` — ${n.error}`:``}`).join(` `);if(ve.log(`[gjsify test] ${Y}`),q.some(n=>!n.ok))return process.exit(1);process.exit(0)}}});function readPackageJson$1(n){if(!existsSync(n))return null;let S=readFileSync(n,`utf-8`);try{return JSON.parse(S)}catch(S){throw Error(`gjsify install: ${n} is not valid JSON: ${S.message}`)}}function writePackageJson(n,S){let C=sortKnownDepFields(S);writeFileSync(n,JSON.stringify(C,null,2)+`
|
|
805
|
-
`,`utf-8`)}function parseSpec$2(n){if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S===-1)return{name:n};let C=n.indexOf(`@`,S+1);return C===-1?{name:n}:{name:n.slice(0,C),range:n.slice(C+1)}}let S=n.indexOf(`@`);return S===-1?{name:n}:{name:n.slice(0,S),range:n.slice(S+1)}}function projectSpecsFromPackageJson(n){let S=[];for(let C of[`dependencies`,`devDependencies`,`optionalDependencies`]){let N=n[C];if(N)for(let[n,C]of Object.entries(N))typeof C==`string`&&(/^(workspace|link|file|portal|git\+|https?):/.test(C)||S.push(`${n}@${C}`))}return S}function addDependencyEntry(n,S,C,N){n[N]===void 0&&(n[N]={}),n[N][S]=C}function defaultRangeFromVersion(n){return`^${n}`}function sortKnownDepFields(n){let S={...n};for(let n of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let C=S[n];C&&(S[n]=Object.fromEntries(Object.entries(C).sort(([n],[S])=>n<S?-1:+(n>S))))}return S}var
|
|
804
|
+
"dependencies": { "@gjsify/node-gi": "^0.13.0" }`);let{env:H,envPrefix:W}=computeNativeEnvForBundle(I,F),q={...process.env,...H},[,Y]=kh[n].launch(I,C),X=n===`node`?nodeBinary():kh[n].probe,Z=[X,...Y.map(n=>n.includes(` `)?`"${n}"`:n)].join(` `);N.quiet||ve.error(`$ ${W?`${W} `:``}${Z}`);let failed=n=>(process.exitCode=n,process.exit(n)),te;try{te=await spawnToCompletion(X,Y,{completion:N.completion,env:q})}catch(n){return ve.error(n.message),failed(1)}if(te.code!==0)return ve.error(`${n} exited with ${describeExit(te)}`),failed(te.code??1);if(N.exitOnSuccess)return process.exit(0)}var xP=__esmMin(()=>{ye(),Vl(),Hs(),th(),yP(),Ah(),_P()});async function buildTestBundle(n,S,C,N){let F=await new Config().forBuild({entryPoints:[n],outfile:S,app:C,verbose:N??!1,logLevel:`warning`,exclude:[]});F.library={...F.library},F.bundler={...F.bundler,input:[n],output:{...F.bundler?.output,file:S}},await new QN(F).start({app:C,library:!1})}async function runTestBundle(n,S){if(S===`gjs`){await runGjsBundle(n,[],{completion:`exit`});return}let C=await spawnToCompletion(nodeBinary(),[n],{completion:`exit`});if(C.code!==0)throw Error(`node exited with ${describeExit(C)}`)}function isFresh(n,S){if(!existsSync(n))return!1;let C=statSync(n).mtimeMs,N=Ps(S);try{return C>=newestMtimeUnder(existsSync(N)?N:S)}catch{return!1}}function newestMtimeUnder(n){let S=statSync(n);if(S.isFile())return S.mtimeMs;let C=S.mtimeMs;for(let S of readdirSync(n,{withFileTypes:!0})){if(S.name===`node_modules`||S.name===`dist`||S.name===`lib`||S.name.startsWith(`.`))continue;let N=newestMtimeUnder(js(n,S.name));N>C&&(C=N)}return C}var SP,CP=__esmMin(()=>{ye(),Vl(),Hs(),Ah(),xP(),_P(),nP(),$N(),yP(),SP={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 S=process.cwd(),C=(await new Config().forBuild({}).catch(()=>({}))).test??{},N=Os(S,n.entry??C.entry??`src/test.mts`),F=Os(S,n.outdir??C.outdir??`dist`);if(!existsSync(N))return ve.error(`[gjsify test] no test entry at ${Ms(S,N)} — add an \`src/test.mts\` that aggregates your \`@gjsify/unit\` suites, or set \`gjsify.test.entry\` in package.json.`),process.exit(1);let I=n.runtime===`gjs`||n.runtime===`node`,H=n.runtime===`gjs`?[`gjs`]:n.runtime===`node`?[`node`]:C.runtimes&&C.runtimes.length>0?C.runtimes:[`gjs`,`node`],W=I?H:H.filter(n=>isRuntimeAvailable(n));for(let n of H.filter(n=>!W.includes(n)))ve.log(`[gjsify test] skipping ${n} — no \`${kh[n].probe}\` on PATH (not requested explicitly)`);if(W.length===0)return ve.error(`[gjsify test] none of the default runtimes (${H.join(`, `)}) is available on this host.\n Install one, or pin the set: \`gjsify test --runtime <rt>\` / \`gjsify.test.runtimes\` in package.json.`),process.exit(1);let q=[];for(let C of W){let I=js(F,`test.${C}.mjs`);if(n.build!==!1)if(n.rebuild||!isFresh(I,N)){let F=Date.now();n.verbose&&ve.log(`[gjsify test] building → ${Ms(S,I)} (—app ${C})`);try{await buildTestBundle(N,I,C,n.verbose),n.verbose&&ve.log(`[gjsify test] built ${C} in ${Date.now()-F}ms`)}catch(n){ve.error(`[gjsify test] build failed for ${C}:`,n.message),q.push({runtime:C,ok:!1,durationMs:0,error:`build failed`});continue}}else n.verbose&&ve.log(`[gjsify test] ${C}: bundle is up-to-date — skipping build (use --rebuild to force)`);else if(!existsSync(I)){ve.error(`[gjsify test] --no-build but ${Ms(S,I)} doesn't exist. Build first or drop --no-build.`),q.push({runtime:C,ok:!1,durationMs:0,error:`no bundle`});continue}let H=Date.now();try{await runTestBundle(I,C),q.push({runtime:C,ok:!0,durationMs:Date.now()-H})}catch(n){q.push({runtime:C,ok:!1,durationMs:Date.now()-H,error:n.message})}}let Y=q.map(n=>`${n.ok?`✅`:`❌`} ${n.runtime} (${n.durationMs}ms)${n.error?` — ${n.error}`:``}`).join(` `);if(ve.log(`[gjsify test] ${Y}`),q.some(n=>!n.ok))return process.exit(1);process.exit(0)}}});function doubleDashArgs(n){let S=n[`--`];if(S==null)return[];if(!Array.isArray(S))throw Error(`gjsify: internal error — yargs' \`--\` slot holds a ${typeof S} rather than an array, so the arguments after \`--\` cannot be forwarded. The command builder must set \`parserConfiguration({ 'populate--': true })\`.`);return S.map((n,S)=>{if(typeof n==`string`)return n;throw Error(`gjsify: internal error — the argument after \`--\` at position ${S} arrived as a ${typeof n} (${String(n)}) instead of a string, so forwarding it would change what the caller wrote. The command builder must set \`parserConfiguration({ 'parse-positional-numbers': false })\` alongside \`populate--\`.`)})}var wP=__esmMin(()=>{});function readPackageJson$1(n){if(!existsSync(n))return null;let S=readFileSync(n,`utf-8`);try{return JSON.parse(S)}catch(S){throw Error(`gjsify install: ${n} is not valid JSON: ${S.message}`)}}function writePackageJson(n,S){let C=sortKnownDepFields(S);writeFileSync(n,JSON.stringify(C,null,2)+`
|
|
805
|
+
`,`utf-8`)}function parseSpec$2(n){if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S===-1)return{name:n};let C=n.indexOf(`@`,S+1);return C===-1?{name:n}:{name:n.slice(0,C),range:n.slice(C+1)}}let S=n.indexOf(`@`);return S===-1?{name:n}:{name:n.slice(0,S),range:n.slice(S+1)}}function projectSpecsFromPackageJson(n){let S=[];for(let C of[`dependencies`,`devDependencies`,`optionalDependencies`]){let N=n[C];if(N)for(let[n,C]of Object.entries(N))typeof C==`string`&&(/^(workspace|link|file|portal|git\+|https?):/.test(C)||S.push(`${n}@${C}`))}return S}function addDependencyEntry(n,S,C,N){n[N]===void 0&&(n[N]={}),n[N][S]=C}function defaultRangeFromVersion(n){return`^${n}`}function sortKnownDepFields(n){let S={...n};for(let n of[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]){let C=S[n];C&&(S[n]=Object.fromEntries(Object.entries(C).sort(([n],[S])=>n<S?-1:+(n>S))))}return S}var TP=__esmMin(()=>{Vl(),__name$1(readPackageJson$1,`readPackageJson`),__name$1(parseSpec$2,`parseSpec`)});function scriptCacheEnabled(){let n=process.env.GJSIFY_NODE_SCRIPT_CACHE;return n===`1`||n===`true`||n===`yes`}async function runNodeScript(n,S=[],C){let N=Os(n);if(!existsSync(N)||!statSync(N).isFile())return ve.error(`gjsify run --node-script: no such file: ${N}`),process.exit(1);let F=hostRuntime$1();if(F!==`gjs`){await runRuntimeBundle(F,N,S,{completion:C.completion,exitOnSuccess:C.exitOnSuccess,quiet:!0});return}let{BuildAction:I}=await Promise.resolve().then(()=>($N(),YN)),{globals:H,excludeGlobals:W}=await new Config().forNodeScript(N),q;try{q=await I.bundleFileForGjsCached(N,{cacheSubdir:`node-scripts`,label:Fs(N),cache:scriptCacheEnabled(),preserveDefaultExport:!1,define:{"import.meta.url":JSON.stringify(pathToFileURL(N).href)},globals:H,excludeGlobals:W,resolveFromToolchain:!0})}catch(n){throw Error(`gjsify run --node-script: failed to bundle ${N} for GJS. The script must import only what gjsify can provide under GJS (node: builtins, workspace packages, pure-JS npm deps). (${n.message})`)}await runGjsBundle(q,S,{completion:C.completion,exitOnSuccess:C.exitOnSuccess,quiet:!0})}var EP=__esmMin(()=>{ye(),Vl(),Hs(),gn(),th(),nP(),yP(),xP()});function parseShebang(n){let S=DP.exec(n.trim());return S?{variables:S[1]??``,prog:S[2]??``,args:S[3]??``}:null}function replaceDollarWithPercentPair(n){return n.replace(/\$\{?([^$@#?\- \t{}:]+)\}?/g,(n,S)=>`%${S}%`)}function convertToSetCommands(n){let S=``;for(let C of n.split(` `)){let n=C.indexOf(`=`);if(n<=0)continue;let N=C.slice(0,n).trim(),F=C.slice(n+1).trim();N&&F&&(S+=`@SET ${N}=${replaceDollarWithPercentPair(F)}\r\n`)}return S}function buildCmdShim(n,S){let C=n.split(`\\`).join(`/`),N=C.split(`/`).join(`\\`),F=C,I=S?.prog??``,H=S?.args??``,W=S?.variables??``,q=I?I.split(`\\`).join(`/`):``,Y=q?`"${q}$exe"`:``,X=``,Z=``,te=``;I?(X=`"%dp0%\\${I}.exe"`,Z=`"$basedir/${I}"`,te=`"$basedir/${I}$exe"`,N=`"%dp0%\\${N}"`,C=`"$basedir_win/${C}"`,F=`"$basedir/${F}"`):(I=`"%dp0%\\${N}"`,q=`"$basedir/${C}"`,Y=q,H=``,N=``,C=``,F=``);let ne;if(X){let n=H.trim();ne=OP+convertToSetCommands(W)+`\r
|
|
806
806
|
IF EXIST ${X} (\r\n SET "_prog=${X.replace(/(^")|("$)/g,``)}"\r\n) ELSE (\r
|
|
807
807
|
SET "_prog=${I.replace(/(^")|("$)/g,``)}"\r\n)\r
|
|
808
808
|
\r
|
|
809
|
-
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & set PATHEXT=%PATHEXT:;.JS;=;% & "%_prog%" ${n} ${N} %*\r\n`}else ne=`${
|
|
809
|
+
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & set PATHEXT=%PATHEXT:;.JS;=;% & "%_prog%" ${n} ${N} %*\r\n`}else ne=`${OP}${I} ${H} ${N} %*\r\n`;let re=`#!/bin/sh\n${kP}`;Z?re+=`PROG_EXE=${Z.replace(/"$/,`.exe"`)}\nif ! [ -x "\$PROG_EXE" ]; then
|
|
810
810
|
PROG_EXE=${Z}\n if ! [ -x "\$PROG_EXE" ]; then
|
|
811
811
|
PROG_EXE=${q}\n if ! [ -x "\$PROG_EXE" ]; then
|
|
812
812
|
PROG_EXE=${q}.exe\n fi
|
|
813
813
|
fi
|
|
814
814
|
fi
|
|
815
815
|
|
|
816
|
-
exec ${W}"$PROG_EXE" ${H} ${C} "$@"\n`:re+=`exec ${q} ${H} ${C} "$@"\n`;let ie=
|
|
816
|
+
exec ${W}"$PROG_EXE" ${H} ${C} "$@"\n`:re+=`exec ${q} ${H} ${C} "$@"\n`;let ie=AP;return te?ie+=`\$ret=0
|
|
817
817
|
if (Test-Path ${te}) {\n # Support pipeline input
|
|
818
818
|
if (\$MyInvocation.ExpectingInput) {
|
|
819
819
|
$input | & ${te} ${H} ${F} $args\n } else {
|
|
@@ -832,7 +832,7 @@ if (\$MyInvocation.ExpectingInput) {
|
|
|
832
832
|
$input | & ${Y} ${F} $args\n} else {
|
|
833
833
|
& ${Y} ${F} $args\n}
|
|
834
834
|
exit \$LASTEXITCODE
|
|
835
|
-
`,{sh:re,cmd:ne,ps1:ie}}function buildLauncherShims(n){let{interpreter:S,interpreterArgs:C=[],target:N,prependEnv:F={},fallback:I}=n,H=N.split(`/`).join(`\\`),W=C.length>0?`${C.join(` `)} `:``,q=Object.entries(F),Y=I===void 0?``:I.target.split(`/`).join(`\\`),X=I?.interpreterArgs!==void 0&&I.interpreterArgs.length>0?`${I.interpreterArgs.join(` `)} `:``,Z=
|
|
835
|
+
`,{sh:re,cmd:ne,ps1:ie}}function buildLauncherShims(n){let{interpreter:S,interpreterArgs:C=[],target:N,prependEnv:F={},fallback:I}=n,H=N.split(`/`).join(`\\`),W=C.length>0?`${C.join(` `)} `:``,q=Object.entries(F),Y=I===void 0?``:I.target.split(`/`).join(`\\`),X=I?.interpreterArgs!==void 0&&I.interpreterArgs.length>0?`${I.interpreterArgs.join(` `)} `:``,Z=OP;for(let[n,S]of q)Z+=`@SET "${n}=${S};%${n}%"\r\n`;I===void 0?Z+=`${S} ${W}"${H}" %*\r\n`:Z+=`@where ${S} >NUL 2>NUL\r\n@IF %ERRORLEVEL% EQU 0 (\r\n ${S} ${W}"${H}" %*\r\n) ELSE (\r\n ${I.interpreter} ${X}"${Y}" %*\r\n)\r\n`;let te=`#!/usr/bin/env pwsh
|
|
836
836
|
`;for(let[n,S]of q)te+=`$env:${n} = "${S};" + $env:${n}\n`;let ne=C.map(n=>`"${n}" `).join(``);if(I===void 0)te+=`# Support pipeline input
|
|
837
837
|
if (\$MyInvocation.ExpectingInput) {
|
|
838
838
|
$input | & "${S}" ${ne}"${H}" $args\n} else {
|
|
@@ -845,7 +845,7 @@ if (\$MyInvocation.ExpectingInput) {
|
|
|
845
845
|
& \$exe @exeArgs \$script \$args
|
|
846
846
|
}
|
|
847
847
|
`}return te+=`exit $LASTEXITCODE
|
|
848
|
-
`,{cmd:Z,ps1:te}}function shQuote(n){return`'${n.replace(/'/g,`'\\''`)}'`}function buildNativeEnvPreamble(n,S=[],C={}){let N=C.platform??process.platform,F=C.arch??process.arch,I=C.libc===void 0?detectHostLibc(N):C.libc,{name:H,separator:W}=libraryPathVar(N);if(N===`win32`){if(S.length===0)return``;let n=shQuote(S.join(W));return`GI_TYPELIB_PATH=${n}\${GI_TYPELIB_PATH:+"${W}$GI_TYPELIB_PATH"}\n${H}=${n}\${${H}:+"${W}$${H}"}\nexport GI_TYPELIB_PATH ${H}\n`}let q=`${n.replace(/\/+$/,``)}/node_modules/`,Y=S.filter(n=>!n.startsWith(q)),X=prebuildDirCandidates(N,F,void 0,I),Z=[];for(let S of X)Z.push(`${shQuote(n)}/node_modules/@*/*/prebuilds/${S}`),Z.push(`${shQuote(n)}/node_modules/*/prebuilds/${S}`);return`gjsify_np=${Y.length>0?shQuote(Y.join(W)):`''`}\nfor gjsify_d in ${Z.join(` `)}; do\n [ -d "$gjsify_d" ] || continue\n for gjsify_t in "$gjsify_d"/*.typelib; do\n if [ -f "$gjsify_t" ]; then gjsify_np="\${gjsify_np:+$gjsify_np${W}}$gjsify_d"; break; fi\n done\ndone\nif [ -n "$gjsify_np" ]; then\n GI_TYPELIB_PATH="$gjsify_np\${GI_TYPELIB_PATH:+${W}$GI_TYPELIB_PATH}"\n ${H}="$gjsify_np\${${H}:+${W}$${H}}"\n export GI_TYPELIB_PATH ${H}\nfi\nunset gjsify_np gjsify_d gjsify_t\n`+dyldFallbackPreamble(N)}function dyldFallbackPreamble(n){return n===`darwin`?`DYLD_FALLBACK_LIBRARY_PATH="\${DYLD_FALLBACK_LIBRARY_PATH:+$DYLD_FALLBACK_LIBRARY_PATH:}${dyldDefaultFallbackDirs({HOME:`$HOME`}).join(`:`)}"\nexport DYLD_FALLBACK_LIBRARY_PATH\n`:``}function normalizeBinMap(n,S){let C=new Map;if(typeof S==`string`){let N=n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n;return C.set(N,S),C}for(let[n,N]of Object.entries(S))C.set(n,N);return C}function pickBinMap(n,S){let C=S.gjsify?.bin,N=S.bin;return C===void 0?N===void 0?null:{map:normalizeBinMap(n,N),isGjsBin:!1,nodeFallback:null}:{map:normalizeBinMap(n,C),isGjsBin:!0,nodeFallback:N===void 0?null:normalizeBinMap(n,N)}}function buildShLauncher(n,S){let C=S.isGjsBundle?S.envPreamble??``:``;return S.isGjsBundle&&S.nodeFallbackAbs!==void 0?`#!/bin/sh\nif command -v gjs >/dev/null 2>&1; then\n${C}exec gjs -m ${shQuote(n)} "$@"\nfi\nexec node ${shQuote(S.nodeFallbackAbs)} "$@"\n`:`#!/bin/sh\n${C}${S.isGjsBundle?`exec gjs -m ${shQuote(n)} "$@"`:`exec ${shQuote(n)} "$@"`}\n`}function isGjsBundlePath(n){return n.endsWith(`.gjs.mjs`)||n.endsWith(`.mjs`)}var
|
|
848
|
+
`,{cmd:Z,ps1:te}}function shQuote(n){return`'${n.replace(/'/g,`'\\''`)}'`}function buildNativeEnvPreamble(n,S=[],C={}){let N=C.platform??process.platform,F=C.arch??process.arch,I=C.libc===void 0?detectHostLibc(N):C.libc,{name:H,separator:W}=libraryPathVar(N);if(N===`win32`){if(S.length===0)return``;let n=shQuote(S.join(W));return`GI_TYPELIB_PATH=${n}\${GI_TYPELIB_PATH:+"${W}$GI_TYPELIB_PATH"}\n${H}=${n}\${${H}:+"${W}$${H}"}\nexport GI_TYPELIB_PATH ${H}\n`}let q=`${n.replace(/\/+$/,``)}/node_modules/`,Y=S.filter(n=>!n.startsWith(q)),X=prebuildDirCandidates(N,F,void 0,I),Z=[];for(let S of X)Z.push(`${shQuote(n)}/node_modules/@*/*/prebuilds/${S}`),Z.push(`${shQuote(n)}/node_modules/*/prebuilds/${S}`);return`gjsify_np=${Y.length>0?shQuote(Y.join(W)):`''`}\nfor gjsify_d in ${Z.join(` `)}; do\n [ -d "$gjsify_d" ] || continue\n for gjsify_t in "$gjsify_d"/*.typelib; do\n if [ -f "$gjsify_t" ]; then gjsify_np="\${gjsify_np:+$gjsify_np${W}}$gjsify_d"; break; fi\n done\ndone\nif [ -n "$gjsify_np" ]; then\n GI_TYPELIB_PATH="$gjsify_np\${GI_TYPELIB_PATH:+${W}$GI_TYPELIB_PATH}"\n ${H}="$gjsify_np\${${H}:+${W}$${H}}"\n export GI_TYPELIB_PATH ${H}\nfi\nunset gjsify_np gjsify_d gjsify_t\n`+dyldFallbackPreamble(N)}function dyldFallbackPreamble(n){return n===`darwin`?`DYLD_FALLBACK_LIBRARY_PATH="\${DYLD_FALLBACK_LIBRARY_PATH:+$DYLD_FALLBACK_LIBRARY_PATH:}${dyldDefaultFallbackDirs({HOME:`$HOME`}).join(`:`)}"\nexport DYLD_FALLBACK_LIBRARY_PATH\n`:``}function normalizeBinMap(n,S){let C=new Map;if(typeof S==`string`){let N=n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n;return C.set(N,S),C}for(let[n,N]of Object.entries(S))C.set(n,N);return C}function pickBinMap(n,S){let C=S.gjsify?.bin,N=S.bin;return C===void 0?N===void 0?null:{map:normalizeBinMap(n,N),isGjsBin:!1,nodeFallback:null}:{map:normalizeBinMap(n,C),isGjsBin:!0,nodeFallback:N===void 0?null:normalizeBinMap(n,N)}}function buildShLauncher(n,S){let C=S.isGjsBundle?S.envPreamble??``:``;return S.isGjsBundle&&S.nodeFallbackAbs!==void 0?`#!/bin/sh\nif command -v gjs >/dev/null 2>&1; then\n${C}exec gjs -m ${shQuote(n)} "$@"\nfi\nexec node ${shQuote(S.nodeFallbackAbs)} "$@"\n`:`#!/bin/sh\n${C}${S.isGjsBundle?`exec gjs -m ${shQuote(n)} "$@"`:`exec ${shQuote(n)} "$@"`}\n`}function isGjsBundlePath(n){return n.endsWith(`.gjs.mjs`)||n.endsWith(`.mjs`)}var DP,OP,kP,AP,jP=__esmMin(()=>{gN(),nN(),DP=/^#!\s*(?:\/usr\/bin\/env\s+(?:-S\s+)?((?:[^ \t=]+=[^ \t=]+\s+)*))?([^ \t]+)(.*)$/,OP=`@ECHO off\r
|
|
849
849
|
GOTO start\r
|
|
850
850
|
:find_dp0\r
|
|
851
851
|
SET dp0=%~dp0\r
|
|
@@ -853,7 +853,7 @@ EXIT /b\r
|
|
|
853
853
|
:start\r
|
|
854
854
|
SETLOCAL\r
|
|
855
855
|
CALL :find_dp0\r
|
|
856
|
-
`,
|
|
856
|
+
`,kP=`basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')")
|
|
857
857
|
basedir_win="$basedir"
|
|
858
858
|
|
|
859
859
|
case \`uname -a\` in
|
|
@@ -873,7 +873,7 @@ case \`uname -a\` in
|
|
|
873
873
|
;;
|
|
874
874
|
esac
|
|
875
875
|
|
|
876
|
-
`,
|
|
876
|
+
`,AP=`#!/usr/bin/env pwsh
|
|
877
877
|
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
|
878
878
|
|
|
879
879
|
$exe=""
|
|
@@ -882,19 +882,19 @@ if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
|
|
882
882
|
# are installed in the same directory
|
|
883
883
|
$exe=".exe"
|
|
884
884
|
}
|
|
885
|
-
`});function makeProgressReporter(n={}){if(n.enabled===!1)return MP;let S=n.stream??process.stderr,C=!!S.isTTY;return n.enabled??!0?C?makeTtyReporter(S):makePlainReporter(S):MP}function makeTtyReporter(n){let S=0,C=``;function render(N,F=!1){let I=Date.now();!F&&I-S<33&&N===C||(S=I,C=N,n.write(`\r\x1B[2K`+N))}function clearLine(){n.write(`\r\x1B[2K`),C=``}return{beginPhase(S,C){render(formatBar(S,0,C,void 0,n.columns??80),!0)},update(S){render(formatBar(S.phase,S.current,S.total,S.name,n.columns??80))},endPhase(S){let C=jP[S];clearLine(),n.write(`gjsify install: ${C} done\n`)}}}function makePlainReporter(n){let S=0,C=0;return{beginPhase(N,F){S=Date.now(),C=0,n.write(`gjsify install: ${jP[N]} ${F} package(s)\n`)},update(N){let F=Date.now();if(F-S<NP||N.current<=C)return;S=F,C=N.current;let I=N.total>0?Math.round(N.current/N.total*100):0;n.write(`gjsify install: ${jP[N.phase]} ${N.current}/${N.total} (${I}%)\n`)},endPhase(S){n.write(`gjsify install: ${jP[S]} done\n`)}}}function formatBar(n,S,C,N,F){let I=jP[n],H=C>0?Math.min(1,S/C):0,W=`${S}/${C}`,q=`gjsify install: ${I} `,Y=` ${W}`+(N?` ${N}`:``),X=Math.max(8,Math.min(40,F-q.length-Y.length-4)),Z=Math.round(H*X),te=`█`.repeat(Z)+`░`.repeat(X-Z),ne=`${q}[${te}]${Y}`;if(ne.length>F){let n=ne.length-F+1,S=N&&N.length>n?N.slice(0,N.length-n-1)+`…`:``;ne=`${q}[${te}] ${W}${S?` `+S:``}`}return ne}var jP,MP,NP,PP=__esmMin(()=>{jP={resolve:`resolving`,download:`downloading`,extract:`extracting`,link:`linking bins`},MP={update(){},beginPhase(){},endPhase(){}},NP=5e3});function parse(n){try{return new SemVer(n)}catch{return null}}function compare(n,S){let C=n instanceof SemVer?n:new SemVer(n),N=S instanceof SemVer?S:new SemVer(S);return C.compare(N)}function satisfies(n,S){let C=S instanceof LP?S:new LP(S),N=n instanceof SemVer?n:parse(String(n));return N?C.test(N):!1}function maxSatisfying(n,S){let C=S instanceof LP?S:new LP(S),N=null;for(let S of n){let n=parse(S);!n||!C.test(n)||(N===null||n.compare(N)>0)&&(N=n)}return N?N.version:null}function testComparator(n,S){if(n.semver===null)return!0;let C=S.compare(n.semver);switch(n.operator){case``:case`=`:return C===0;case`<`:return C<0;case`<=`:return C<=0;case`>`:return C>0;case`>=`:return C>=0}}function formatComparator(n){return n.semver===null?`*`:`${n.operator}${n.semver.version}`}function parseRangePart(n){let S=n.trim();if(S===``||S===`*`||S.toLowerCase()===`latest`)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let C=S.match(/^\s*(\S+)\s+-\s+(\S+)\s*$/);if(C)return hyphenRange(C[1],C[2]);let N=S.replace(/(<=|>=|<|>|=)\s+(?=\S)/g,`$1`).split(/\s+/),F=[];for(let n of N)F.push(...parseSimple(n));return F}function parseSimple(n){if(n===`*`||n===``||n.toLowerCase()===`latest`)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];if(n.startsWith(`^`))return caretRange(n.slice(1));if(n.startsWith(`~`))return tildeRange(n.slice(1).replace(/^>/,``));let S=n.match(/^(<=|>=|<|>|=)\s*(.+)$/);if(S){let n=S[1];return primitiveRange(n,S[2])}return partialRange(n)}function parsePartial(n){let S=n.trim().replace(/^v/,``);if(S===``||S===`*`)return{major:null,minor:null,patch:null,pre:``,build:``};let C=``,N=``,F=S,I=F.indexOf(`+`);I>=0&&(N=F.slice(I+1),F=F.slice(0,I));let H=F.indexOf(`-`);H>=0&&(C=F.slice(H+1),F=F.slice(0,H));let W=F.split(`.`),xr=S=>{if(S===void 0||S===``||S===`x`||S===`X`||S===`*`)return null;if(!/^\d+$/.test(S))throw TypeError(`Invalid partial version: ${n}`);return Number(S)};return{major:xr(W[0]),minor:xr(W[1]),patch:xr(W[2]),pre:C,build:N}}function partialToVersion(n){return`${n.major??0}.${n.minor??0}.${n.patch??0}${n.pre?`-${n.pre}`:``}${n.build?`+${n.build}`:``}`}function partialRange(n){let S=parsePartial(n);return S.major===null?[{operator:`>=`,semver:new SemVer(`0.0.0`)}]:S.minor===null?[{operator:`>=`,semver:new SemVer(`${S.major}.0.0`)},{operator:`<`,semver:new SemVer(`${S.major+1}.0.0`)}]:S.patch===null?[{operator:`>=`,semver:new SemVer(`${S.major}.${S.minor}.0`)},{operator:`<`,semver:new SemVer(`${S.major}.${S.minor+1}.0`)}]:[{operator:`=`,semver:new SemVer(partialToVersion(S))}]}function caretRange(n){let S=parsePartial(n);if(S.major===null)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let C=`${S.major}.${S.minor??0}.${S.patch??0}${S.pre?`-${S.pre}`:``}`,N;return N=S.major>0||S.minor===null?`${S.major+1}.0.0`:S.minor>0||S.patch===null?`0.${S.minor+1}.0`:`0.0.${S.patch+1}`,[{operator:`>=`,semver:new SemVer(C)},{operator:`<`,semver:new SemVer(N)}]}function tildeRange(n){let S=parsePartial(n);if(S.major===null)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let C=`${S.major}.${S.minor??0}.${S.patch??0}${S.pre?`-${S.pre}`:``}`,N=S.minor===null?`${S.major+1}.0.0`:`${S.major}.${S.minor+1}.0`;return[{operator:`>=`,semver:new SemVer(C)},{operator:`<`,semver:new SemVer(N)}]}function primitiveRange(n,S){let C=parsePartial(S);return C.major===null?[{operator:`>=`,semver:new SemVer(`0.0.0`)}]:n===`=`||n===``?partialRange(S):n===`>`?C.minor===null?[{operator:`>=`,semver:new SemVer(`${C.major+1}.0.0`)}]:C.patch===null?[{operator:`>=`,semver:new SemVer(`${C.major}.${C.minor+1}.0`)}]:[{operator:`>`,semver:new SemVer(partialToVersion(C))}]:n===`<`?C.minor===null?[{operator:`<`,semver:new SemVer(`${C.major}.0.0`)}]:C.patch===null?[{operator:`<`,semver:new SemVer(`${C.major}.${C.minor}.0`)}]:[{operator:`<`,semver:new SemVer(partialToVersion(C))}]:n===`>=`?[{operator:`>=`,semver:new SemVer(partialToVersion(C))}]:C.minor===null?[{operator:`<`,semver:new SemVer(`${C.major+1}.0.0`)}]:C.patch===null?[{operator:`<`,semver:new SemVer(`${C.major}.${C.minor+1}.0`)}]:[{operator:`<=`,semver:new SemVer(partialToVersion(C))}]}function hyphenRange(n,S){let C=parsePartial(n),N=parsePartial(S),F=C.major===null?{operator:`>=`,semver:new SemVer(`0.0.0`)}:{operator:`>=`,semver:new SemVer(`${C.major}.${C.minor??0}.${C.patch??0}${C.pre?`-${C.pre}`:``}`)},I;return I=N.major===null?{operator:`>=`,semver:new SemVer(`0.0.0`)}:N.minor===null?{operator:`<`,semver:new SemVer(`${N.major+1}.0.0`)}:N.patch===null?{operator:`<`,semver:new SemVer(`${N.major}.${N.minor+1}.0`)}:{operator:`<=`,semver:new SemVer(`${N.major}.${N.minor}.${N.patch}${N.pre?`-${N.pre}`:``}`)},[F,I]}var FP,IP,SemVer,LP,RP=__esmMin(()=>{FP=/^(0|[1-9]\d*)$/,IP=/^(\d+)\.(\d+)\.(\d+)(?:-((?:[0-9A-Za-z-]+)(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,SemVer=class{major;minor;patch;prerelease;build;version;constructor(n){let S=String(n).trim().replace(/^v/,``),C=IP.exec(S);if(!C)throw TypeError(`Invalid Version: ${n}`);this.major=Number(C[1]),this.minor=Number(C[2]),this.patch=Number(C[3]),this.prerelease=C[4]?C[4].split(`.`).map(n=>FP.test(n)?Number(n):n):[],this.build=C[5]?C[5].split(`.`):[],this.version=`${this.major}.${this.minor}.${this.patch}`+(this.prerelease.length?`-${this.prerelease.join(`.`)}`:``)+(this.build.length?`+${this.build.join(`.`)}`:``)}compare(n){return this.major===n.major?this.minor===n.minor?this.patch===n.patch?this.comparePre(n):this.patch<n.patch?-1:1:this.minor<n.minor?-1:1:this.major<n.major?-1:1}comparePre(n){let S=this.prerelease,C=n.prerelease;if(S.length===0&&C.length===0)return 0;if(S.length===0)return 1;if(C.length===0)return-1;for(let n=0;;n++){let N=S[n],F=C[n];if(N===void 0&&F===void 0)return 0;if(F===void 0)return 1;if(N===void 0)return-1;if(N===F)continue;let I=typeof N==`number`,H=typeof F==`number`;return I&&!H?-1:!I&&H?1:N<F?-1:1}}toString(){return this.version}},LP=class Range{raw;set;constructor(n){if(n instanceof Range){this.raw=n.raw,this.set=n.set;return}this.raw=String(n).trim();let S=this.raw.split(/\s*\|\|\s*/),C=[];for(let n of S){let S=parseRangePart(n);if(S.length===0)throw TypeError(`Invalid range: ${this.raw}`);C.push(S)}if(C.length===0)throw TypeError(`Invalid range: ${this.raw}`);this.set=C}test(n){let S=n instanceof SemVer?n:parse(String(n));if(!S)return!1;for(let n of this.set)if(n.every(n=>testComparator(n,S))){if(S.prerelease.length>0&&!n.some(n=>n.semver!==null&&n.semver.prerelease.length>0&&n.semver.major===S.major&&n.semver.minor===S.minor&&n.semver.patch===S.patch))continue;return!0}return!1}format(){return this.set.map(n=>n.map(formatComparator).join(` `)).join(` || `)}toString(){return this.format()}}});function parseTar(n){let S=[],C=null,N=null,F=null,I=0;for(;I+512<=n.length;){let H=n.subarray(I,I+512);if(allZeros(H)){let S=n.subarray(I+512,I+2*512);if(S.length===512&&allZeros(S))break;I+=512;continue}if(!validateChecksum(H))throw new TarParseError(`Bad header checksum at offset ${I} — file is not a valid tar archive`);let W=readString(H,0,100),q=parseOctal(H,100,8),Y=parseOctal(H,124,12),X=parseOctal(H,136,12),Z=String.fromCharCode(H[156]||0),te=readString(H,157,100),ne=readString(H,257,6),re=readString(H,345,155),ie=readString(H,265,32),ae=readString(H,297,32);I+=512;let oe=n.subarray(I,I+Y);if(I+=alignToBlock(Y),Z===`x`){C=parsePaxRecords(oe);continue}if(Z===`g`)continue;if(Z===`L`){N=bytesToString(oe).replace(/\0+$/,``);continue}if(Z===`K`){F=bytesToString(oe).replace(/\0+$/,``);continue}let se=W;ne===`ustar`&&re!==``&&(se=`${re}/${W}`),N!==null&&(se=N,N=null);let Q=te;if(F!==null&&(Q=F,F=null),C!==null){let N=C.get(`path`);N!==void 0&&(se=N);let F=C.get(`linkpath`);F!==void 0&&(Q=F);let H=C.get(`size`);if(H!==void 0){let N=Number(H);if(Number.isFinite(N)){let F=I-alignToBlock(Y),H=n.subarray(F,F+N);I=F+alignToBlock(N),C=null,S.push(buildEntry(se,Q,Z,q,X,ie,ae,H));continue}}C=null}S.push(buildEntry(se,Q,Z,q,X,ie,ae,oe))}return S}function buildEntry(n,S,C,N,F,I,H,W){return{name:n,linkname:S,type:typeflagToType(C,n),mode:N,mtime:F,body:W,uname:I,gname:H}}function typeflagToType(n,S){switch(n){case`0`:case`\0`:case``:return S.endsWith(`/`)?`directory`:`file`;case`1`:return`hardlink`;case`2`:return`symlink`;case`5`:return`directory`;case`x`:return`pax-header`;case`g`:return`pax-global`;case`L`:return`gnu-longname`;case`K`:return`gnu-longlink`;default:return`unknown`}}function parsePaxRecords(n){let S=new Map,C=0;for(;C<n.length;){let N=C;for(;N<n.length&&n[N]!==32;)N++;if(N>=n.length)break;let F=bytesToString(n.subarray(C,N)),I=Number(F);if(!Number.isFinite(I)||I<=0)break;let H=C+I;if(H>n.length)break;let W=bytesToString(n.subarray(N+1,H-1)),q=W.indexOf(`=`);if(q>0){let n=W.slice(0,q),C=W.slice(q+1);S.set(n,C)}C=H}return S}function readString(n,S,C){let N=S,F=S+C;for(;N<F&&n[N]!==0;)N++;return bytesToString(n.subarray(S,N))}function bytesToString(n){return new TextDecoder(`utf-8`,{fatal:!1}).decode(n)}function parseOctal(n,S,C){if(C>0&&n[S]&128){let N=n[S]&127;for(let F=1;F<C;F++)N=N*256+n[S+F];return N}let N=``;for(let F=0;F<C;F++){let C=n[S+F];C===0||C===32||(N+=String.fromCharCode(C))}return N===``?0:parseInt(N,8)}function alignToBlock(n){return Math.ceil(n/512)*512}function allZeros(n){for(let S=0;S<n.length;S++)if(n[S]!==0)return!1;return!0}function validateChecksum(n){let S=parseOctal(n,148,8),C=0,N=0;for(let S=0;S<512;S++){let F=S>=148&&S<156?32:n[S];C+=F,N+=F>127?F-256:F}return S===C||S===N}var TarParseError,zP=__esmMin(()=>{TarParseError=class extends Error{constructor(n){super(n),this.name=`TarParseError`}}});function createTarball(n){let S=[];for(let C of n){if(`directory`in C&&C.directory===!0){S.push(buildHeader$1(ensureTrailingSlash(C.name),0,`5`,C.mode??493,C.mtime??0));continue}let n=C,N=typeof n.body==`string`?new TextEncoder().encode(n.body):n.body,F=n.mode??defaultFileMode(N);S.push(buildHeader$1(n.name,N.byteLength,`0`,F,n.mtime??0)),S.push(N);let I=padTo512(N.byteLength);I>0&&S.push(new Uint8Array(I))}return S.push(new Uint8Array(512*2)),concatChunks(S)}function buildHeader$1(n,S,C,N,F){let{prefix:I,basename:H}=splitPathForUstar(n),W=new Uint8Array(512);writeAscii(W,H,0,100),writeOctal(W,N&4095,100,7),W[107]=0,writeOctal(W,0,108,7),W[115]=0,writeOctal(W,0,116,7),W[123]=0,writeOctal(W,S,124,11),W[135]=0,writeOctal(W,F,136,11),W[147]=0;for(let n=148;n<156;n++)W[n]=32;W[156]=C.charCodeAt(0),writeAscii(W,`ustar\0`,257,6),writeAscii(W,`00`,263,2),I&&writeAscii(W,I,345,155);let q=0;for(let n=0;n<512;n++)q+=W[n];return writeAscii(W,q.toString(8).padStart(6,`0`),148,6),W[154]=0,W[155]=32,W}function splitPathForUstar(n){if(n.length<=100)return{prefix:``,basename:n};if(n.length>255)throw Error(`createTarball: path too long (${n.length} > 255 chars): ${n}`);for(let S=Math.min(n.length-1,155);S>0;S--)if(n[S]===`/`&&n.length-S-1<=100)return{prefix:n.slice(0,S),basename:n.slice(S+1)};throw Error(`createTarball: cannot split path into ustar prefix+basename (basename slot is 100 chars): ${n}`)}function writeAscii(n,S,C,N){let F=new TextEncoder().encode(S);if(F.length>N)throw Error(`createTarball: field too long (${F.length} > ${N}): "${S}"`);n.set(F,C)}function writeOctal(n,S,C,N){writeAscii(n,S.toString(8).padStart(N,`0`),C,N)}function padTo512(n){let S=n%512;return S===0?0:512-S}function ensureTrailingSlash(n){return n.endsWith(`/`)?n:`${n}/`}function defaultFileMode(n){return n.length>=2&&n[0]===35&&n[1]===33?493:420}function concatChunks(n){let S=0;for(let C of n)S+=C.byteLength;let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.byteLength;return C}var BP=__esmMin(()=>{__name$1(buildHeader$1,`buildHeader`)});async function extractTarball(n,S,C={}){let N=n instanceof Uint8Array?n:new Uint8Array(n),F=parseTar(C.gzip??(N.length>=2&&N[0]===31&&N[1]===139)?await gunzip(N):N);mkdirSync(S,{recursive:!0});let I=C.strip??1,H=C.preventEscape??!0,W={files:[],directories:[],symlinks:[],skipped:0};for(let n of F){let N=stripComponents(n.name,I);if(N===null||N===``){W.skipped++;continue}let F=Os(S,N);if(H&&!isInside$2(F,S))throw Error(`tar: refusing to extract ${n.name} outside ${S} (resolved=${F})`);if(C.filter&&!C.filter(n,F)){W.skipped++;continue}if(n.type===`directory`){mkdirSync(F,{recursive:!0}),W.directories.push(F);continue}if(n.type===`file`){mkdirSync(Ps(F),{recursive:!0}),writeFileSync(F,n.body);let S=C.chmod?.(n,F)??n.mode&511;if(S>0)try{chmodSync(F,S)}catch{}W.files.push(F);continue}if(n.type===`symlink`){mkdirSync(Ps(F),{recursive:!0});try{symlinkSync(n.linkname,F),W.symlinks.push(F)}catch{writeFileSync(F,n.linkname),W.files.push(F)}continue}W.skipped++}return W}async function gunzip(n){let S=globalThis.DecompressionStream;if(typeof S!=`function`)throw Error(`@gjsify/tar: globalThis.DecompressionStream is not available — import '@gjsify/compression-streams/register' on GJS to register it`);return drainStream(new Blob([new Uint8Array(n)]).stream().pipeThrough(new S(`gzip`)))}async function gzip(n){let S=globalThis.CompressionStream;if(typeof S!=`function`)throw Error(`@gjsify/tar: globalThis.CompressionStream is not available — import '@gjsify/compression-streams/register' on GJS to register it`);return drainStream(new Blob([new Uint8Array(n)]).stream().pipeThrough(new S(`gzip`)))}async function drainStream(n){let S=[],C=0,N=n.getReader();for(;;){let{value:n,done:F}=await N.read();if(F)break;let I=n instanceof Uint8Array?n:new Uint8Array(n);S.push(I),C+=I.length}let F=new Uint8Array(C),I=0;for(let n of S)F.set(n,I),I+=n.length;return F}function stripComponents(n,S){if(S<=0)return n;let C=n.split(`/`).filter(n=>n!==``);return C.length<=S?null:C.slice(S).join(`/`)}function isInside$2(n,S){let C=Ms(S,n);return C!==``&&!C.startsWith(`..`)&&!As(C)}var VP=__esmMin(()=>{zP(),Vl(),Hs(),__name$1(isInside$2,`isInside`)}),HP=__exportAll$4({BLOCK_SIZE:()=>512,TarParseError:()=>TarParseError,createTarball:()=>createTarball,extractTarball:()=>extractTarball,gunzip:()=>gunzip,gzip:()=>gzip,parseTar:()=>parseTar}),UP=__esmMin(()=>{zP(),BP(),VP()});function gjsifyCacheRoot(n,S){let C=process.env.XDG_CACHE_HOME;return js(C&&C.length>0?C:js(homedir(),`.cache`),`gjsify`,n,S)}function atomicWrite(n,S){try{atomicWriteStrict(n,S)}catch{}}function atomicWriteStrict(n,S){mkdirSync(js(n,`..`),{recursive:!0});let C=`${n}.tmp.${process.pid}`;writeFileSync(C,S),renameSync(C,n)}function readCacheFile(n){if(!existsSync(n))return null;try{let S=readFileSync(n);return S.length===0?null:S}catch{return null}}var WP=__esmMin(()=>{Vl(),Dm(),Hs()});function staleMs(){let n=process.env.GJSIFY_INSTALL_LOCK_STALE_MS;if(n!==void 0){let S=Number(n);if(Number.isFinite(S)&&S>0)return S}return qP}function lockingDisabled(){let n=process.env.GJSIFY_INSTALL_LOCK;if(n===void 0)return!1;let S=n.trim();return S===`0`||S===`false`}function isPidAlive(n){return existsSync(`/proc/${n}`)}function mtimeMs(n){try{return statSync(n).mtimeMs}catch{return null}}function assessLock(n){let S=js(n,KP),C=null;try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{C=null}let N=Date.now();if(C&&typeof C.pid==`number`){if(!isPidAlive(C.pid))return{stale:!0,reason:`owner pid ${C.pid} is gone`,ownerPid:C.pid};let n=typeof C.startedAt==`number`?C.startedAt:mtimeMs(S);return n!==null&&N-n>staleMs()?{stale:!0,reason:`owner pid ${C.pid} exceeded the ${staleMs()}ms staleness budget`,ownerPid:C.pid}:{stale:!1,ownerPid:C.pid}}let F=mtimeMs(n);return F===null?{stale:!1}:N-F>JP?{stale:!0,reason:`no owner recorded within the acquire grace period`}:{stale:!1}}function stealStaleLock(n){let S=`${n}.stale-${process.pid}-${++QP}`;try{renameSync(n,S)}catch{return!1}try{rmSync(S,{recursive:!0,force:!0})}catch{}return!0}function abortErr(n){let S=n&&`reason`in n?n.reason:void 0;if(S instanceof Error)return S;let C=Error(`Aborted`);return C.name=`AbortError`,C}function delay(n,S){return n<=0?Promise.resolve():new Promise((C,N)=>{let onAbort=()=>{clearTimeout(F),N(abortErr(S))},F=setTimeout(()=>{S?.removeEventListener?.(`abort`,onAbort),C()},n);if(S?.aborted){clearTimeout(F),N(abortErr(S));return}S?.addEventListener?.(`abort`,onAbort,{once:!0})})}function makeHandle(n){let S=!1;return{release(){if(S)return;S=!0;let C=ZP.get(n);if(C&&(C.count--,!(C.count>0))){ZP.delete(n);try{let S=JSON.parse(readFileSync(js(n,KP),`utf-8`));if(S.nonce!==void 0&&S.nonce!==C.nonce)return}catch{}try{rmSync(n,{recursive:!0,force:!0})}catch{}}}}}async function acquireInstallLock(n,S={}){if(lockingDisabled())return{release(){}};let C;try{C=realpathSync(n)}catch{C=Os(n)}let N=js(C,`node_modules`,GP),F=ZP.get(N);if(F)return F.count++,makeHandle(N);mkdirSync(Ps(N),{recursive:!0});let I=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,H=YP,W=!1;for(;;){if(S.signal?.aborted)throw abortErr(S.signal);try{return mkdirSync(N),writeFileSync(js(N,KP),JSON.stringify({pid:process.pid,nonce:I,startedAt:Date.now()})),ZP.set(N,{count:1,nonce:I}),makeHandle(N)}catch(n){if(n.code!==`EEXIST`)throw n}let n=assessLock(N);if(n.stale){stealStaleLock(N)&&ve.warn(`gjsify install: removed stale install lock (${n.reason}) — ${N}`);continue}if(!W){W=!0;let S=n.ownerPid===void 0?``:` (pid ${n.ownerPid})`;ve.warn(`gjsify install: waiting for a concurrent install${S} to release ${N} …`)}await delay(H,S.signal),H=Math.min(Math.round(H*1.6),XP)}}var GP,KP,qP,JP,YP,XP,ZP,QP,$P=__esmMin(()=>{ye(),Vl(),Hs(),GP=`.gjsify-install-lock`,KP=`owner.json`,qP=35*6e4,JP=15e3,YP=150,XP=1e3,ZP=new Map,QP=0});function cacheRoot$1(){return gjsifyCacheRoot(`tarballs`,eF)}function parseSri$1(n){if(!n)return null;let S=n.indexOf(`-`);if(S<=0||S===n.length-1)return null;let C=n.slice(0,S),N=n.slice(S+1).replace(/=+$/,``),F=$e.from(N,`base64`).toString(`hex`);return F.length<4?null:{algorithm:C,hex:F}}function pathFor$3(n){let S=parseSri$1(n);if(!S)return null;let C=S.hex.slice(0,2);return js(cacheRoot$1(),S.algorithm,C,`${S.hex}.tgz`)}function getCachedTarball(n){let S=pathFor$3(n);return S?readCacheFile(S):null}function putCachedTarball(n,S){let C=pathFor$3(n);C&&(existsSync(C)||atomicWrite(C,S))}function npmCacacheContentDir(){let n=process.env.GJSIFY_NPM_CACHE;if(n!==void 0){let S=n.trim();return S===``||S===`0`||S===`false`?null:js(S.endsWith(`_cacache`)?S:js(S,`_cacache`),`content-v2`)}let S=process.env.npm_config_cache;return js(S&&S.length>0?S:js(homedir(),`.npm`),`_cacache`,`content-v2`)}function npmCachePathFor(n){let S=npmCacacheContentDir();if(!S)return null;let C=parseSri$1(n);return C?js(S,C.algorithm,C.hex.slice(0,2),C.hex.slice(2,4),C.hex.slice(4)):null}function getForeignCachedTarball(n){let S=npmCachePathFor(n);return S?readCacheFile(S):null}var eF,tF=__esmMin(()=>{lt(),Vl(),Dm(),Hs(),WP(),eF=`v1`,__name$1(cacheRoot$1,`cacheRoot`),__name$1(parseSri$1,`parseSri`),__name$1(pathFor$3,`pathFor`)});function isEnabled(){let n=process.env.GJSIFY_PACKUMENT_CACHE;if(n===void 0)return!0;let S=n.trim();return!(S===`0`||S===`false`||S===``)}function cacheRoot(){return gjsifyCacheRoot(`metadata`,nF)}function shardFor(n){let S=2166136261;for(let C=0;C<n.length;C++)S^=n.charCodeAt(C),S=Math.imul(S,16777619);return(S>>>0&255).toString(16).padStart(2,`0`)}function encodePart(n){return encodeURIComponent(n).replace(/\*/g,`%2A`)}function packumentCacheKey(n,S,C){return`${C},${encodePart(n)},${encodePart(S)}`}function pathFor$2(n,S,C){if(!isEnabled())return null;let N=packumentCacheKey(n,S,C);return js(cacheRoot(),shardFor(N),`${N}.json`)}function getCachedPackument(n,S,C=`corgi`){let N=pathFor$2(n,S,C);if(!N)return null;let F=readCacheFile(N);if(!F)return null;try{let n=JSON.parse(F.toString(`utf-8`));return typeof n.etag!=`string`||!n.etag||!n.packument||typeof n.packument!=`object`?null:{etag:n.etag,packument:n.packument}}catch{return null}}function putCachedPackument(n,S,C,N,F=`corgi`){if(!C)return;let I=pathFor$2(n,S,F);I&&atomicWrite(I,JSON.stringify({etag:C,packument:N}))}var nF,rF=__esmMin(()=>{Hs(),WP(),nF=`v3`,__name$1(pathFor$2,`pathFor`)});function parseNodeMajor(n){return Number.parseInt(String(n).split(`.`,1)[0]??``,10)}function nativeBackendNodeError(n,S){if(!S)return null;let C=parseNodeMajor(n);return!Number.isFinite(C)||C>=24?null:`gjsify install (native backend) requires Node ≥ 24, but this is Node ${n}. Its prebuilt native modules are ABI-locked to Node 24 and crash on older majors. Use Node 24 (nvm/asdf locally, actions/setup-node in CI), or run with --backend npm.`}function onRealNode(){return gjsSystemVersion()===void 0?isNode():!1}function assertNativeBackendNodeVersion(){let n=nativeBackendNodeError(process.versions.node,onRealNode());if(n)throw Error(n)}var iF=__esmMin(()=>{th()});function checkList(n,S){let C=typeof S==`string`?[S]:S;if(C.length===1&&C[0]===`any`)return!0;let N=0,F=!1;for(let S of C){let C=S.charAt(0)===`!`,I=C?S.slice(1):S;if(C){if(N++,n===I)return!1}else F||=n===I}return F||N===C.length}function checkPlatform(n,S){let C=n.os?checkList(S.os,n.os):!0,N=n.cpu?checkList(S.cpu,n.cpu):!0,F=n.libc?checkList(S.libc,n.libc):!0;return n.libc&&!S.libc&&(F=!1),{ok:C&&N&&F,current:{os:S.os,cpu:S.cpu,libc:S.libc},required:{os:n.os,cpu:n.cpu,libc:n.libc}}}function declaresPlatform(n){return!!(n.os||n.cpu||n.libc)}function badPlatformError(n,S){let C=Error(`Unsupported platform for ${n}: wanted ${JSON.stringify(S.required)} (current: ${JSON.stringify(S.current)})`);return C.code=`EBADPLATFORM`,C.pkgid=n,C.current=S.current,C.required=S.required,C}function isMuslSharedObject(n){return n.includes(`libc.musl-`)||n.includes(`ld-musl-`)}function libcFromLddFile(n){let S=n.readTextFile(aF);if(S!==null)return S.includes(`musl`)?`musl`:S.includes(`GNU C Library`)?`glibc`:null}function libcFromReportData(n){return n.glibcVersionRuntime?`glibc`:Array.isArray(n.sharedObjects)&&n.sharedObjects.some(n=>isMuslSharedObject(String(n)))?`musl`:null}function libcFromLoaderScan(n,S=oF){let C=!1;for(let N of S){let S=n.listDir(N);if(S)for(let n of S){if(n.startsWith(`ld-linux`))return`glibc`;n.startsWith(`ld-musl-`)&&(C=!0)}}return C?`musl`:null}function detectLibc(n,S){if(n!==`linux`)return;let C=libcFromLddFile(S);if(C!==void 0)return C??void 0;let N=S.diagnosticReport();return N===null?libcFromLoaderScan(S)??void 0:libcFromReportData(N)??void 0}function defaultLibcProbeHost(){return{readTextFile(n){try{return readFileSync(n,`utf-8`)}catch{return null}},listDir(n){try{return readdirSync(n)}catch{return null}},diagnosticReport(){let n=process.report;if(!n||typeof n.getReport!=`function`)return null;let S=n.excludeNetwork;n.excludeNetwork=!0;try{let S=n.getReport();return{glibcVersionRuntime:S.header?.glibcVersionRuntime,sharedObjects:S.sharedObjects}}finally{n.excludeNetwork=S}}}}function hostLibc(n,S=defaultLibcProbeHost()){return cF||=(sF=detectLibc(n,S),!0),sF}function readPlatformOverrides(n){let pick=S=>{let C=n[S];if(typeof C!=`string`)return;let N=C.trim();return N===``?void 0:N},S={},C=pick(`npm_config_os`),N=pick(`npm_config_cpu`),F=pick(`npm_config_libc`);return C!==void 0&&(S.os=C),N!==void 0&&(S.cpu=N),F!==void 0&&(S.libc=F),S}function readPlatformForce(n){let S=n.npm_config_force;if(typeof S!=`string`)return!1;let C=S.trim().toLowerCase();return C===`true`||C===`1`}function resolveHostPlatform(n={}){let S=readPlatformOverrides(n.env??process.env),C=S.os??n.platform??process.platform;return{os:C,cpu:S.cpu??n.arch??process.arch,libc:S.libc??(C===`linux`?hostLibc(C,n.probe??defaultLibcProbeHost()):void 0)}}function describePlatformTarget(n){return`${n.os}-${n.cpu}${n.libc?`-${n.libc}`:``}`}var aF,oF,sF,cF,lF=__esmMin(()=>{Vl(),aF=`/usr/bin/ldd`,oF=[`/lib`,`/lib64`,`/usr/lib`],cF=!1}),uF=__exportAll$4({applyPlatformFilter:()=>applyPlatformFilter,computeOptionalFlags:()=>computeOptionalFlags,installPackagesNative:()=>installPackagesNative,parseSpec:()=>parseSpec$1,pickVersion:()=>pickVersion,requiredDepEntries:()=>requiredDepEntries,warnMissingNativeBuilds:()=>warnMissingNativeBuilds,writeBinEntry:()=>writeBinEntry});async function installPackagesNative(n){if(assertNativeBackendNodeVersion(),n.specs.length===0)throw Error(`installPackagesNative: empty specs list`);mkdirSync(n.prefix,{recursive:!0});let S=await loadNpmrc$1(n),C=makeLogger(n.verbose??!1),N=await acquireInstallLock(n.prefix,{signal:n.signal});try{return await installPackagesNativeLocked(n,S,C)}finally{N.release()}}async function installPackagesNativeLocked(n,S,C){let N=n.progress,F=js(n.prefix,fF),I=readLockfile(F),H=resolveHostPlatform(),W=readPlatformForce(process.env);C(`install: platform target %s%s`,describePlatformTarget(H),W?` (--force: checks bypassed)`:``);let q,Y=!1,X=new Set;if(n.frozen){if(!I)throw Error(`install: --immutable requires ${fF} at ${n.prefix} — none found. Run \`gjsify install\` (without --immutable) to generate one and commit it.`);let S=describeLockfileDrift(I,n.specs);if(S)throw Error(`install: --immutable but ${F} is stale.\n${S}\nRe-run \`gjsify install\` (without --immutable) to refresh the lockfile.`);C(`install: --immutable, using lockfile (%d package(s))`,Object.keys(I.packages).length),q=lockfileToNodes(I)}else if(!n.refreshLockfile&&I&&I.lockfileVersion===pF&&lockfileMatchesRequest(I,n.specs))C(`install: using lockfile (%d package(s))`,Object.keys(I.packages).length),q=lockfileToNodes(I);else{let F=!n.refreshLockfile&&I?buildPreferredVersions(I):void 0;C(`install: resolving %d top-level spec(s) → %s%s`,n.specs.length,n.prefix,F?` (preserving ${F.size} locked name(s))`:``);let H=await resolveDeps(n.specs,S,C,n.overrides,n.skipDeps,n.signal,N,F,n.workspaceNames,n.specOrigins,n.optionalSpecs);q=H.nodes,X=H.skippedEdges,Y=!0}if(computeOptionalFlags(q,requiredTopLevelNames(n.specs,n.optionalSpecs),C),assertRequiredEdgesResolved(q,X),Y&&n.lockfile&&(writeLockfile(F,n.specs,q),C(`install: wrote %s (%d entries)`,fF,q.length)),n.workspaceNames&&n.workspaceNames.size>0){let S=q.length;q=q.filter(S=>!n.workspaceNames.has(S.name));let N=S-q.length;N>0&&C(`install: %d workspace-provided package(s) symlinked, not fetched`,N)}let Z=applyPlatformFilter(q,H,W,C);return C(`install: downloading %d tarball(s)`,Z.length),await downloadAndExtractAll(Z,n.prefix,S,C,n.signal,N),await linkBins(Z,n.prefix,C),warnMissingNativeBuilds(Z,n.prefix,C),C(`install: done`),topLevelResolutions(n.specs,q)}function errMsg(n){return n instanceof Error?n.message:String(n)}function applyPlatformFilter(n,S,C,N){let F=[],I=0;for(let H of n){let n=H.platform;if(!n||!declaresPlatform(n)){F.push(H);continue}let W=checkPlatform(n,S);if(W.ok){F.push(H);continue}let q=`${H.name}@${H.version}`;if(!H.optional){if(C){N(`platform-forced: %s (required, incompatible, installed anyway via --force)`,q),F.push(H);continue}throw badPlatformError(q,W)}H.inert=!0,I++,N(`platform-skip: %s (%s) current=%s required=%s`,q,H.installPath,JSON.stringify(W.current),JSON.stringify(W.required))}return I>0&&N(`install: %d optional package(s) inert — not installable on %s`,I,describePlatformTarget(S)),F}function warnMissingNativeBuilds(n,S,C){let N=process.platform,F=process.arch,I=[`preinstall`,`install`,`postinstall`];for(let H of n){let n=js(S,H.installPath),W;try{W=JSON.parse(readFileSync(js(n,`package.json`),`utf8`))?.scripts}catch{continue}if(!W||typeof W!=`object`)continue;let q=I.find(n=>typeof W[n]==`string`);if(q===void 0)continue;let Y=!1;try{let S=js(n,`prebuilds`);for(let n of readdirSync(S))if(n.startsWith(`${N}-`)&&readdirSync(js(S,n)).length>0){Y=!0;break}}catch{}if(!Y)try{Y=readdirSync(js(n,`build`,`Release`)).some(n=>n.endsWith(`.node`)||n.endsWith(`.so`))}catch{}Y||C("install: WARNING — %s declares a native `%s` build script but ships no %s-%s prebuild, and gjsify install does not run build scripts (node-free). It will not load until built: run `node-gyp rebuild` in %s, or use a version that ships a %s-%s prebuild.",H.name,q,N,F,H.installPath,N,F)}}function topLevelResolutions(n,S){let C=new Map;for(let n of S)n.installPath===`node_modules/${n.name}`&&C.set(n.name,n);let N=[];for(let S of n){let n=parseSpecName(S),F=C.get(n);F&&N.push({name:F.name,version:F.version})}return N}function parseSpecName(n){if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S===-1)return n;let C=n.indexOf(`@`,S+1);return C===-1?n:n.slice(0,C)}let S=n.indexOf(`@`);return S===-1?n:n.slice(0,S)}async function resolveDeps(n,S,C,N,F,I,H,W,q,Y,X){H?.beginPhase(`resolve`,n.length);let applyOverride=(n,S)=>{if(!N)return S;let F=N[n];return typeof F!=`string`||F.length===0||F===S?S:(C(`install: override %s %s → %s`,n,S,F),F)},Z=new Map,fetchPkg=n=>{let N=Z.get(n);if(N)return N;let F=fetchPackumentWithDiskCache(n,S,C,I,`full`);return Z.set(n,F),F},te=new Map,ne=new Map,re=new Set,ie=new Map,ae=n.map(parseSpec$1).map(n=>{let S=applyOverride(n.name,n.range),C=ie.get(n.name);C||(C=new Map,ie.set(n.name,C));let N=C.get(S);N||(N=new Set,C.set(S,N));for(let S of Y?.get(`${n.name}@${n.range}`)??[])N.add(S);return{from:null,name:n.name,range:S,required:!X?.has(n.name)}});for(;ae.length>0;){let n=ae.splice(0,ae.length),S=[],N=new Set;for(let C of n)Z.has(C.name)||N.has(C.name)||(N.add(C.name),S.push(C.name));await prefetchPackuments(S,fetchPkg,I);for(let S=0;S<n.length;S++){let N=n[S];if(q?.has(N.name))continue;let I=findVisible(N.from,N.name,te);if(I&&satisfiesRange(I.version,N.range))continue;let Y=null;try{let I=await fetchPkg(N.name),q=preferredVersionFor(W?.get(N.name),N.range);if(Y=pickVersion(I,N.range,q),!Y)throw Error(`No version of ${N.name} satisfies ${N.range}`);let X=I.versions[Y];if(!X)throw Error(`Packument for ${N.name} promised ${Y} but no entry exists`);let Z=decidePlacement(N.from,N.name,Y,ne),re={name:N.name,version:Y,tarballUrl:X.dist.tarball,integrity:X.dist.integrity,installPath:Z,dependencies:X.dependencies??{},optionalDependencies:X.optionalDependencies??{},bin:X.bin,platform:platformDeclarationOf(X),optional:!N.required};if(te.set(Z,re),Z===`node_modules/${N.name}`&&ne.set(N.name,re),C(`resolve: %s@%s ← %s (at %s)`,N.name,Y,N.range,Z),H?.update({phase:`resolve`,current:te.size,total:te.size+(n.length-S-1)+ae.length,name:`${N.name}@${Y}`}),!F){for(let[n,S]of requiredDepEntries(re))ae.push({from:Z,name:n,range:applyOverride(n,S),required:!re.optional});for(let[n,S]of Object.entries(re.optionalDependencies))ae.push({from:Z,name:n,range:applyOverride(n,S),required:!1})}}catch(n){if(!N.required){re.add(edgeKey(N.from,N.name)),C(`resolve: optional dep %s@%s skipped (%s)`,N.name,N.range,errMsg(n));continue}throw n}}}return H?.endPhase(`resolve`),emitTopLevelConflictWarnings(ie,ne),{nodes:Array.from(te.values()),skippedEdges:re}}function platformDeclarationOf(n){let S={os:n.os,cpu:n.cpu,libc:n.libc};return declaresPlatform(S)?S:void 0}function edgeKey(n,S){return`${n??``}\n${S}`}function parseEdgeKey(n){let S=n.indexOf(`
|
|
886
|
-
`),C=n.slice(0,S);return{from:C===``?null:C,name:n.slice(S+1)}}function requiredTopLevelNames(n,S){let C=new Set;for(let N of n){let n=parseSpecName(N);S?.has(n)||C.add(n)}return C}function requiredDepEntries(n){let S=[];for(let[C,N]of Object.entries(n.dependencies))C in n.optionalDependencies||S.push([C,N]);return S}function computeOptionalFlags(n,S,C){let N=new Map;for(let S of n)N.set(S.installPath,S);let F=new Set,I=[],enter=n=>{F.has(n.installPath)||(F.add(n.installPath),I.push(n.installPath))};for(let n of S){let S=N.get(`node_modules/${n}`);S&&enter(S)}for(;I.length>0;){let n=I.pop();if(n===void 0)break;let S=N.get(n);if(S)for(let[C]of requiredDepEntries(S)){let S=findVisible(n,C,N);S&&enter(S)}}let H=0;for(let S of n){let n=!F.has(S.installPath);(S.optional??!1)!==n&&H++,S.optional=n}C(`install: optionality fixpoint — %d of %d node(s) reachable only via optional edges%s`,n.length-F.size,n.length,H>0?`; corrected ${H} incoming flag(s)`:``)}function assertRequiredEdgesResolved(n,S){if(S.size===0)return;let C=new Map;for(let S of n)C.set(S.installPath,S);for(let n of S){let{from:S,name:N}=parseEdgeKey(n);if(S===null)continue;let F=C.get(S);if(F&&!F.optional&&!(N in F.optionalDependencies))throw Error(`install: required dependency ${N} of ${F.name}@${F.version} (${F.installPath}) could not be resolved.\nThe failure was tolerated during the walk because ${F.name} looked optional at that point, but the final dependency graph makes it required — so ${N} is required too and the tree would be incomplete.\nRe-run with --verbose and look for the "resolve: optional dep ${N}@… skipped (…)" line for the underlying cause.`)}}function emitTopLevelConflictWarnings(n,S){for(let[C,N]of n){if(N.size<2)continue;let n=S.get(C);if(!n)continue;let describe=(n,S)=>S.size>0?`${n} (requested by ${[...S].join(`, `)})`:n,F=[],I=[];for(let[S,C]of N){let N;try{N=satisfies(n.version,new
|
|
885
|
+
`});function makeProgressReporter(n={}){if(n.enabled===!1)return NP;let S=n.stream??process.stderr,C=!!S.isTTY;return n.enabled??!0?C?makeTtyReporter(S):makePlainReporter(S):NP}function makeTtyReporter(n){let S=0,C=``;function render(N,F=!1){let I=Date.now();!F&&I-S<33&&N===C||(S=I,C=N,n.write(`\r\x1B[2K`+N))}function clearLine(){n.write(`\r\x1B[2K`),C=``}return{beginPhase(S,C){render(formatBar(S,0,C,void 0,n.columns??80),!0)},update(S){render(formatBar(S.phase,S.current,S.total,S.name,n.columns??80))},endPhase(S){let C=MP[S];clearLine(),n.write(`gjsify install: ${C} done\n`)}}}function makePlainReporter(n){let S=0,C=0;return{beginPhase(N,F){S=Date.now(),C=0,n.write(`gjsify install: ${MP[N]} ${F} package(s)\n`)},update(N){let F=Date.now();if(F-S<PP||N.current<=C)return;S=F,C=N.current;let I=N.total>0?Math.round(N.current/N.total*100):0;n.write(`gjsify install: ${MP[N.phase]} ${N.current}/${N.total} (${I}%)\n`)},endPhase(S){n.write(`gjsify install: ${MP[S]} done\n`)}}}function formatBar(n,S,C,N,F){let I=MP[n],H=C>0?Math.min(1,S/C):0,W=`${S}/${C}`,q=`gjsify install: ${I} `,Y=` ${W}`+(N?` ${N}`:``),X=Math.max(8,Math.min(40,F-q.length-Y.length-4)),Z=Math.round(H*X),te=`█`.repeat(Z)+`░`.repeat(X-Z),ne=`${q}[${te}]${Y}`;if(ne.length>F){let n=ne.length-F+1,S=N&&N.length>n?N.slice(0,N.length-n-1)+`…`:``;ne=`${q}[${te}] ${W}${S?` `+S:``}`}return ne}var MP,NP,PP,FP=__esmMin(()=>{MP={resolve:`resolving`,download:`downloading`,extract:`extracting`,link:`linking bins`},NP={update(){},beginPhase(){},endPhase(){}},PP=5e3});function parse(n){try{return new SemVer(n)}catch{return null}}function compare(n,S){let C=n instanceof SemVer?n:new SemVer(n),N=S instanceof SemVer?S:new SemVer(S);return C.compare(N)}function satisfies(n,S){let C=S instanceof RP?S:new RP(S),N=n instanceof SemVer?n:parse(String(n));return N?C.test(N):!1}function maxSatisfying(n,S){let C=S instanceof RP?S:new RP(S),N=null;for(let S of n){let n=parse(S);!n||!C.test(n)||(N===null||n.compare(N)>0)&&(N=n)}return N?N.version:null}function testComparator(n,S){if(n.semver===null)return!0;let C=S.compare(n.semver);switch(n.operator){case``:case`=`:return C===0;case`<`:return C<0;case`<=`:return C<=0;case`>`:return C>0;case`>=`:return C>=0}}function formatComparator(n){return n.semver===null?`*`:`${n.operator}${n.semver.version}`}function parseRangePart(n){let S=n.trim();if(S===``||S===`*`||S.toLowerCase()===`latest`)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let C=S.match(/^\s*(\S+)\s+-\s+(\S+)\s*$/);if(C)return hyphenRange(C[1],C[2]);let N=S.replace(/(<=|>=|<|>|=)\s+(?=\S)/g,`$1`).split(/\s+/),F=[];for(let n of N)F.push(...parseSimple(n));return F}function parseSimple(n){if(n===`*`||n===``||n.toLowerCase()===`latest`)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];if(n.startsWith(`^`))return caretRange(n.slice(1));if(n.startsWith(`~`))return tildeRange(n.slice(1).replace(/^>/,``));let S=n.match(/^(<=|>=|<|>|=)\s*(.+)$/);if(S){let n=S[1];return primitiveRange(n,S[2])}return partialRange(n)}function parsePartial(n){let S=n.trim().replace(/^v/,``);if(S===``||S===`*`)return{major:null,minor:null,patch:null,pre:``,build:``};let C=``,N=``,F=S,I=F.indexOf(`+`);I>=0&&(N=F.slice(I+1),F=F.slice(0,I));let H=F.indexOf(`-`);H>=0&&(C=F.slice(H+1),F=F.slice(0,H));let W=F.split(`.`),xr=S=>{if(S===void 0||S===``||S===`x`||S===`X`||S===`*`)return null;if(!/^\d+$/.test(S))throw TypeError(`Invalid partial version: ${n}`);return Number(S)};return{major:xr(W[0]),minor:xr(W[1]),patch:xr(W[2]),pre:C,build:N}}function partialToVersion(n){return`${n.major??0}.${n.minor??0}.${n.patch??0}${n.pre?`-${n.pre}`:``}${n.build?`+${n.build}`:``}`}function partialRange(n){let S=parsePartial(n);return S.major===null?[{operator:`>=`,semver:new SemVer(`0.0.0`)}]:S.minor===null?[{operator:`>=`,semver:new SemVer(`${S.major}.0.0`)},{operator:`<`,semver:new SemVer(`${S.major+1}.0.0`)}]:S.patch===null?[{operator:`>=`,semver:new SemVer(`${S.major}.${S.minor}.0`)},{operator:`<`,semver:new SemVer(`${S.major}.${S.minor+1}.0`)}]:[{operator:`=`,semver:new SemVer(partialToVersion(S))}]}function caretRange(n){let S=parsePartial(n);if(S.major===null)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let C=`${S.major}.${S.minor??0}.${S.patch??0}${S.pre?`-${S.pre}`:``}`,N;return N=S.major>0||S.minor===null?`${S.major+1}.0.0`:S.minor>0||S.patch===null?`0.${S.minor+1}.0`:`0.0.${S.patch+1}`,[{operator:`>=`,semver:new SemVer(C)},{operator:`<`,semver:new SemVer(N)}]}function tildeRange(n){let S=parsePartial(n);if(S.major===null)return[{operator:`>=`,semver:new SemVer(`0.0.0`)}];let C=`${S.major}.${S.minor??0}.${S.patch??0}${S.pre?`-${S.pre}`:``}`,N=S.minor===null?`${S.major+1}.0.0`:`${S.major}.${S.minor+1}.0`;return[{operator:`>=`,semver:new SemVer(C)},{operator:`<`,semver:new SemVer(N)}]}function primitiveRange(n,S){let C=parsePartial(S);return C.major===null?[{operator:`>=`,semver:new SemVer(`0.0.0`)}]:n===`=`||n===``?partialRange(S):n===`>`?C.minor===null?[{operator:`>=`,semver:new SemVer(`${C.major+1}.0.0`)}]:C.patch===null?[{operator:`>=`,semver:new SemVer(`${C.major}.${C.minor+1}.0`)}]:[{operator:`>`,semver:new SemVer(partialToVersion(C))}]:n===`<`?C.minor===null?[{operator:`<`,semver:new SemVer(`${C.major}.0.0`)}]:C.patch===null?[{operator:`<`,semver:new SemVer(`${C.major}.${C.minor}.0`)}]:[{operator:`<`,semver:new SemVer(partialToVersion(C))}]:n===`>=`?[{operator:`>=`,semver:new SemVer(partialToVersion(C))}]:C.minor===null?[{operator:`<`,semver:new SemVer(`${C.major+1}.0.0`)}]:C.patch===null?[{operator:`<`,semver:new SemVer(`${C.major}.${C.minor+1}.0`)}]:[{operator:`<=`,semver:new SemVer(partialToVersion(C))}]}function hyphenRange(n,S){let C=parsePartial(n),N=parsePartial(S),F=C.major===null?{operator:`>=`,semver:new SemVer(`0.0.0`)}:{operator:`>=`,semver:new SemVer(`${C.major}.${C.minor??0}.${C.patch??0}${C.pre?`-${C.pre}`:``}`)},I;return I=N.major===null?{operator:`>=`,semver:new SemVer(`0.0.0`)}:N.minor===null?{operator:`<`,semver:new SemVer(`${N.major+1}.0.0`)}:N.patch===null?{operator:`<`,semver:new SemVer(`${N.major}.${N.minor+1}.0`)}:{operator:`<=`,semver:new SemVer(`${N.major}.${N.minor}.${N.patch}${N.pre?`-${N.pre}`:``}`)},[F,I]}var IP,LP,SemVer,RP,zP=__esmMin(()=>{IP=/^(0|[1-9]\d*)$/,LP=/^(\d+)\.(\d+)\.(\d+)(?:-((?:[0-9A-Za-z-]+)(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,SemVer=class{major;minor;patch;prerelease;build;version;constructor(n){let S=String(n).trim().replace(/^v/,``),C=LP.exec(S);if(!C)throw TypeError(`Invalid Version: ${n}`);this.major=Number(C[1]),this.minor=Number(C[2]),this.patch=Number(C[3]),this.prerelease=C[4]?C[4].split(`.`).map(n=>IP.test(n)?Number(n):n):[],this.build=C[5]?C[5].split(`.`):[],this.version=`${this.major}.${this.minor}.${this.patch}`+(this.prerelease.length?`-${this.prerelease.join(`.`)}`:``)+(this.build.length?`+${this.build.join(`.`)}`:``)}compare(n){return this.major===n.major?this.minor===n.minor?this.patch===n.patch?this.comparePre(n):this.patch<n.patch?-1:1:this.minor<n.minor?-1:1:this.major<n.major?-1:1}comparePre(n){let S=this.prerelease,C=n.prerelease;if(S.length===0&&C.length===0)return 0;if(S.length===0)return 1;if(C.length===0)return-1;for(let n=0;;n++){let N=S[n],F=C[n];if(N===void 0&&F===void 0)return 0;if(F===void 0)return 1;if(N===void 0)return-1;if(N===F)continue;let I=typeof N==`number`,H=typeof F==`number`;return I&&!H?-1:!I&&H?1:N<F?-1:1}}toString(){return this.version}},RP=class Range{raw;set;constructor(n){if(n instanceof Range){this.raw=n.raw,this.set=n.set;return}this.raw=String(n).trim();let S=this.raw.split(/\s*\|\|\s*/),C=[];for(let n of S){let S=parseRangePart(n);if(S.length===0)throw TypeError(`Invalid range: ${this.raw}`);C.push(S)}if(C.length===0)throw TypeError(`Invalid range: ${this.raw}`);this.set=C}test(n){let S=n instanceof SemVer?n:parse(String(n));if(!S)return!1;for(let n of this.set)if(n.every(n=>testComparator(n,S))){if(S.prerelease.length>0&&!n.some(n=>n.semver!==null&&n.semver.prerelease.length>0&&n.semver.major===S.major&&n.semver.minor===S.minor&&n.semver.patch===S.patch))continue;return!0}return!1}format(){return this.set.map(n=>n.map(formatComparator).join(` `)).join(` || `)}toString(){return this.format()}}});function parseTar(n){let S=[],C=null,N=null,F=null,I=0;for(;I+512<=n.length;){let H=n.subarray(I,I+512);if(allZeros(H)){let S=n.subarray(I+512,I+2*512);if(S.length===512&&allZeros(S))break;I+=512;continue}if(!validateChecksum(H))throw new TarParseError(`Bad header checksum at offset ${I} — file is not a valid tar archive`);let W=readString(H,0,100),q=parseOctal(H,100,8),Y=parseOctal(H,124,12),X=parseOctal(H,136,12),Z=String.fromCharCode(H[156]||0),te=readString(H,157,100),ne=readString(H,257,6),re=readString(H,345,155),ie=readString(H,265,32),ae=readString(H,297,32);I+=512;let oe=n.subarray(I,I+Y);if(I+=alignToBlock(Y),Z===`x`){C=parsePaxRecords(oe);continue}if(Z===`g`)continue;if(Z===`L`){N=bytesToString(oe).replace(/\0+$/,``);continue}if(Z===`K`){F=bytesToString(oe).replace(/\0+$/,``);continue}let se=W;ne===`ustar`&&re!==``&&(se=`${re}/${W}`),N!==null&&(se=N,N=null);let Q=te;if(F!==null&&(Q=F,F=null),C!==null){let N=C.get(`path`);N!==void 0&&(se=N);let F=C.get(`linkpath`);F!==void 0&&(Q=F);let H=C.get(`size`);if(H!==void 0){let N=Number(H);if(Number.isFinite(N)){let F=I-alignToBlock(Y),H=n.subarray(F,F+N);I=F+alignToBlock(N),C=null,S.push(buildEntry(se,Q,Z,q,X,ie,ae,H));continue}}C=null}S.push(buildEntry(se,Q,Z,q,X,ie,ae,oe))}return S}function buildEntry(n,S,C,N,F,I,H,W){return{name:n,linkname:S,type:typeflagToType(C,n),mode:N,mtime:F,body:W,uname:I,gname:H}}function typeflagToType(n,S){switch(n){case`0`:case`\0`:case``:return S.endsWith(`/`)?`directory`:`file`;case`1`:return`hardlink`;case`2`:return`symlink`;case`5`:return`directory`;case`x`:return`pax-header`;case`g`:return`pax-global`;case`L`:return`gnu-longname`;case`K`:return`gnu-longlink`;default:return`unknown`}}function parsePaxRecords(n){let S=new Map,C=0;for(;C<n.length;){let N=C;for(;N<n.length&&n[N]!==32;)N++;if(N>=n.length)break;let F=bytesToString(n.subarray(C,N)),I=Number(F);if(!Number.isFinite(I)||I<=0)break;let H=C+I;if(H>n.length)break;let W=bytesToString(n.subarray(N+1,H-1)),q=W.indexOf(`=`);if(q>0){let n=W.slice(0,q),C=W.slice(q+1);S.set(n,C)}C=H}return S}function readString(n,S,C){let N=S,F=S+C;for(;N<F&&n[N]!==0;)N++;return bytesToString(n.subarray(S,N))}function bytesToString(n){return new TextDecoder(`utf-8`,{fatal:!1}).decode(n)}function parseOctal(n,S,C){if(C>0&&n[S]&128){let N=n[S]&127;for(let F=1;F<C;F++)N=N*256+n[S+F];return N}let N=``;for(let F=0;F<C;F++){let C=n[S+F];C===0||C===32||(N+=String.fromCharCode(C))}return N===``?0:parseInt(N,8)}function alignToBlock(n){return Math.ceil(n/512)*512}function allZeros(n){for(let S=0;S<n.length;S++)if(n[S]!==0)return!1;return!0}function validateChecksum(n){let S=parseOctal(n,148,8),C=0,N=0;for(let S=0;S<512;S++){let F=S>=148&&S<156?32:n[S];C+=F,N+=F>127?F-256:F}return S===C||S===N}var TarParseError,BP=__esmMin(()=>{TarParseError=class extends Error{constructor(n){super(n),this.name=`TarParseError`}}});function createTarball(n){let S=[];for(let C of n){if(`directory`in C&&C.directory===!0){S.push(buildHeader$1(ensureTrailingSlash(C.name),0,`5`,C.mode??493,C.mtime??0));continue}let n=C,N=typeof n.body==`string`?new TextEncoder().encode(n.body):n.body,F=n.mode??defaultFileMode(N);S.push(buildHeader$1(n.name,N.byteLength,`0`,F,n.mtime??0)),S.push(N);let I=padTo512(N.byteLength);I>0&&S.push(new Uint8Array(I))}return S.push(new Uint8Array(512*2)),concatChunks(S)}function buildHeader$1(n,S,C,N,F){let{prefix:I,basename:H}=splitPathForUstar(n),W=new Uint8Array(512);writeAscii(W,H,0,100),writeOctal(W,N&4095,100,7),W[107]=0,writeOctal(W,0,108,7),W[115]=0,writeOctal(W,0,116,7),W[123]=0,writeOctal(W,S,124,11),W[135]=0,writeOctal(W,F,136,11),W[147]=0;for(let n=148;n<156;n++)W[n]=32;W[156]=C.charCodeAt(0),writeAscii(W,`ustar\0`,257,6),writeAscii(W,`00`,263,2),I&&writeAscii(W,I,345,155);let q=0;for(let n=0;n<512;n++)q+=W[n];return writeAscii(W,q.toString(8).padStart(6,`0`),148,6),W[154]=0,W[155]=32,W}function splitPathForUstar(n){if(n.length<=100)return{prefix:``,basename:n};if(n.length>255)throw Error(`createTarball: path too long (${n.length} > 255 chars): ${n}`);for(let S=Math.min(n.length-1,155);S>0;S--)if(n[S]===`/`&&n.length-S-1<=100)return{prefix:n.slice(0,S),basename:n.slice(S+1)};throw Error(`createTarball: cannot split path into ustar prefix+basename (basename slot is 100 chars): ${n}`)}function writeAscii(n,S,C,N){let F=new TextEncoder().encode(S);if(F.length>N)throw Error(`createTarball: field too long (${F.length} > ${N}): "${S}"`);n.set(F,C)}function writeOctal(n,S,C,N){writeAscii(n,S.toString(8).padStart(N,`0`),C,N)}function padTo512(n){let S=n%512;return S===0?0:512-S}function ensureTrailingSlash(n){return n.endsWith(`/`)?n:`${n}/`}function defaultFileMode(n){return n.length>=2&&n[0]===35&&n[1]===33?493:420}function concatChunks(n){let S=0;for(let C of n)S+=C.byteLength;let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.byteLength;return C}var VP=__esmMin(()=>{__name$1(buildHeader$1,`buildHeader`)});async function extractTarball(n,S,C={}){let N=n instanceof Uint8Array?n:new Uint8Array(n),F=parseTar(C.gzip??(N.length>=2&&N[0]===31&&N[1]===139)?await gunzip(N):N);mkdirSync(S,{recursive:!0});let I=C.strip??1,H=C.preventEscape??!0,W={files:[],directories:[],symlinks:[],skipped:0};for(let n of F){let N=stripComponents(n.name,I);if(N===null||N===``){W.skipped++;continue}let F=Os(S,N);if(H&&!isInside$2(F,S))throw Error(`tar: refusing to extract ${n.name} outside ${S} (resolved=${F})`);if(C.filter&&!C.filter(n,F)){W.skipped++;continue}if(n.type===`directory`){mkdirSync(F,{recursive:!0}),W.directories.push(F);continue}if(n.type===`file`){mkdirSync(Ps(F),{recursive:!0}),writeFileSync(F,n.body);let S=C.chmod?.(n,F)??n.mode&511;if(S>0)try{chmodSync(F,S)}catch{}W.files.push(F);continue}if(n.type===`symlink`){mkdirSync(Ps(F),{recursive:!0});try{symlinkSync(n.linkname,F),W.symlinks.push(F)}catch{writeFileSync(F,n.linkname),W.files.push(F)}continue}W.skipped++}return W}async function gunzip(n){let S=globalThis.DecompressionStream;if(typeof S!=`function`)throw Error(`@gjsify/tar: globalThis.DecompressionStream is not available — import '@gjsify/compression-streams/register' on GJS to register it`);return drainStream(new Blob([new Uint8Array(n)]).stream().pipeThrough(new S(`gzip`)))}async function gzip(n){let S=globalThis.CompressionStream;if(typeof S!=`function`)throw Error(`@gjsify/tar: globalThis.CompressionStream is not available — import '@gjsify/compression-streams/register' on GJS to register it`);return drainStream(new Blob([new Uint8Array(n)]).stream().pipeThrough(new S(`gzip`)))}async function drainStream(n){let S=[],C=0,N=n.getReader();for(;;){let{value:n,done:F}=await N.read();if(F)break;let I=n instanceof Uint8Array?n:new Uint8Array(n);S.push(I),C+=I.length}let F=new Uint8Array(C),I=0;for(let n of S)F.set(n,I),I+=n.length;return F}function stripComponents(n,S){if(S<=0)return n;let C=n.split(`/`).filter(n=>n!==``);return C.length<=S?null:C.slice(S).join(`/`)}function isInside$2(n,S){let C=Ms(S,n);return C!==``&&!C.startsWith(`..`)&&!As(C)}var HP=__esmMin(()=>{BP(),Vl(),Hs(),__name$1(isInside$2,`isInside`)}),UP=__exportAll$4({BLOCK_SIZE:()=>512,TarParseError:()=>TarParseError,createTarball:()=>createTarball,extractTarball:()=>extractTarball,gunzip:()=>gunzip,gzip:()=>gzip,parseTar:()=>parseTar}),WP=__esmMin(()=>{BP(),VP(),HP()});function gjsifyCacheRoot(n,S){let C=process.env.XDG_CACHE_HOME;return js(C&&C.length>0?C:js(homedir(),`.cache`),`gjsify`,n,S)}function atomicWrite(n,S){try{atomicWriteStrict(n,S)}catch{}}function atomicWriteStrict(n,S){mkdirSync(js(n,`..`),{recursive:!0});let C=`${n}.tmp.${process.pid}`;writeFileSync(C,S),renameSync(C,n)}function readCacheFile(n){if(!existsSync(n))return null;try{let S=readFileSync(n);return S.length===0?null:S}catch{return null}}var GP=__esmMin(()=>{Vl(),Dm(),Hs()});function staleMs(){let n=process.env.GJSIFY_INSTALL_LOCK_STALE_MS;if(n!==void 0){let S=Number(n);if(Number.isFinite(S)&&S>0)return S}return JP}function lockingDisabled(){let n=process.env.GJSIFY_INSTALL_LOCK;if(n===void 0)return!1;let S=n.trim();return S===`0`||S===`false`}function isPidAlive(n){return existsSync(`/proc/${n}`)}function mtimeMs(n){try{return statSync(n).mtimeMs}catch{return null}}function assessLock(n){let S=js(n,qP),C=null;try{C=JSON.parse(readFileSync(S,`utf-8`))}catch{C=null}let N=Date.now();if(C&&typeof C.pid==`number`){if(!isPidAlive(C.pid))return{stale:!0,reason:`owner pid ${C.pid} is gone`,ownerPid:C.pid};let n=typeof C.startedAt==`number`?C.startedAt:mtimeMs(S);return n!==null&&N-n>staleMs()?{stale:!0,reason:`owner pid ${C.pid} exceeded the ${staleMs()}ms staleness budget`,ownerPid:C.pid}:{stale:!1,ownerPid:C.pid}}let F=mtimeMs(n);return F===null?{stale:!1}:N-F>YP?{stale:!0,reason:`no owner recorded within the acquire grace period`}:{stale:!1}}function stealStaleLock(n){let S=`${n}.stale-${process.pid}-${++$P}`;try{renameSync(n,S)}catch{return!1}try{rmSync(S,{recursive:!0,force:!0})}catch{}return!0}function abortErr(n){let S=n&&`reason`in n?n.reason:void 0;if(S instanceof Error)return S;let C=Error(`Aborted`);return C.name=`AbortError`,C}function delay(n,S){return n<=0?Promise.resolve():new Promise((C,N)=>{let onAbort=()=>{clearTimeout(F),N(abortErr(S))},F=setTimeout(()=>{S?.removeEventListener?.(`abort`,onAbort),C()},n);if(S?.aborted){clearTimeout(F),N(abortErr(S));return}S?.addEventListener?.(`abort`,onAbort,{once:!0})})}function makeHandle(n){let S=!1;return{release(){if(S)return;S=!0;let C=QP.get(n);if(C&&(C.count--,!(C.count>0))){QP.delete(n);try{let S=JSON.parse(readFileSync(js(n,qP),`utf-8`));if(S.nonce!==void 0&&S.nonce!==C.nonce)return}catch{}try{rmSync(n,{recursive:!0,force:!0})}catch{}}}}}async function acquireInstallLock(n,S={}){if(lockingDisabled())return{release(){}};let C;try{C=realpathSync(n)}catch{C=Os(n)}let N=js(C,`node_modules`,KP),F=QP.get(N);if(F)return F.count++,makeHandle(N);mkdirSync(Ps(N),{recursive:!0});let I=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,H=XP,W=!1;for(;;){if(S.signal?.aborted)throw abortErr(S.signal);try{return mkdirSync(N),writeFileSync(js(N,qP),JSON.stringify({pid:process.pid,nonce:I,startedAt:Date.now()})),QP.set(N,{count:1,nonce:I}),makeHandle(N)}catch(n){if(n.code!==`EEXIST`)throw n}let n=assessLock(N);if(n.stale){stealStaleLock(N)&&ve.warn(`gjsify install: removed stale install lock (${n.reason}) — ${N}`);continue}if(!W){W=!0;let S=n.ownerPid===void 0?``:` (pid ${n.ownerPid})`;ve.warn(`gjsify install: waiting for a concurrent install${S} to release ${N} …`)}await delay(H,S.signal),H=Math.min(Math.round(H*1.6),ZP)}}var KP,qP,JP,YP,XP,ZP,QP,$P,eF=__esmMin(()=>{ye(),Vl(),Hs(),KP=`.gjsify-install-lock`,qP=`owner.json`,JP=35*6e4,YP=15e3,XP=150,ZP=1e3,QP=new Map,$P=0});function cacheRoot$1(){return gjsifyCacheRoot(`tarballs`,tF)}function parseSri$1(n){if(!n)return null;let S=n.indexOf(`-`);if(S<=0||S===n.length-1)return null;let C=n.slice(0,S),N=n.slice(S+1).replace(/=+$/,``),F=$e.from(N,`base64`).toString(`hex`);return F.length<4?null:{algorithm:C,hex:F}}function pathFor$3(n){let S=parseSri$1(n);if(!S)return null;let C=S.hex.slice(0,2);return js(cacheRoot$1(),S.algorithm,C,`${S.hex}.tgz`)}function getCachedTarball(n){let S=pathFor$3(n);return S?readCacheFile(S):null}function putCachedTarball(n,S){let C=pathFor$3(n);C&&(existsSync(C)||atomicWrite(C,S))}function npmCacacheContentDir(){let n=process.env.GJSIFY_NPM_CACHE;if(n!==void 0){let S=n.trim();return S===``||S===`0`||S===`false`?null:js(S.endsWith(`_cacache`)?S:js(S,`_cacache`),`content-v2`)}let S=process.env.npm_config_cache;return js(S&&S.length>0?S:js(homedir(),`.npm`),`_cacache`,`content-v2`)}function npmCachePathFor(n){let S=npmCacacheContentDir();if(!S)return null;let C=parseSri$1(n);return C?js(S,C.algorithm,C.hex.slice(0,2),C.hex.slice(2,4),C.hex.slice(4)):null}function getForeignCachedTarball(n){let S=npmCachePathFor(n);return S?readCacheFile(S):null}var tF,nF=__esmMin(()=>{lt(),Vl(),Dm(),Hs(),GP(),tF=`v1`,__name$1(cacheRoot$1,`cacheRoot`),__name$1(parseSri$1,`parseSri`),__name$1(pathFor$3,`pathFor`)});function isEnabled(){let n=process.env.GJSIFY_PACKUMENT_CACHE;if(n===void 0)return!0;let S=n.trim();return!(S===`0`||S===`false`||S===``)}function cacheRoot(){return gjsifyCacheRoot(`metadata`,rF)}function shardFor(n){let S=2166136261;for(let C=0;C<n.length;C++)S^=n.charCodeAt(C),S=Math.imul(S,16777619);return(S>>>0&255).toString(16).padStart(2,`0`)}function encodePart(n){return encodeURIComponent(n).replace(/\*/g,`%2A`)}function packumentCacheKey(n,S,C){return`${C},${encodePart(n)},${encodePart(S)}`}function pathFor$2(n,S,C){if(!isEnabled())return null;let N=packumentCacheKey(n,S,C);return js(cacheRoot(),shardFor(N),`${N}.json`)}function getCachedPackument(n,S,C=`corgi`){let N=pathFor$2(n,S,C);if(!N)return null;let F=readCacheFile(N);if(!F)return null;try{let n=JSON.parse(F.toString(`utf-8`));return typeof n.etag!=`string`||!n.etag||!n.packument||typeof n.packument!=`object`?null:{etag:n.etag,packument:n.packument}}catch{return null}}function putCachedPackument(n,S,C,N,F=`corgi`){if(!C)return;let I=pathFor$2(n,S,F);I&&atomicWrite(I,JSON.stringify({etag:C,packument:N}))}var rF,iF=__esmMin(()=>{Hs(),GP(),rF=`v3`,__name$1(pathFor$2,`pathFor`)});function parseNodeMajor(n){return Number.parseInt(String(n).split(`.`,1)[0]??``,10)}function nativeBackendNodeError(n,S){if(!S)return null;let C=parseNodeMajor(n);return!Number.isFinite(C)||C>=24?null:`gjsify install (native backend) requires Node ≥ 24, but this is Node ${n}. Its prebuilt native modules are ABI-locked to Node 24 and crash on older majors. Use Node 24 (nvm/asdf locally, actions/setup-node in CI), or run with --backend npm.`}function onRealNode(){return gjsSystemVersion()===void 0?isNode():!1}function assertNativeBackendNodeVersion(){let n=nativeBackendNodeError(process.versions.node,onRealNode());if(n)throw Error(n)}var aF=__esmMin(()=>{th()});function checkList(n,S){let C=typeof S==`string`?[S]:S;if(C.length===1&&C[0]===`any`)return!0;let N=0,F=!1;for(let S of C){let C=S.charAt(0)===`!`,I=C?S.slice(1):S;if(C){if(N++,n===I)return!1}else F||=n===I}return F||N===C.length}function checkPlatform(n,S){let C=n.os?checkList(S.os,n.os):!0,N=n.cpu?checkList(S.cpu,n.cpu):!0,F=n.libc?checkList(S.libc,n.libc):!0;return n.libc&&!S.libc&&(F=!1),{ok:C&&N&&F,current:{os:S.os,cpu:S.cpu,libc:S.libc},required:{os:n.os,cpu:n.cpu,libc:n.libc}}}function declaresPlatform(n){return!!(n.os||n.cpu||n.libc)}function badPlatformError(n,S){let C=Error(`Unsupported platform for ${n}: wanted ${JSON.stringify(S.required)} (current: ${JSON.stringify(S.current)})`);return C.code=`EBADPLATFORM`,C.pkgid=n,C.current=S.current,C.required=S.required,C}function isMuslSharedObject(n){return n.includes(`libc.musl-`)||n.includes(`ld-musl-`)}function libcFromLddFile(n){let S=n.readTextFile(oF);if(S!==null)return S.includes(`musl`)?`musl`:S.includes(`GNU C Library`)?`glibc`:null}function libcFromReportData(n){return n.glibcVersionRuntime?`glibc`:Array.isArray(n.sharedObjects)&&n.sharedObjects.some(n=>isMuslSharedObject(String(n)))?`musl`:null}function libcFromLoaderScan(n,S=sF){let C=!1;for(let N of S){let S=n.listDir(N);if(S)for(let n of S){if(n.startsWith(`ld-linux`))return`glibc`;n.startsWith(`ld-musl-`)&&(C=!0)}}return C?`musl`:null}function detectLibc(n,S){if(n!==`linux`)return;let C=libcFromLddFile(S);if(C!==void 0)return C??void 0;let N=S.diagnosticReport();return N===null?libcFromLoaderScan(S)??void 0:libcFromReportData(N)??void 0}function defaultLibcProbeHost(){return{readTextFile(n){try{return readFileSync(n,`utf-8`)}catch{return null}},listDir(n){try{return readdirSync(n)}catch{return null}},diagnosticReport(){let n=process.report;if(!n||typeof n.getReport!=`function`)return null;let S=n.excludeNetwork;n.excludeNetwork=!0;try{let S=n.getReport();return{glibcVersionRuntime:S.header?.glibcVersionRuntime,sharedObjects:S.sharedObjects}}finally{n.excludeNetwork=S}}}}function hostLibc(n,S=defaultLibcProbeHost()){return lF||=(cF=detectLibc(n,S),!0),cF}function readPlatformOverrides(n){let pick=S=>{let C=n[S];if(typeof C!=`string`)return;let N=C.trim();return N===``?void 0:N},S={},C=pick(`npm_config_os`),N=pick(`npm_config_cpu`),F=pick(`npm_config_libc`);return C!==void 0&&(S.os=C),N!==void 0&&(S.cpu=N),F!==void 0&&(S.libc=F),S}function readPlatformForce(n){let S=n.npm_config_force;if(typeof S!=`string`)return!1;let C=S.trim().toLowerCase();return C===`true`||C===`1`}function resolveHostPlatform(n={}){let S=readPlatformOverrides(n.env??process.env),C=S.os??n.platform??process.platform;return{os:C,cpu:S.cpu??n.arch??process.arch,libc:S.libc??(C===`linux`?hostLibc(C,n.probe??defaultLibcProbeHost()):void 0)}}function describePlatformTarget(n){return`${n.os}-${n.cpu}${n.libc?`-${n.libc}`:``}`}var oF,sF,cF,lF,uF=__esmMin(()=>{Vl(),oF=`/usr/bin/ldd`,sF=[`/lib`,`/lib64`,`/usr/lib`],lF=!1}),dF=__exportAll$4({applyPlatformFilter:()=>applyPlatformFilter,computeOptionalFlags:()=>computeOptionalFlags,installPackagesNative:()=>installPackagesNative,parseSpec:()=>parseSpec$1,pickVersion:()=>pickVersion,requiredDepEntries:()=>requiredDepEntries,warnMissingNativeBuilds:()=>warnMissingNativeBuilds,writeBinEntry:()=>writeBinEntry});async function installPackagesNative(n){if(assertNativeBackendNodeVersion(),n.specs.length===0)throw Error(`installPackagesNative: empty specs list`);mkdirSync(n.prefix,{recursive:!0});let S=await loadNpmrc$1(n),C=makeLogger(n.verbose??!1),N=await acquireInstallLock(n.prefix,{signal:n.signal});try{return await installPackagesNativeLocked(n,S,C)}finally{N.release()}}async function installPackagesNativeLocked(n,S,C){let N=n.progress,F=js(n.prefix,pF),I=readLockfile(F),H=resolveHostPlatform(),W=readPlatformForce(process.env);C(`install: platform target %s%s`,describePlatformTarget(H),W?` (--force: checks bypassed)`:``);let q,Y=!1,X=new Set;if(n.frozen){if(!I)throw Error(`install: --immutable requires ${pF} at ${n.prefix} — none found. Run \`gjsify install\` (without --immutable) to generate one and commit it.`);let S=describeLockfileDrift(I,n.specs);if(S)throw Error(`install: --immutable but ${F} is stale.\n${S}\nRe-run \`gjsify install\` (without --immutable) to refresh the lockfile.`);C(`install: --immutable, using lockfile (%d package(s))`,Object.keys(I.packages).length),q=lockfileToNodes(I)}else if(!n.refreshLockfile&&I&&I.lockfileVersion===mF&&lockfileMatchesRequest(I,n.specs))C(`install: using lockfile (%d package(s))`,Object.keys(I.packages).length),q=lockfileToNodes(I);else{let F=!n.refreshLockfile&&I?buildPreferredVersions(I):void 0;C(`install: resolving %d top-level spec(s) → %s%s`,n.specs.length,n.prefix,F?` (preserving ${F.size} locked name(s))`:``);let H=await resolveDeps(n.specs,S,C,n.overrides,n.skipDeps,n.signal,N,F,n.workspaceNames,n.specOrigins,n.optionalSpecs);q=H.nodes,X=H.skippedEdges,Y=!0}if(computeOptionalFlags(q,requiredTopLevelNames(n.specs,n.optionalSpecs),C),assertRequiredEdgesResolved(q,X),Y&&n.lockfile&&(writeLockfile(F,n.specs,q),C(`install: wrote %s (%d entries)`,pF,q.length)),n.workspaceNames&&n.workspaceNames.size>0){let S=q.length;q=q.filter(S=>!n.workspaceNames.has(S.name));let N=S-q.length;N>0&&C(`install: %d workspace-provided package(s) symlinked, not fetched`,N)}let Z=applyPlatformFilter(q,H,W,C);return C(`install: downloading %d tarball(s)`,Z.length),await downloadAndExtractAll(Z,n.prefix,S,C,n.signal,N),await linkBins(Z,n.prefix,C),warnMissingNativeBuilds(Z,n.prefix,C),C(`install: done`),topLevelResolutions(n.specs,q)}function errMsg(n){return n instanceof Error?n.message:String(n)}function applyPlatformFilter(n,S,C,N){let F=[],I=0;for(let H of n){let n=H.platform;if(!n||!declaresPlatform(n)){F.push(H);continue}let W=checkPlatform(n,S);if(W.ok){F.push(H);continue}let q=`${H.name}@${H.version}`;if(!H.optional){if(C){N(`platform-forced: %s (required, incompatible, installed anyway via --force)`,q),F.push(H);continue}throw badPlatformError(q,W)}H.inert=!0,I++,N(`platform-skip: %s (%s) current=%s required=%s`,q,H.installPath,JSON.stringify(W.current),JSON.stringify(W.required))}return I>0&&N(`install: %d optional package(s) inert — not installable on %s`,I,describePlatformTarget(S)),F}function warnMissingNativeBuilds(n,S,C){let N=process.platform,F=process.arch,I=[`preinstall`,`install`,`postinstall`];for(let H of n){let n=js(S,H.installPath),W;try{W=JSON.parse(readFileSync(js(n,`package.json`),`utf8`))?.scripts}catch{continue}if(!W||typeof W!=`object`)continue;let q=I.find(n=>typeof W[n]==`string`);if(q===void 0)continue;let Y=!1;try{let S=js(n,`prebuilds`);for(let n of readdirSync(S))if(n.startsWith(`${N}-`)&&readdirSync(js(S,n)).length>0){Y=!0;break}}catch{}if(!Y)try{Y=readdirSync(js(n,`build`,`Release`)).some(n=>n.endsWith(`.node`)||n.endsWith(`.so`))}catch{}Y||C("install: WARNING — %s declares a native `%s` build script but ships no %s-%s prebuild, and gjsify install does not run build scripts (node-free). It will not load until built: run `node-gyp rebuild` in %s, or use a version that ships a %s-%s prebuild.",H.name,q,N,F,H.installPath,N,F)}}function topLevelResolutions(n,S){let C=new Map;for(let n of S)n.installPath===`node_modules/${n.name}`&&C.set(n.name,n);let N=[];for(let S of n){let n=parseSpecName(S),F=C.get(n);F&&N.push({name:F.name,version:F.version})}return N}function parseSpecName(n){if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S===-1)return n;let C=n.indexOf(`@`,S+1);return C===-1?n:n.slice(0,C)}let S=n.indexOf(`@`);return S===-1?n:n.slice(0,S)}async function resolveDeps(n,S,C,N,F,I,H,W,q,Y,X){H?.beginPhase(`resolve`,n.length);let applyOverride=(n,S)=>{if(!N)return S;let F=N[n];return typeof F!=`string`||F.length===0||F===S?S:(C(`install: override %s %s → %s`,n,S,F),F)},Z=new Map,fetchPkg=n=>{let N=Z.get(n);if(N)return N;let F=fetchPackumentWithDiskCache(n,S,C,I,`full`);return Z.set(n,F),F},te=new Map,ne=new Map,re=new Set,ie=new Map,ae=n.map(parseSpec$1).map(n=>{let S=applyOverride(n.name,n.range),C=ie.get(n.name);C||(C=new Map,ie.set(n.name,C));let N=C.get(S);N||(N=new Set,C.set(S,N));for(let S of Y?.get(`${n.name}@${n.range}`)??[])N.add(S);return{from:null,name:n.name,range:S,required:!X?.has(n.name)}});for(;ae.length>0;){let n=ae.splice(0,ae.length),S=[],N=new Set;for(let C of n)Z.has(C.name)||N.has(C.name)||(N.add(C.name),S.push(C.name));await prefetchPackuments(S,fetchPkg,I);for(let S=0;S<n.length;S++){let N=n[S];if(q?.has(N.name))continue;let I=findVisible(N.from,N.name,te);if(I&&satisfiesRange(I.version,N.range))continue;let Y=null;try{let I=await fetchPkg(N.name),q=preferredVersionFor(W?.get(N.name),N.range);if(Y=pickVersion(I,N.range,q),!Y)throw Error(`No version of ${N.name} satisfies ${N.range}`);let X=I.versions[Y];if(!X)throw Error(`Packument for ${N.name} promised ${Y} but no entry exists`);let Z=decidePlacement(N.from,N.name,Y,ne),re={name:N.name,version:Y,tarballUrl:X.dist.tarball,integrity:X.dist.integrity,installPath:Z,dependencies:X.dependencies??{},optionalDependencies:X.optionalDependencies??{},bin:X.bin,platform:platformDeclarationOf(X),optional:!N.required};if(te.set(Z,re),Z===`node_modules/${N.name}`&&ne.set(N.name,re),C(`resolve: %s@%s ← %s (at %s)`,N.name,Y,N.range,Z),H?.update({phase:`resolve`,current:te.size,total:te.size+(n.length-S-1)+ae.length,name:`${N.name}@${Y}`}),!F){for(let[n,S]of requiredDepEntries(re))ae.push({from:Z,name:n,range:applyOverride(n,S),required:!re.optional});for(let[n,S]of Object.entries(re.optionalDependencies))ae.push({from:Z,name:n,range:applyOverride(n,S),required:!1})}}catch(n){if(!N.required){re.add(edgeKey(N.from,N.name)),C(`resolve: optional dep %s@%s skipped (%s)`,N.name,N.range,errMsg(n));continue}throw n}}}return H?.endPhase(`resolve`),emitTopLevelConflictWarnings(ie,ne),{nodes:Array.from(te.values()),skippedEdges:re}}function platformDeclarationOf(n){let S={os:n.os,cpu:n.cpu,libc:n.libc};return declaresPlatform(S)?S:void 0}function edgeKey(n,S){return`${n??``}\n${S}`}function parseEdgeKey(n){let S=n.indexOf(`
|
|
886
|
+
`),C=n.slice(0,S);return{from:C===``?null:C,name:n.slice(S+1)}}function requiredTopLevelNames(n,S){let C=new Set;for(let N of n){let n=parseSpecName(N);S?.has(n)||C.add(n)}return C}function requiredDepEntries(n){let S=[];for(let[C,N]of Object.entries(n.dependencies))C in n.optionalDependencies||S.push([C,N]);return S}function computeOptionalFlags(n,S,C){let N=new Map;for(let S of n)N.set(S.installPath,S);let F=new Set,I=[],enter=n=>{F.has(n.installPath)||(F.add(n.installPath),I.push(n.installPath))};for(let n of S){let S=N.get(`node_modules/${n}`);S&&enter(S)}for(;I.length>0;){let n=I.pop();if(n===void 0)break;let S=N.get(n);if(S)for(let[C]of requiredDepEntries(S)){let S=findVisible(n,C,N);S&&enter(S)}}let H=0;for(let S of n){let n=!F.has(S.installPath);(S.optional??!1)!==n&&H++,S.optional=n}C(`install: optionality fixpoint — %d of %d node(s) reachable only via optional edges%s`,n.length-F.size,n.length,H>0?`; corrected ${H} incoming flag(s)`:``)}function assertRequiredEdgesResolved(n,S){if(S.size===0)return;let C=new Map;for(let S of n)C.set(S.installPath,S);for(let n of S){let{from:S,name:N}=parseEdgeKey(n);if(S===null)continue;let F=C.get(S);if(F&&!F.optional&&!(N in F.optionalDependencies))throw Error(`install: required dependency ${N} of ${F.name}@${F.version} (${F.installPath}) could not be resolved.\nThe failure was tolerated during the walk because ${F.name} looked optional at that point, but the final dependency graph makes it required — so ${N} is required too and the tree would be incomplete.\nRe-run with --verbose and look for the "resolve: optional dep ${N}@… skipped (…)" line for the underlying cause.`)}}function emitTopLevelConflictWarnings(n,S){for(let[C,N]of n){if(N.size<2)continue;let n=S.get(C);if(!n)continue;let describe=(n,S)=>S.size>0?`${n} (requested by ${[...S].join(`, `)})`:n,F=[],I=[];for(let[S,C]of N){let N;try{N=satisfies(n.version,new RP(S))}catch{continue}(N?F:I).push(describe(S,C))}I.length!==0&&ve.warn(`[gjsify] warning: version conflict for ${C}: installed ${n.version} at ${n.installPath} — does NOT satisfy ${I.join(`, `)}`+(F.length>0?`; satisfies ${F.join(`, `)}`:``)+`. One hoisted copy serves all requesters until the per-workspace dedup pass lands (Phase D.8).`)}}async function fetchPackumentWithDiskCache(n,S,C,N,F=`corgi`){let I=registryFor(n,S),H=F===`full`,W=getCachedPackument(I,n,F),onRetry=({attempt:S,error:N,delayMs:I})=>{C(`packument %s (%s): retry %d after %dms (%s)`,n,F,S,I,errMsg(N))},q=await fetchPackumentConditional(n,{npmrc:S,signal:N,ifNoneMatch:W?.etag,fullMetadata:H,onRetry});return q.status===`not-modified`&&W?(C(`packument-cache-hit: %s (%s, 304, etag %s)`,n,F,W.etag),W.packument):q.status===`fresh`&&q.packument?(q.etag&&putCachedPackument(I,n,q.etag,q.packument,F),q.packument):fetchPackument(n,{npmrc:S,signal:N,fullMetadata:H,onRetry})}async function prefetchPackuments(n,S,C){if(n.length===0)return;let N=0,F=Math.max(1,Math.min(fF,n.length)),worker=async()=>{for(;N<n.length;){if(C?.aborted)return;let F=n[N++];try{await S(F)}catch{}}};await Promise.all(Array.from({length:F},()=>worker()))}function findVisible(n,S,C){let N=[];if(n!==null){N.push(`${n}/node_modules/${S}`);let C=n;for(;;){let n=C.lastIndexOf(`/node_modules/`);if(n<0||(C=C.slice(0,n),N.push(`${C}/node_modules/${S}`),C===``))break}}N.push(`node_modules/${S}`);for(let n of N){let S=C.get(n);if(S)return S}return null}function decidePlacement(n,S,C,N){let F=N.get(S);return!F||F.version===C||n===null?`node_modules/${S}`:`${n}/node_modules/${S}`}function satisfiesRange(n,S){try{return satisfies(n,new RP(S))}catch{return!1}}function readLockfile(n){if(!existsSync(n))return null;try{let S=JSON.parse(readFileSync(n,`utf-8`));return!hF.has(S.lockfileVersion)||!S.packages||typeof S.packages!=`object`?null:S}catch{return null}}function writeLockfile(n,S,C){let N={},F=[...C].sort((n,S)=>n.installPath<S.installPath?-1:+(n.installPath>S.installPath));for(let n of F)N[n.installPath]={version:n.version,resolved:n.tarballUrl,integrity:n.integrity,dependencies:Object.keys(n.dependencies).length>0?n.dependencies:void 0,optionalDependencies:Object.keys(n.optionalDependencies).length>0?n.optionalDependencies:void 0,bin:n.bin,os:n.platform?.os,cpu:n.platform?.cpu,libc:n.platform?.libc,optional:n.optional?!0:void 0};let I={lockfileVersion:mF,requested:[...S],packages:N};atomicWriteStrict(n,JSON.stringify(I,null,2)+`
|
|
887
887
|
`)}function buildPreferredVersions(n){let S=new Map;for(let[C,N]of Object.entries(n.packages)){let n=nameFromInstallPath(C),F=S.get(n);F||(F=new Set,S.set(n,F)),F.add(N.version)}return S}function preferredVersionFor(n,S){if(!n||n.size===0)return;let C;for(let N of n)satisfiesRange(N,S)&&(C===void 0||new SemVer(N).compare(new SemVer(C))>0)&&(C=N);return C}function lockfileToNodes(n){return Object.entries(n.packages).map(([n,S])=>{let C={os:S.os,cpu:S.cpu,libc:S.libc};return{name:nameFromInstallPath(n),version:S.version,tarballUrl:S.resolved,integrity:S.integrity,installPath:n,dependencies:S.dependencies??{},optionalDependencies:S.optionalDependencies??{},bin:S.bin,platform:declaresPlatform(C)?C:void 0,optional:S.optional===!0}})}function nameFromInstallPath(n){let S=n.lastIndexOf(`/node_modules/`);return S<0?n.replace(/^node_modules\//,``):n.slice(S+14)}function lockfileMatchesRequest(n,S){if(n.requested.length!==S.length)return!1;let C=[...n.requested].sort(),N=[...S].sort();return C.every((n,S)=>n===N[S])}function describeLockfileDrift(n,S){let C=new Set(n.requested),N=new Set(S),F=[],I=[];for(let n of N)C.has(n)||F.push(n);for(let n of C)N.has(n)||I.push(n);if(F.length===0&&I.length===0)return null;let H=[];return F.length>0&&H.push(` + ${F.sort().join(`
|
|
888
888
|
+ `)}`),I.length>0&&H.push(` - ${I.sort().join(`
|
|
889
889
|
- `)}`),H.join(`
|
|
890
|
-
`)}function parseSpec$1(n){if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S<0)throw Error(`Invalid spec (scoped name without slash): ${n}`);let C=n.indexOf(`@`,S);return C<0?{name:n,range:`latest`}:{name:n.slice(0,C),range:n.slice(C+1)||`latest`}}let S=n.indexOf(`@`);return S<0?{name:n,range:`latest`}:{name:n.slice(0,S),range:n.slice(S+1)||`latest`}}function pickVersion(n,S,C){if(C&&n.versions[C]&&satisfiesRange(C,S))return C;if(n[`dist-tags`][S])return n[`dist-tags`][S];let N;try{N=new LP(S)}catch{throw Error(`Invalid version range for ${n.name}: ${S}`)}return maxSatisfying(Object.keys(n.versions).filter(n=>{try{return new SemVer(n),!0}catch{return!1}}),N)}async function downloadAndExtractAll(n,S,C,N,F,I){let H=[...n].sort((n,S)=>depth$1(n.installPath)-depth$1(S.installPath)||(n.installPath<S.installPath?-1:1)),W=[],q=Math.max(1,Math.min(dF,H.length));I?.beginPhase(`download`,H.length);let Y=0,X=0,tickProgress=(n,S)=>{Y++,S&&X++,I?.update({phase:`download`,current:Y,total:H.length,name:`${n.name}@${n.version}`})},Z=0,te=H.findIndex(n=>depth$1(n.installPath)>1),ne=te<0?H.length:te;for(;Z<ne;){if(F?.aborted)throw abortError(F);let n=H[Z++];if(!n)break;tickProgress(n,await extractOne(n,S,C,N,F))}for(let n=0;n<q;n++)W.push((async()=>{for(;;){if(F?.aborted)throw abortError(F);let n=Z++;if(n>=H.length)return;let I=H[n];if(!I)return;let W=await extractOne(I,S,C,N,F);tickProgress(I,W)}})());await Promise.all(W),I?.endPhase(`download`),X>0&&N(`install: %d/%d package(s) already up to date — extracted %d`,X,H.length,H.length-X)}function isAlreadyExtracted(n,S){let C=js(n,`package.json`),N;try{N=readFileSync(C,`utf-8`)}catch{return!1}try{let n=JSON.parse(N);return!(n.version!==S.version||typeof n.name==`string`&&n.name!==S.name)}catch{return!1}}async function extractOne(n,S,C,N,F){let I=js(S,n.installPath);if(assertNodeModulesDest(I,n),process.env.GJSIFY_INSTALL_FORCE_EXTRACT!==`1`&&isAlreadyExtracted(I,n))return N(`up-to-date: %s@%s (already extracted at %s)`,n.name,n.version,n.installPath),!0;let H=getCachedTarball(n.integrity);return H?N(`cache-hit: %s@%s ← %s`,n.name,n.version,n.integrity):(H=getForeignCachedTarball(n.integrity))?(N(`npm-cache-hit: %s@%s ← %s`,n.name,n.version,n.integrity),putCachedTarball(n.integrity,H)):(N(`fetch: %s@%s ← %s (→ %s)`,n.name,n.version,n.tarballUrl,n.installPath),H=await fetchTarball(n.tarballUrl,{npmrc:C,signal:F,integrity:n.integrity,onRetry:({attempt:S,error:C,delayMs:F})=>{N(`tarball %s@%s: retry %d after %dms (%s)`,n.name,n.version,S,F,errMsg(C))}}),putCachedTarball(n.integrity,H)),rmWithRetry(I),mkdirSync(I,{recursive:!0}),await extractWithStallGuard(H,I,n,F),!1}async function extractWithStallGuard(n,S,C,N){if(hF===0&&!N){await extractTarball(n,S);return}let F,onAbort;try{await new Promise((I,H)=>{if(process.env.GJSIFY_TEST_HANG_EXTRACT!==`1`&&extractTarball(n,S).then(()=>I(),H),hF>0&&(F=setTimeout(()=>{H(Error(`gjsify install: extract of ${C.name}@${C.version} stalled for ${Math.round(hF/1e3)}s (${C.installPath}) — the tarball decompress/write never completed. This is usually a dropped Gio stream event under GJS; re-run the install. Override the cap with GJSIFY_EXTRACT_STALL_MS=<ms> (0 disables it).`))},hF),F.unref?.()),N){if(N.aborted){H(abortError(N));return}onAbort=()=>H(abortError(N)),N.addEventListener(`abort`,onAbort,{once:!0})}})}finally{F&&clearTimeout(F),N&&onAbort&&N.removeEventListener(`abort`,onAbort)}}function abortError(n){let S=n&&`reason`in n?n.reason:void 0;if(S instanceof Error)return S;let C=Error(`Aborted`);return C.name=`AbortError`,C}function assertNodeModulesDest(n,S){if(!n.split(zs).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${S.name}@${S.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 C;try{C=realpathSync(n)}catch{return}if(!C.split(zs).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${S.name}@${S.version} — ${n} resolves to ${C}, 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$1(n){return n.split(`/node_modules/`).length}function readShebang$1(n){let S;try{S=readFileSync(n,`utf-8`)}catch{return null}return parseShebang(S.trimStart().split(/\r*\n/,1)[0]??``)}function writeBinEntry(n){let{binDir:S,binName:C,targetAbs:N,gjs:F,nodeFallbackAbs:I}=n,H=n.platform??process.platform,W=js(S,C);if(F){let n=isGjsBundlePath(N);for(let n of[W,`${W}.cmd`,`${W}.ps1`])rmWithRetry(n);writeFileSync(W,buildShLauncher(N,{envPreamble:F.envPreamble,isGjsBundle:n,nodeFallbackAbs:I}));try{chmodSync(W,493)}catch{}if(H===`win32`&&n){let n=F.prebuildDirs.join(`;`),S=buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:N,prependEnv:F.prebuildDirs.length>0?{GI_TYPELIB_PATH:n,PATH:n}:{},fallback:I===void 0?void 0:{interpreter:`node`,target:I}});writeFileSync(`${W}.cmd`,S.cmd),writeFileSync(`${W}.ps1`,S.ps1)}return}if(H===`win32`){let{sh:n,cmd:C,ps1:F}=buildCmdShim(Ms(S,N).split(`\\`).join(`/`),readShebang$1(N));for(let[S,N]of[[W,n],[`${W}.cmd`,C],[`${W}.ps1`,F]]){rmWithRetry(S),writeFileSync(S,N);try{chmodSync(S,493)}catch{}}return}rmWithRetry(W);let q=Ms(S,N);try{symlinkSync(q,W)}catch{copyFileSync(N,W),chmodSync(W,493)}}async function linkBins(n,S,C){let N=js(S,`node_modules`,`.bin`),F=0,I,gjsEnvForPrefix=()=>{if(I===void 0){let n=detectNativePackages(S).map(n=>n.prebuildsDir);I={envPreamble:buildNativeEnvPreamble(S,n),prebuildDirs:n}}return I};for(let C of n){if(depth$1(C.installPath)!==1)continue;let n=js(S,C.installPath),I=readInstalledManifest(n)??(C.bin===void 0?null:{bin:C.bin});if(I===null)continue;let H=pickBinMap(C.name,I);if(!(H===null||H.map.size===0)){mkdirSync(N,{recursive:!0});for(let[S,C]of H.map){let I=js(n,C);if(!existsSync(I))continue;try{chmodSync(I,493)}catch{}let W=H.nodeFallback?.get(S),q=W===void 0?void 0:js(n,W);writeBinEntry({binDir:N,binName:S,targetAbs:I,gjs:H.isGjsBin?gjsEnvForPrefix():void 0,nodeFallbackAbs:q!==void 0&&existsSync(q)?q:void 0}),F++}}}F>0&&C(`bin: linked %d entry(ies) under .bin/`,F)}function readInstalledManifest(n){try{let S=readFileSync(js(n,`package.json`),`utf-8`);return JSON.parse(S)}catch{return null}}function rmWithRetry(n){rmSync(n,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}async function loadNpmrc$1(n){let S=homedir(),C={registry:n.registry??qf,scopes:{},authTokens:{},basicAuth:{}};for(let N of[js(S,`.npmrc`),js(n.prefix,`.npmrc`)])if(existsSync(N))try{let n=parseNpmrc(readFileSync(N,`utf-8`));C={...C,...n,scopes:{...C.scopes,...n.scopes}}}catch(n){ve.warn(`gjsify install: ignoring malformed ${N}: ${n.message}`)}let N=process.env.npm_config_registry;return N&&(C.registry=N),n.registry&&(C.registry=n.registry),C}function makeLogger(n){return n?(n,...S)=>{let C=n.replace(/%s|%d/g,()=>String(S.shift()));process.stderr.write(`gjsify install: ${C}\n`)}:()=>{}}var dF,fF,pF,mF,hF,gF=__esmMin(()=>{ye(),Vl(),Hs(),Dm(),RP(),ep(),UP(),WP(),$P(),tF(),rF(),iF(),AP(),gN(),lF(),dF=Number(process.env.GJSIFY_INSTALL_CONCURRENCY??`16`)||16,fF=`gjsify-lock.json`,pF=4,mF=new Set([2,3,pF]),__name$1(parseSpec$1,`parseSpec`),hF=(()=>{let n=process.env.GJSIFY_EXTRACT_STALL_MS;if(n===void 0)return 12e4;let S=Number(n);return Number.isFinite(S)&&S>=0?S:12e4})(),__name$1(depth$1,`depth`),__name$1(readShebang$1,`readShebang`),__name$1(loadNpmrc$1,`loadNpmrc`)}),_F=__exportAll$4({installPackages:()=>installPackages,makeProgressReporter:()=>makeProgressReporter});async function installPackages(n){if(vF===`npm`)return await installViaNpm(n),{installed:[]};let{installPackagesNative:S}=await Promise.resolve().then(()=>(gF(),uF));return{installed:await S(n)}}async function installViaNpm({prefix:n,specs:S,verbose:C,registry:N}){if(S.length===0)throw Error(`installPackages: empty specs list`);writeFileSync(js(n,`package.json`),JSON.stringify({name:`gjsify-dlx-cache`,version:`0.0.0`,private:!0},null,2)),N&&writeFileSync(js(n,`.npmrc`),`registry=${N}\n`);let{code:F}=await spawnToCompletion(`npm`,[`install`,`--no-package-lock`,`--no-audit`,`--no-fund`,`--prefix`,n,...C?[`--loglevel`,`verbose`]:[`--loglevel`,`warn`],...S],{completion:`return`,notFound:n=>Error(`npm not found on PATH — install Node.js, or unset GJSIFY_INSTALL_BACKEND to use the default native backend (${n.message})`)});if(F!==0)throw Error(`npm install exited with code ${F}`)}var vF,yF=__esmMin(()=>{Vl(),Hs(),_P(),PP(),vF=process.env.GJSIFY_INSTALL_BACKEND??`native`});function defaultGlobalLayout(){let n=process.env.GJSIFY_GLOBAL_PREFIX,S=process.env.GJSIFY_GLOBAL_BIN_DIR,C=homedir(),N=process.env.XDG_DATA_HOME??js(C,`.local`,`share`);return{prefix:n??js(N,`gjsify`,`global`),binDir:S??js(C,`.local`,`bin`)}}function hasBundlerEngineInstalled(n){let S=new Set(detectNativePackages(n).map(n=>n.name));if(S.has(`@gjsify/rolldown-native`))return!0;let C=detectHostLibc(process.platform);return hostPlatformTokens(process.platform,process.arch,C).some(n=>S.has(platformPackageName(xF,n)))}async function installGjsEnginePackages(n,S,C={}){let N=C.verbose??!1,F=C.installFn??(async S=>{let{installPackages:C}=await Promise.resolve().then(()=>(yF(),_F));await C({prefix:n,specs:[S],verbose:N})});for(let n of bF){let C=S?`${n}@${S}`:n;try{await F(C)}catch(C){let F=C instanceof Error?C.message:String(C);n===`@gjsify/rolldown-native`?ve.warn(`\nWarning: could not install the GJS bundler engine ${n}@${S} — ${F}\n \`gjsify build\` (and storybook / flatpak) will fail under GJS until it is present.\n This usually means no prebuild is published for this platform (${process.platform}/${process.arch}).`):N&&ve.warn(`gjsify install: optional GJS engine ${n}@${S} not installed — ${F}`)}}}function linkGlobalBins(n,S){mkdirSync(S.binDir,{recursive:!0});let C=[],N=detectNativePackages(S.prefix).map(n=>n.prebuildsDir),F=buildNativeEnvPreamble(S.prefix,N);for(let I of n){let n=js(S.prefix,`node_modules`,I),H=js(n,`package.json`);if(!existsSync(H))continue;let W=pickBinMap(I,readJson(H));if(!(W===null||W.map.size===0))for(let[I,H]of W.map){let q=js(n,H);if(!existsSync(q))continue;try{chmodSync(q,493)}catch{}let Y=js(S.binDir,I);for(let n of[Y,`${Y}.cmd`,`${Y}.ps1`])rmSync(n,{force:!0,maxRetries:10,retryDelay:100});let X=isGjsBundlePath(q),Z=W.nodeFallback?.get(I),te=Z===void 0?void 0:js(n,Z),ne=te!==void 0&&existsSync(te)?te:void 0;if(writeFileSync(Y,buildShLauncher(q,{envPreamble:F,isGjsBundle:X,nodeFallbackAbs:ne})),chmodSync(Y,493),process.platform===`win32`){let n=N.join(`;`),S=X&&N.length>0?{GI_TYPELIB_PATH:n,PATH:n}:{},C=X?null:readShebangOf(q),F=buildLauncherShims(X?{interpreter:`gjs`,interpreterArgs:[`-m`],target:q,prependEnv:S,fallback:ne===void 0?void 0:{interpreter:`node`,target:ne}}:{interpreter:C?.prog||`node`,interpreterArgs:C?.args.trim()?C.args.trim().split(/\s+/):[],target:q});writeFileSync(`${Y}.cmd`,F.cmd),writeFileSync(`${Y}.ps1`,F.ps1)}C.push({name:I,target:q,link:Y})}}return C}function readShebangOf(n){try{return parseShebang(readFileSync(n,`utf-8`).trimStart().split(/\r*\n/,1)[0]??``)}catch{return null}}function readJson(n){return JSON.parse(readFileSync(n,`utf-8`))}function globalLayoutIsDefault(n=process.env){return!n.GJSIFY_GLOBAL_PREFIX&&!n.GJSIFY_GLOBAL_BIN_DIR}function pathFor$1(n){return n===`win32`?Cs:xs}function searchPathEntries(n,S){let C=pathFor$1(S),N=S===`win32`?`;`:`:`;return n.split(N).filter(Boolean).map(n=>C.resolve(n))}function binDirOnPath(n){let S=pathFor$1(process.platform).resolve(n);return searchPathEntries(process.env.PATH??``,process.platform).includes(S)}function resolveBinOnPath(n,S={}){let C=S.platform??process.platform,N=S.pathValue??process.env.PATH??``,F=S.exists??existsSync,I=C===`win32`?[...(S.pathExt??process.env.PATHEXT??SF).split(`;`).filter(Boolean).map(n=>n.startsWith(`.`)?n:`.${n}`),``]:[``],H=pathFor$1(C);for(let S of searchPathEntries(N,C))for(let C of I){let N=H.join(S,`${n}${C}`);if(F(N))return N}return null}function specToPackageName(n){if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S<0)return n;let C=n.indexOf(`@`,S);return C<0?n:n.slice(0,C)}let S=n.indexOf(`@`);return S<0?n:n.slice(0,S)}var bF,xF,SF,CF=__esmMin(()=>{ye(),Vl(),Dm(),Hs(),gN(),AP(),bF=[`@gjsify/rolldown-native`,`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`],xF=`@gjsify/rolldown-native`,__name$1(pathFor$1,`pathFor`),SF=`.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC`});function usingSelfShim(){return TF}function needsSelfShim(n){if(n.gjs)return!0;let S=Ms(n.workspaceRoot,n.selfEntry);return S===``||S.startsWith(`..`)||As(S)}function ensureGjsifyShimOnPath(){if(wF)return;wF=!0;let n=process.env.GJSIFY_SHIM_DIR;if(n&&existsSync(js(n,`gjsify`))){TF=!0,(process.env.PATH??``).split(Bs).includes(n)||(process.env.PATH=n+Bs+(process.env.PATH??``));return}let S=isGjs(),C=fileURLToPath(S?import.meta.url:new URL(`../index.js`,import.meta.url));if(!needsSelfShim({gjs:S,selfEntry:C,workspaceRoot:findWorkspaceRoot(process.cwd())??process.cwd()}))return;let N=mkdtempSync(js(tmpdir(),`gjsify-shim-`)),F=js(N,`gjsify`),I=S?process.env.GJS_CONSOLE||`gjs`:`node`,H=S?[`-m`]:[];if(writeFileSync(F,`#!/bin/sh\nexec "${I}" ${H.length>0?`${H.join(` `)} `:``}"${C}" "$@"\n`,{mode:493}),chmodSync(F,493),!S&&process.platform===`win32`){let{cmd:n,ps1:S}=buildLauncherShims({interpreter:I,interpreterArgs:H,target:C});writeFileSync(`${F}.cmd`,n),writeFileSync(`${F}.ps1`,S)}TF=!0,process.env.GJSIFY_SHIM_DIR=N,process.env.PATH=N+Bs+(process.env.PATH??``),writeNodeShim(N,S,C)}function nodeShimDir(){let n=process.env.GJSIFY_SHIM_DIR;if(!n)return null;let S=js(n,EF);return existsSync(js(S,`node`))?S:null}function writeNodeShim(n,S,C){if(!S)return;let N=js(n,EF);if(existsSync(js(N,`node`))||resolveBinOnPath(`node`))return;let F=process.env.GJS_CONSOLE||`gjs`;mkdirSync(N,{recursive:!0});let I=js(N,`node`);writeFileSync(I,`#!/bin/sh
|
|
890
|
+
`)}function parseSpec$1(n){if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S<0)throw Error(`Invalid spec (scoped name without slash): ${n}`);let C=n.indexOf(`@`,S);return C<0?{name:n,range:`latest`}:{name:n.slice(0,C),range:n.slice(C+1)||`latest`}}let S=n.indexOf(`@`);return S<0?{name:n,range:`latest`}:{name:n.slice(0,S),range:n.slice(S+1)||`latest`}}function pickVersion(n,S,C){if(C&&n.versions[C]&&satisfiesRange(C,S))return C;if(n[`dist-tags`][S])return n[`dist-tags`][S];let N;try{N=new RP(S)}catch{throw Error(`Invalid version range for ${n.name}: ${S}`)}return maxSatisfying(Object.keys(n.versions).filter(n=>{try{return new SemVer(n),!0}catch{return!1}}),N)}async function downloadAndExtractAll(n,S,C,N,F,I){let H=[...n].sort((n,S)=>depth$1(n.installPath)-depth$1(S.installPath)||(n.installPath<S.installPath?-1:1)),W=[],q=Math.max(1,Math.min(fF,H.length));I?.beginPhase(`download`,H.length);let Y=0,X=0,tickProgress=(n,S)=>{Y++,S&&X++,I?.update({phase:`download`,current:Y,total:H.length,name:`${n.name}@${n.version}`})},Z=0,te=H.findIndex(n=>depth$1(n.installPath)>1),ne=te<0?H.length:te;for(;Z<ne;){if(F?.aborted)throw abortError(F);let n=H[Z++];if(!n)break;tickProgress(n,await extractOne(n,S,C,N,F))}for(let n=0;n<q;n++)W.push((async()=>{for(;;){if(F?.aborted)throw abortError(F);let n=Z++;if(n>=H.length)return;let I=H[n];if(!I)return;let W=await extractOne(I,S,C,N,F);tickProgress(I,W)}})());await Promise.all(W),I?.endPhase(`download`),X>0&&N(`install: %d/%d package(s) already up to date — extracted %d`,X,H.length,H.length-X)}function isAlreadyExtracted(n,S){let C=js(n,`package.json`),N;try{N=readFileSync(C,`utf-8`)}catch{return!1}try{let n=JSON.parse(N);return!(n.version!==S.version||typeof n.name==`string`&&n.name!==S.name)}catch{return!1}}async function extractOne(n,S,C,N,F){let I=js(S,n.installPath);if(assertNodeModulesDest(I,n),process.env.GJSIFY_INSTALL_FORCE_EXTRACT!==`1`&&isAlreadyExtracted(I,n))return N(`up-to-date: %s@%s (already extracted at %s)`,n.name,n.version,n.installPath),!0;let H=getCachedTarball(n.integrity);return H?N(`cache-hit: %s@%s ← %s`,n.name,n.version,n.integrity):(H=getForeignCachedTarball(n.integrity))?(N(`npm-cache-hit: %s@%s ← %s`,n.name,n.version,n.integrity),putCachedTarball(n.integrity,H)):(N(`fetch: %s@%s ← %s (→ %s)`,n.name,n.version,n.tarballUrl,n.installPath),H=await fetchTarball(n.tarballUrl,{npmrc:C,signal:F,integrity:n.integrity,onRetry:({attempt:S,error:C,delayMs:F})=>{N(`tarball %s@%s: retry %d after %dms (%s)`,n.name,n.version,S,F,errMsg(C))}}),putCachedTarball(n.integrity,H)),rmWithRetry(I),mkdirSync(I,{recursive:!0}),await extractWithStallGuard(H,I,n,F),!1}async function extractWithStallGuard(n,S,C,N){if(gF===0&&!N){await extractTarball(n,S);return}let F,onAbort;try{await new Promise((I,H)=>{if(process.env.GJSIFY_TEST_HANG_EXTRACT!==`1`&&extractTarball(n,S).then(()=>I(),H),gF>0&&(F=setTimeout(()=>{H(Error(`gjsify install: extract of ${C.name}@${C.version} stalled for ${Math.round(gF/1e3)}s (${C.installPath}) — the tarball decompress/write never completed. This is usually a dropped Gio stream event under GJS; re-run the install. Override the cap with GJSIFY_EXTRACT_STALL_MS=<ms> (0 disables it).`))},gF),F.unref?.()),N){if(N.aborted){H(abortError(N));return}onAbort=()=>H(abortError(N)),N.addEventListener(`abort`,onAbort,{once:!0})}})}finally{F&&clearTimeout(F),N&&onAbort&&N.removeEventListener(`abort`,onAbort)}}function abortError(n){let S=n&&`reason`in n?n.reason:void 0;if(S instanceof Error)return S;let C=Error(`Aborted`);return C.name=`AbortError`,C}function assertNodeModulesDest(n,S){if(!n.split(zs).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${S.name}@${S.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 C;try{C=realpathSync(n)}catch{return}if(!C.split(zs).includes(`node_modules`))throw Error(`gjsify install: refusing to extract ${S.name}@${S.version} — ${n} resolves to ${C}, 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$1(n){return n.split(`/node_modules/`).length}function readShebang$1(n){let S;try{S=readFileSync(n,`utf-8`)}catch{return null}return parseShebang(S.trimStart().split(/\r*\n/,1)[0]??``)}function writeBinEntry(n){let{binDir:S,binName:C,targetAbs:N,gjs:F,nodeFallbackAbs:I}=n,H=n.platform??process.platform,W=js(S,C);if(F){let n=isGjsBundlePath(N);for(let n of[W,`${W}.cmd`,`${W}.ps1`])rmWithRetry(n);writeFileSync(W,buildShLauncher(N,{envPreamble:F.envPreamble,isGjsBundle:n,nodeFallbackAbs:I}));try{chmodSync(W,493)}catch{}if(H===`win32`&&n){let n=F.prebuildDirs.join(`;`),S=buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:N,prependEnv:F.prebuildDirs.length>0?{GI_TYPELIB_PATH:n,PATH:n}:{},fallback:I===void 0?void 0:{interpreter:`node`,target:I}});writeFileSync(`${W}.cmd`,S.cmd),writeFileSync(`${W}.ps1`,S.ps1)}return}if(H===`win32`){let{sh:n,cmd:C,ps1:F}=buildCmdShim(Ms(S,N).split(`\\`).join(`/`),readShebang$1(N));for(let[S,N]of[[W,n],[`${W}.cmd`,C],[`${W}.ps1`,F]]){rmWithRetry(S),writeFileSync(S,N);try{chmodSync(S,493)}catch{}}return}rmWithRetry(W);let q=Ms(S,N);try{symlinkSync(q,W)}catch{copyFileSync(N,W),chmodSync(W,493)}}async function linkBins(n,S,C){let N=js(S,`node_modules`,`.bin`),F=0,I,gjsEnvForPrefix=()=>{if(I===void 0){let n=detectNativePackages(S).map(n=>n.prebuildsDir);I={envPreamble:buildNativeEnvPreamble(S,n),prebuildDirs:n}}return I};for(let C of n){if(depth$1(C.installPath)!==1)continue;let n=js(S,C.installPath),I=readInstalledManifest(n)??(C.bin===void 0?null:{bin:C.bin});if(I===null)continue;let H=pickBinMap(C.name,I);if(!(H===null||H.map.size===0)){mkdirSync(N,{recursive:!0});for(let[S,C]of H.map){let I=js(n,C);if(!existsSync(I))continue;try{chmodSync(I,493)}catch{}let W=H.nodeFallback?.get(S),q=W===void 0?void 0:js(n,W);writeBinEntry({binDir:N,binName:S,targetAbs:I,gjs:H.isGjsBin?gjsEnvForPrefix():void 0,nodeFallbackAbs:q!==void 0&&existsSync(q)?q:void 0}),F++}}}F>0&&C(`bin: linked %d entry(ies) under .bin/`,F)}function readInstalledManifest(n){try{let S=readFileSync(js(n,`package.json`),`utf-8`);return JSON.parse(S)}catch{return null}}function rmWithRetry(n){rmSync(n,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}async function loadNpmrc$1(n){let S=homedir(),C={registry:n.registry??qf,scopes:{},authTokens:{},basicAuth:{}};for(let N of[js(S,`.npmrc`),js(n.prefix,`.npmrc`)])if(existsSync(N))try{let n=parseNpmrc(readFileSync(N,`utf-8`));C={...C,...n,scopes:{...C.scopes,...n.scopes}}}catch(n){ve.warn(`gjsify install: ignoring malformed ${N}: ${n.message}`)}let N=process.env.npm_config_registry;return N&&(C.registry=N),n.registry&&(C.registry=n.registry),C}function makeLogger(n){return n?(n,...S)=>{let C=n.replace(/%s|%d/g,()=>String(S.shift()));process.stderr.write(`gjsify install: ${C}\n`)}:()=>{}}var fF,pF,mF,hF,gF,_F=__esmMin(()=>{ye(),Vl(),Hs(),Dm(),zP(),ep(),WP(),GP(),eF(),nF(),iF(),aF(),jP(),gN(),uF(),fF=Number(process.env.GJSIFY_INSTALL_CONCURRENCY??`16`)||16,pF=`gjsify-lock.json`,mF=4,hF=new Set([2,3,mF]),__name$1(parseSpec$1,`parseSpec`),gF=(()=>{let n=process.env.GJSIFY_EXTRACT_STALL_MS;if(n===void 0)return 12e4;let S=Number(n);return Number.isFinite(S)&&S>=0?S:12e4})(),__name$1(depth$1,`depth`),__name$1(readShebang$1,`readShebang`),__name$1(loadNpmrc$1,`loadNpmrc`)}),vF=__exportAll$4({installPackages:()=>installPackages,makeProgressReporter:()=>makeProgressReporter});async function installPackages(n){if(yF===`npm`)return await installViaNpm(n),{installed:[]};let{installPackagesNative:S}=await Promise.resolve().then(()=>(_F(),dF));return{installed:await S(n)}}async function installViaNpm({prefix:n,specs:S,verbose:C,registry:N}){if(S.length===0)throw Error(`installPackages: empty specs list`);writeFileSync(js(n,`package.json`),JSON.stringify({name:`gjsify-dlx-cache`,version:`0.0.0`,private:!0},null,2)),N&&writeFileSync(js(n,`.npmrc`),`registry=${N}\n`);let{code:F}=await spawnToCompletion(`npm`,[`install`,`--no-package-lock`,`--no-audit`,`--no-fund`,`--prefix`,n,...C?[`--loglevel`,`verbose`]:[`--loglevel`,`warn`],...S],{completion:`return`,notFound:n=>Error(`npm not found on PATH — install Node.js, or unset GJSIFY_INSTALL_BACKEND to use the default native backend (${n.message})`)});if(F!==0)throw Error(`npm install exited with code ${F}`)}var yF,bF=__esmMin(()=>{Vl(),Hs(),_P(),FP(),yF=process.env.GJSIFY_INSTALL_BACKEND??`native`});function defaultGlobalLayout(){let n=process.env.GJSIFY_GLOBAL_PREFIX,S=process.env.GJSIFY_GLOBAL_BIN_DIR,C=homedir(),N=process.env.XDG_DATA_HOME??js(C,`.local`,`share`);return{prefix:n??js(N,`gjsify`,`global`),binDir:S??js(C,`.local`,`bin`)}}function hasBundlerEngineInstalled(n){let S=new Set(detectNativePackages(n).map(n=>n.name));if(S.has(`@gjsify/rolldown-native`))return!0;let C=detectHostLibc(process.platform);return hostPlatformTokens(process.platform,process.arch,C).some(n=>S.has(platformPackageName(SF,n)))}async function installGjsEnginePackages(n,S,C={}){let N=C.verbose??!1,F=C.installFn??(async S=>{let{installPackages:C}=await Promise.resolve().then(()=>(bF(),vF));await C({prefix:n,specs:[S],verbose:N})});for(let n of xF){let C=S?`${n}@${S}`:n;try{await F(C)}catch(C){let F=C instanceof Error?C.message:String(C);n===`@gjsify/rolldown-native`?ve.warn(`\nWarning: could not install the GJS bundler engine ${n}@${S} — ${F}\n \`gjsify build\` (and storybook / flatpak) will fail under GJS until it is present.\n This usually means no prebuild is published for this platform (${process.platform}/${process.arch}).`):N&&ve.warn(`gjsify install: optional GJS engine ${n}@${S} not installed — ${F}`)}}}function linkGlobalBins(n,S){mkdirSync(S.binDir,{recursive:!0});let C=[],N=detectNativePackages(S.prefix).map(n=>n.prebuildsDir),F=buildNativeEnvPreamble(S.prefix,N);for(let I of n){let n=js(S.prefix,`node_modules`,I),H=js(n,`package.json`);if(!existsSync(H))continue;let W=pickBinMap(I,readJson(H));if(!(W===null||W.map.size===0))for(let[I,H]of W.map){let q=js(n,H);if(!existsSync(q))continue;try{chmodSync(q,493)}catch{}let Y=js(S.binDir,I);for(let n of[Y,`${Y}.cmd`,`${Y}.ps1`])rmSync(n,{force:!0,maxRetries:10,retryDelay:100});let X=isGjsBundlePath(q),Z=W.nodeFallback?.get(I),te=Z===void 0?void 0:js(n,Z),ne=te!==void 0&&existsSync(te)?te:void 0;if(writeFileSync(Y,buildShLauncher(q,{envPreamble:F,isGjsBundle:X,nodeFallbackAbs:ne})),chmodSync(Y,493),process.platform===`win32`){let n=N.join(`;`),S=X&&N.length>0?{GI_TYPELIB_PATH:n,PATH:n}:{},C=X?null:readShebangOf(q),F=buildLauncherShims(X?{interpreter:`gjs`,interpreterArgs:[`-m`],target:q,prependEnv:S,fallback:ne===void 0?void 0:{interpreter:`node`,target:ne}}:{interpreter:C?.prog||`node`,interpreterArgs:C?.args.trim()?C.args.trim().split(/\s+/):[],target:q});writeFileSync(`${Y}.cmd`,F.cmd),writeFileSync(`${Y}.ps1`,F.ps1)}C.push({name:I,target:q,link:Y})}}return C}function readShebangOf(n){try{return parseShebang(readFileSync(n,`utf-8`).trimStart().split(/\r*\n/,1)[0]??``)}catch{return null}}function readJson(n){return JSON.parse(readFileSync(n,`utf-8`))}function globalLayoutIsDefault(n=process.env){return!n.GJSIFY_GLOBAL_PREFIX&&!n.GJSIFY_GLOBAL_BIN_DIR}function pathFor$1(n){return n===`win32`?Cs:xs}function searchPathEntries(n,S){let C=pathFor$1(S),N=S===`win32`?`;`:`:`;return n.split(N).filter(Boolean).map(n=>C.resolve(n))}function binDirOnPath(n){let S=pathFor$1(process.platform).resolve(n);return searchPathEntries(process.env.PATH??``,process.platform).includes(S)}function resolveBinOnPath(n,S={}){let C=S.platform??process.platform,N=S.pathValue??process.env.PATH??``,F=S.exists??existsSync,I=C===`win32`?[...(S.pathExt??process.env.PATHEXT??CF).split(`;`).filter(Boolean).map(n=>n.startsWith(`.`)?n:`.${n}`),``]:[``],H=pathFor$1(C);for(let S of searchPathEntries(N,C))for(let C of I){let N=H.join(S,`${n}${C}`);if(F(N))return N}return null}function specToPackageName(n){if(n.startsWith(`@`)){let S=n.indexOf(`/`);if(S<0)return n;let C=n.indexOf(`@`,S);return C<0?n:n.slice(0,C)}let S=n.indexOf(`@`);return S<0?n:n.slice(0,S)}var xF,SF,CF,wF=__esmMin(()=>{ye(),Vl(),Dm(),Hs(),gN(),jP(),xF=[`@gjsify/rolldown-native`,`@gjsify/lightningcss-native`,`@gjsify/oxfmt-native`],SF=`@gjsify/rolldown-native`,__name$1(pathFor$1,`pathFor`),CF=`.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC`});function usingSelfShim(){return EF}function needsSelfShim(n){if(n.gjs)return!0;let S=Ms(n.workspaceRoot,n.selfEntry);return S===``||S.startsWith(`..`)||As(S)}function ensureGjsifyShimOnPath(){if(TF)return;TF=!0;let n=process.env.GJSIFY_SHIM_DIR;if(n&&existsSync(js(n,`gjsify`))){EF=!0,(process.env.PATH??``).split(Bs).includes(n)||(process.env.PATH=n+Bs+(process.env.PATH??``));return}let S=isGjs(),C=fileURLToPath(S?import.meta.url:new URL(`../index.js`,import.meta.url));if(!needsSelfShim({gjs:S,selfEntry:C,workspaceRoot:findWorkspaceRoot(process.cwd())??process.cwd()}))return;let N=mkdtempSync(js(tmpdir(),`gjsify-shim-`)),F=js(N,`gjsify`),I=S?process.env.GJS_CONSOLE||`gjs`:`node`,H=S?[`-m`]:[];if(writeFileSync(F,`#!/bin/sh\nexec "${I}" ${H.length>0?`${H.join(` `)} `:``}"${C}" "$@"\n`,{mode:493}),chmodSync(F,493),!S&&process.platform===`win32`){let{cmd:n,ps1:S}=buildLauncherShims({interpreter:I,interpreterArgs:H,target:C});writeFileSync(`${F}.cmd`,n),writeFileSync(`${F}.ps1`,S)}EF=!0,process.env.GJSIFY_SHIM_DIR=N,process.env.PATH=N+Bs+(process.env.PATH??``),writeNodeShim(N,S,C)}function nodeShimDir(){let n=process.env.GJSIFY_SHIM_DIR;if(!n)return null;let S=js(n,DF);return existsSync(js(S,`node`))?S:null}function writeNodeShim(n,S,C){if(!S)return;let N=js(n,DF);if(existsSync(js(N,`node`))||resolveBinOnPath(`node`))return;let F=process.env.GJS_CONSOLE||`gjs`;mkdirSync(N,{recursive:!0});let I=js(N,`node`);writeFileSync(I,`#!/bin/sh
|
|
891
891
|
case "\$1" in
|
|
892
892
|
-*) echo "gjsify: this host has no node; the gjsify shim runs a SCRIPT FILE only" >&2
|
|
893
893
|
echo "gjsify: got: node \$*" >&2
|
|
894
894
|
exit 127 ;;
|
|
895
895
|
esac
|
|
896
|
-
exec "${F}" -m "${C}" run --node-script "$@"\n`,{mode:493}),chmodSync(I,493)}var
|
|
897
|
-
\r*?{}[]~#!`.includes(H))return null;C+=H,N=!0}return F?null:(N&&S.push(C),S)}function gjsifyCommandArgv(n){let S=tokenizeSimpleCommand(n);return!S||S.length<2||S[0]!==`gjsify`?null:S.slice(1)}var
|
|
896
|
+
exec "${F}" -m "${C}" run --node-script "$@"\n`,{mode:493}),chmodSync(I,493)}var TF,EF,DF,OF=__esmMin(()=>{Vl(),Dm(),Hs(),gn(),th(),jP(),wF(),qM(),TF=!1,EF=!1,DF=`node-shim`});function tokenizeSimpleCommand(n){let S=[],C=``,N=!1,F=null;for(let I=0;I<n.length;I++){let H=n[I];if(F===`'`){H===`'`?F=null:C+=H;continue}if(F===`"`){if(H===`"`)F=null;else if(H===`\\`&&(n[I+1]===`"`||n[I+1]===`\\`))C+=n[++I];else if(H===`$`||H==="`")return null;else C+=H;continue}if(H===`'`||H===`"`){F=H,N=!0;continue}if(H===` `||H===` `){N&&=(S.push(C),C=``,!1);continue}if(`|&;<>\`$()\\
|
|
897
|
+
\r*?{}[]~#!`.includes(H))return null;C+=H,N=!0}return F?null:(N&&S.push(C),S)}function gjsifyCommandArgv(n){let S=tokenizeSimpleCommand(n);return!S||S.length<2||S[0]!==`gjsify`?null:S.slice(1)}var kF=__esmMin(()=>{});function markDaemonCommand(){AF=!0}function isDaemonCommand(){return AF}var AF,jF=__esmMin(()=>{AF=!1});async function runTargetOnRuntime(n,S,C){if(!looksLikeFile(S))return ve.error(`gjsify run: --runtime ${n} needs a bundle FILE, but "${S}" is not a path.\n Build first (e.g. \`gjsify build src/app.ts --app ${n===`gjs`?`gjs`:`node`} --outfile dist/app.${n===`gjs`?`gjs`:`node`}.mjs\`), then run the output file.`),process.exit(1);let N=readPackageJson$1(js(process.cwd(),`package.json`)),F=checkRuntimeSupported(n,readDeclaredRuntimes(N),N?.name??S);if(!F.ok)return ve.error(`gjsify run: ${F.message}`),process.exit(1);let I=Os(S);n===`gjs`?await runGjsBundle(I,C,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(n,I,C,{completion:`exit`,exitOnSuccess:!0})}function isLikelyGjsBundle(n){if(/\.gjs\.[mc]?js$/.test(n))return!0;try{let S=readFileSync(n,`utf-8`).slice(0,65536);return S.startsWith(`#!/usr/bin/env -S gjs`)||/(?:from|import)\s*["']gi:\/\//.test(S)||/\bimports\.(?:gi|system)\b/.test(S)}catch{return!1}}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 runScriptInWorkspace(n,S,C){let N=findWorkspaceRoot(process.cwd())??process.cwd(),F;try{F=discoverWorkspaces(N)}catch(n){return ve.error(`gjsify run: could not read workspaces at ${N}: ${n.message}`),process.exit(1)}let I=F.find(S=>S.name===n||S.relativeLocation===n||Fs(S.location)===n);if(!I){let S=F.map(n=>n.relativeLocation).join(`, `)||`<none>`;return ve.error(`gjsify run: no workspace "${n}" under ${N} (available: ${S})`),process.exit(1)}await runScript(S,C,I.location)}async function runScript(n,S,C=process.cwd()){let N=js(C,`package.json`),F=readPackageJson$1(N);if(!F)return ve.error(`gjsify run: no package.json in ${C}`),process.exit(1);let I=F.scripts??{},H=I[n];if(typeof H!=`string`){let S=Object.keys(I).join(`, `)||`<none>`;return ve.error(`gjsify run: no script "${n}" in ${N} (available: ${S})`),process.exit(1)}let W=findWorkspaceRoot(C),q=[js(C,`node_modules`,`.bin`)];W&&W!==C&&q.push(js(W,`node_modules`,`.bin`)),process.env.GJSIFY_SHIM_DIR&&q.unshift(process.env.GJSIFY_SHIM_DIR);let Y=nodeShimDir();Y&&q.unshift(Y);let X=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},Z={...process.env,...X,PATH:[...q,process.env.PATH??``].filter(Boolean).join(Bs),npm_lifecycle_event:n,npm_package_name:F.name??``,npm_package_version:F.version??``},te=isGjs()?gjsifyInProcessArgv(H,S):null;if(te){process.env.PATH=Z.PATH,process.env.npm_lifecycle_event=Z.npm_lifecycle_event,process.env.npm_package_name=Z.npm_package_name,process.env.npm_package_version=Z.npm_package_version,Z.FORCE_COLOR!==void 0&&(process.env.FORCE_COLOR=Z.FORCE_COLOR),C!==process.cwd()&&process.chdir(C);let n=!1;try{let{runCli:n}=await Promise.resolve().then(()=>(gH(),hH));await n(te)}catch(S){ve.error(S.message),n=!0}if(!n&&isDaemonCommand())return;let S=n?1:process.exitCode==null?0:Number(process.exitCode);return process.exit(S)}let ne=S.length>0?`${H} ${S.map(shellEscape).join(` `)}`:H,re;try{re=await spawnToCompletion(ne,[],{completion:`exit`,cwd:C,env:Z,shell:!0})}catch(n){return ve.error(n.message),process.exit(1)}return re.code===0?process.exit(0):(ve.error(`script "${n}" exited with ${describeExit(re)}`),process.exit(1))}function shellEscape(n){return/^[a-zA-Z0-9_\-./=:@,]+$/.test(n)?n:`'${n.replace(/'/g,`'\\''`)}'`}function gjsifyInProcessArgv(n,S){let C=gjsifyCommandArgv(n);return C?[...C,...S]:null}var MF,NF=__esmMin(()=>{ye(),Vl(),Hs(),wP(),_P(),yP(),xP(),TP(),EP(),OF(),qM(),kF(),jF(),GM(),th(),Ah(),MF={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:[]}).option(`workspace`,{alias:`w`,type:`string`,description:"Run <target> as a script in the named workspace (by name or path), like `npm run <script> -w <name>`."}).option(`node-script`,{type:`boolean`,default:!1,description:"Treat <target> as an unbundled Node-style script (imports `node:` builtins) and run it on the host runtime. Under GJS the file is bundled `--app gjs` on the fly first, which is what makes a repo script runnable on a host that has no Node."}).option(`runtime`,{type:`string`,choices:Oh,description:"Runtime to launch a bundle FILE on: gjs (default, `--app gjs` bundle) | node | bun | deno (the `--app node` bundle). Forces file mode."}).version(!1).help(!1).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1,"unknown-options-as-args":!0}),handler:async n=>{let S=n.target,C=[...n.args??[],...doubleDashArgs(n)];if(n.nodeScript===!0){let isSet=n=>typeof n==`string`&&n.length>0,N=isSet(n.runtime)?`--runtime`:isSet(n.workspace)?`--workspace`:null;if(N)return ve.error(`gjsify run: --node-script cannot be combined with ${N}.`),process.exit(1);await runNodeScript(S,C,{completion:`exit`,exitOnSuccess:!0});return}let N=n.runtime;if(typeof N==`string`&&N.length>0){if(typeof n.workspace==`string`&&n.workspace.length>0)return ve.error(`gjsify run: --runtime cannot be combined with --workspace (file mode vs script mode).`),process.exit(1);if(!isExampleRuntime(N))return ve.error(`gjsify run: unknown --runtime "${N}" (expected: ${Oh.join(`, `)}).`),process.exit(1);await runTargetOnRuntime(N,S,C);return}if(typeof n.workspace==`string`&&n.workspace.length>0){await runScriptInWorkspace(n.workspace,S,C);return}let F=readPackageJson$1(js(process.cwd(),`package.json`));if(!(F?.scripts&&typeof F.scripts[S]==`string`)&&looksLikeFile(S)){let n=Os(S),N=hostRuntime$1(),F=N===`gjs`||isLikelyGjsBundle(n)?`gjs`:N;F===`gjs`?await runGjsBundle(n,C,{completion:`exit`,exitOnSuccess:!0}):await runRuntimeBundle(F,n,C,{completion:`exit`,exitOnSuccess:!0});return}await runScript(S,C)}}}),PF,FF=__esmMin(()=>{ye(),Hs(),gN(),PF={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 S=process.cwd(),C=n.file?Os(n.file):null,N=detectNativePackages(S),F=buildNativeEnv(N),I=Object.entries(F).filter(([,n])=>n!==void 0);if(n.export){for(let[n,S]of I)ve.log(`export ${n}="${S}"`);return}if(N.length===0){ve.log(`No native gjsify packages detected in node_modules.`),ve.log(`Native packages declare "gjsify": { "prebuilds": "<dir>" } in their package.json.`);return}ve.log(`Native packages detected:`);for(let n of N)ve.log(` ${n.name} → ${n.prebuildsDir}`);ve.log(``),ve.log(`To run your app directly with gjs, set:`);for(let[n,S]of I)ve.log(` export ${n}="${S}"`);C?ve.log(` gjs -m ${C}`):ve.log(` gjs -m <your-bundle.js>`),ve.log(``),ve.log(`Or use gjsify run to handle this automatically:`),C?ve.log(` gjsify run ${n.file}`):ve.log(` gjsify run <your-bundle.js>`)}}}),IF,LF=__esmMin(()=>{ye(),dN(),IF={command:`system-check`,description:"Check that required system dependencies (GJS, GTK4, libsoup3, …) are installed. Optional dependencies are detected only when their @gjsify/* package is in your project. (Previously called `gjsify check`; the bare name now runs TypeScript checks across the workspace — see `gjsify check --help`.)",builder:n=>n.option(`json`,{description:`Output results as JSON`,type:`boolean`,default:!1}),handler:async n=>{let S=runAllChecks(process.cwd()),C=detectPackageManager$1(),N=checkTypeSkew(process.cwd()),F=S.filter(n=>!n.found&&n.severity===`required`),I=S.filter(n=>!n.found&&n.severity===`optional`),H=[...F,...I];if(n.json)return ve.log(JSON.stringify({packageManager:C,deps:S,typeSkew:N},null,2)),process.exit(+(F.length>0));ve.log(`System dependency check
|
|
898
898
|
`);let W=S.filter(n=>n.severity===`required`),q=S.filter(n=>n.severity===`optional`);if(W.length>0){ve.log(`Required:`);for(let n of W){let S=n.found?`✓`:`✗`,C=n.version?` (${n.version})`:``;ve.log(` ${S} ${n.name}${C}`)}}if(q.length>0){ve.log(`
|
|
899
899
|
Optional:`);for(let n of q){let S=n.found?`✓`:`⚠`,C=n.version?` (${n.version})`:``,N=n.requiredBy&&n.requiredBy.length>0?` — needed by ${n.requiredBy.join(`, `)}`:``;ve.log(` ${S} ${n.name}${C}${N}`)}}if(N.length>0){ve.log(`
|
|
900
900
|
Type/runtime version skew:`);for(let n of N){let S=n.relation===`ahead`?`⚠`:`ℹ`;ve.log(` ${S} ${n.typePackage} describes ${n.declared}, installed ${n.pkgConfig} is ${n.installed}`)}N.some(n=>n.relation===`ahead`)&&ve.log(`
|
|
@@ -906,19 +906,19 @@ Type/runtime version skew:`);for(let n of N){let S=n.relation===`ahead`?`⚠`:`
|
|
|
906
906
|
All dependencies found.`);return}F.length>0&&ve.log(`\nMissing required: ${F.map(n=>n.name).join(`, `)}`),I.length>0&&ve.log(`Missing optional: ${I.map(n=>n.name).join(`, `)}`);let Y=buildInstallCommand(C,H);Y?ve.log(`\nTo install:\n ${Y}`):ve.log(`
|
|
907
907
|
No install command available for your package manager. Install manually.`),process.exit(+(F.length>0))}}});function prefixLines(n,S,C,N){let F=``,I=``,emit=n=>{N?I+=n:S.write(n)};return n.setEncoding(`utf-8`),n.on(`data`,n=>{F+=n;let S;for(;(S=F.indexOf(`
|
|
908
908
|
`))!==-1;)emit(C+F.slice(0,S+1)),F=F.slice(S+1)}),n.on(`end`,()=>{F.length>0&&emit(C+F+`
|
|
909
|
-
`)}),()=>{I.length>0&&(S.write(I),I=``)}}var
|
|
909
|
+
`)}),()=>{I.length>0&&(S.write(I),I=``)}}var RF=__esmMin(()=>{});function dirLinkTarget(n,S,C=zF){return C===`junction`?Os(S):Ms(Ps(n),S)}function linkDirSync(n,S){assertAbsolute(S),symlinkSync(dirLinkTarget(n,S),n,BF)}function replicateLinkSync(n,S){let C=readlinkSync(n);if(!dirLinksAreJunctions()){symlinkSync(C,S);return}let N=Os(Ps(n),C),F;try{F=statSync(N).isDirectory()}catch{symlinkSync(C,S);return}F?symlinkSync(N,S,`junction`):symlinkSync(C,S,`file`)}function assertAbsolute(n){if(Os(n)!==n)throw TypeError(`linkDir: target must be an absolute path, got ${JSON.stringify(n)}. Node resolves a Windows junction target against the process CWD rather than the link's own directory, so a relative target silently points somewhere else there.`)}var zF,BF,dirLinksAreJunctions,VF=__esmMin(()=>{Vl(),Cl(),Hs(),zF=process.platform===`win32`?`junction`:`symlink`,BF=zF===`junction`?`junction`:void 0,dirLinksAreJunctions=()=>zF===`junction`});function buildCacheEnabledByEnv(n=process.env){let S=n.GJSIFY_BUILD_CACHE;return S===void 0?!1:S!==``&&S!==`0`&&S!==`false`}function buildCacheRoot(n){return js(n,`node_modules`,`.cache`,`gjsify`,`build`)}function sanitizePackageDirName(n){return`${n.replace(/^@/,``).replace(/[^A-Za-z0-9._-]/g,`-`)}-${createHash(`sha256`).update(n).digest(`hex`).slice(0,8)}`}function hashFileStream(n){let S=createHash(`sha256`),C=openSync(n,`r`);try{let n=Buffer.alloc(64*1024);for(;;){let N=readSync(C,n,0,n.length,null);if(N<=0)break;S.update(n.subarray(0,N))}}finally{closeSync(C)}return S.digest(`hex`)}function walkFiles(n,S,C){let N;try{N=readdirSync(n)}catch{return}N.sort();for(let F of N){if(F===`node_modules`)continue;let N=js(n,F),I=S===``?F:`${S}/${F}`,H;try{H=lstatSync(N)}catch{continue}if(H.isSymbolicLink())try{let n=readlinkSync(N);C.push({rel:I,abs:N,link:n})}catch{}else H.isDirectory()?walkFiles(N,I,C):H.isFile()&&C.push({rel:I,abs:N})}}function hashPackageInputs(n){let S=[],C=js(n,`package.json`);existsSync(C)&&S.push({rel:`package.json`,abs:C});let N=[];try{N=readdirSync(n)}catch{}for(let C of N.sort())/^tsconfig.*\.json$/.test(C)&&S.push({rel:C,abs:js(n,C)});let F=js(n,`src`);existsSync(F)&&walkFiles(F,`src`,S);let I=createHash(`sha256`);I.update(`gjsify-build-cache-inputs/v3
|
|
910
910
|
`);for(let n of S){if(n.link!==void 0){let S;try{S=hashFileStream(n.abs)}catch{S=`link:${n.link}`}I.update(`${n.rel} ${S}\n`);continue}try{I.update(`${n.rel} ${hashFileStream(n.abs)}\n`)}catch{I.update(`${n.rel} unreadable\n`)}}return I.digest(`hex`)}function hashOutputDirs(n,S){let C=createHash(`sha256`);C.update(`gjsify-build-cache-outputs/v3
|
|
911
|
-
`);for(let N of[...S].sort()){let S=js(n,N);if(!existsSync(S)){C.update(`${N} absent\n`);continue}let F=[];walkFiles(S,N,F);for(let n of F){if(n.link!==void 0){C.update(`${n.rel} link:${n.link}\n`);continue}try{C.update(`${n.rel} ${hashFileStream(n.abs)}\n`)}catch{C.update(`${n.rel} unreadable\n`)}}}return C.digest(`hex`)}function outputUnits(n){let S=[];for(let C of
|
|
912
|
-
`),S.update(`script:${n.script}\n`);for(let C of n.args??[])S.update(`arg:${C}\n`);for(let C of Object.keys(n.toolchain).sort())S.update(`tool:${C}@${n.toolchain[C]}\n`);S.update(`self:${n.ownHash}\n`);let C=n.depHashes instanceof Map?n.depHashes:new Map(Object.entries(n.depHashes));for(let n of[...C.keys()].sort())S.update(`dep:${n} ${C.get(n)}\n`);return S.digest(`hex`).slice(0,32)}function resolveToolchainVersions(n){let S={};for(let C of HF){let N=`none`;try{let S=readFileSync(js(n,`node_modules`,...C.split(`/`),`package.json`),`utf-8`),F=JSON.parse(S);typeof F.version==`string`&&(N=F.version)}catch{}C===`@gjsify/cli`&&N===`none`&&(N=readOwnCliVersion()??`none`),S[C]=N}return S}function readOwnCliVersion(){try{let n=Ps(fileURLToPath(import.meta.url));for(let S=0;S<4;S++){let S=js(n,`package.json`);if(existsSync(S)){let n=JSON.parse(readFileSync(S,`utf-8`));if(n.name===`@gjsify/cli`&&typeof n.version==`string`)return n.version}n=Ps(n)}}catch{}return null}function copyDirRecursive(n,S){mkdirSync(S,{recursive:!0});for(let C of readdirSync(n).sort()){let N=js(n,C),F=js(S,C),I=lstatSync(N);if(I.isSymbolicLink())replicateLinkSync(N,F);else if(I.isDirectory())copyDirRecursive(N,F);else if(I.isFile()){copyFileSync(N,F);try{chmodSync(F,I.mode&511)}catch{}}}}function buildCacheEntryDir(n,S,C){return js(n,sanitizePackageDirName(S),C)}function readCacheEntry(n,S,C){let N=js(UF(n,S,C),`manifest.json`);try{let F=JSON.parse(readFileSync(N,`utf-8`));if(F.version!==1||F.layout!==`v3`||F.package!==S||F.key!==C||!Array.isArray(F.dirs))return null;for(let N of F.dirs)if(!existsSync(js(UF(n,S,C),`outputs`,N)))return null;return F}catch{return null}}function storeCacheEntry(n,S,C,N,F){let I=UF(n,S.name,C),H=`${I}.tmp-${process.pid}`;try{rmSync(H,{recursive:!0,force:!0}),mkdirSync(js(H,`outputs`),{recursive:!0});for(let n of F)copyDirRecursive(js(S.location,n),js(H,`outputs`,n));let W=new Date().toISOString(),q={version:1,layout:`v3`,package:S.name,script:N,key:C,dirs:[...F],outputsHash:hashOutputDirs(S.location,F),createdAt:W,usedAt:W};return writeFileSync(js(H,`manifest.json`),JSON.stringify(q,null,2)),rmSync(I,{recursive:!0,force:!0}),renameSync(H,I),pruneCacheEntries(n,S.name),q}catch{try{rmSync(H,{recursive:!0,force:!0})}catch{}return null}}function restoreCacheEntry(n,S,C){let N=UF(n,S.name,C.key);try{if(C.dirs.length>0&&hashOutputDirs(S.location,C.dirs)===C.outputsHash)return touchManifestUsed(N,C),`up-to-date`;for(let n of C.dirs){let C=js(S.location,n);rmSync(C,{recursive:!0,force:!0}),copyDirRecursive(js(N,`outputs`,n),C)}return touchManifestUsed(N,C),C.dirs.length>0?`restored`:`up-to-date`}catch{return null}}function touchManifestUsed(n,S){try{S.usedAt=new Date().toISOString(),writeFileSync(js(n,`manifest.json`),JSON.stringify(S,null,2))}catch{}}function pruneCacheEntries(n,S,C=2){let N=js(n,sanitizePackageDirName(S)),F;try{F=readdirSync(N)}catch{return}let I=[];for(let n of F){if(n.includes(`.tmp-`)){try{rmSync(js(N,n),{recursive:!0,force:!0})}catch{}continue}let S=``;try{let C=JSON.parse(readFileSync(js(N,n,`manifest.json`),`utf-8`));S=C.usedAt??C.createdAt??``}catch{}I.push({name:n,stamp:S})}if(!(I.length<=C)){I.sort((n,S)=>n.stamp<S.stamp?1:n.stamp>S.stamp?-1:0);for(let n of I.slice(C))try{rmSync(js(N,n.name),{recursive:!0,force:!0})}catch{}}}function buildCacheOptedOut(n){return n.manifest.gjsify?.buildCache===!1}var VF,HF,isBuildInfo,UF,BuildCacheRunner,WF=__esmMin(()=>{ye(),No(),Vl(),Hs(),gn(),GM(),BF(),VF=[`lib`,`dist`,`dist-templates`],HF=[`@gjsify/cli`,`@gjsify/tsc`,`rolldown`,`typescript`],isBuildInfo=n=>n.endsWith(`.tsbuildinfo`),UF=buildCacheEntryDir,BuildCacheRunner=class{options;cacheRoot;graph;toolchain;ownHashes=new Map;closures=new Map;keys=new Map;log;constructor(n){this.options=n,this.cacheRoot=buildCacheRoot(n.root),this.graph=buildDependencyGraph(n.workspaces,{includeDev:!0,includePeer:!0,includeOptional:!0}),this.toolchain=resolveToolchainVersions(n.root),this.log=n.log??(n=>ve.error(n));for(let S of n.targets??[])if(this.graph.byName.has(S)){this.ownHashOf(S);for(let n of this.closureOf(S))this.ownHashOf(n)}}ownHashOf(n){let S=this.ownHashes.get(n);if(S===void 0){let C=this.graph.byName.get(n);S=C?hashPackageInputs(C.location):`unknown-workspace`,this.ownHashes.set(n,S)}return S}closureOf(n){let S=this.closures.get(n);if(S===void 0){let C=new Set,N=[...this.graph.edges.get(n)??[]];for(;N.length>0;){let S=N.shift();if(!(S===n||C.has(S))){C.add(S);for(let F of this.graph.edges.get(S)??[])!C.has(F)&&F!==n&&N.push(F)}}S=[...C].sort(),this.closures.set(n,S)}return S}keyFor(n){let S=this.keys.get(n.name);if(S===void 0){let C=new Map;for(let S of this.closureOf(n.name))C.set(S,this.ownHashOf(S));S=composeCacheKey({script:this.options.script,args:this.options.args,toolchain:this.toolchain,ownHash:this.ownHashOf(n.name),depHashes:C}),this.keys.set(n.name,S)}return S}tryRestore(n){try{if(buildCacheOptedOut(n))return this.log(`[gjsify build-cache] ${n.name}: opted out (gjsify.buildCache=false) — running uncached`),!1;let S=this.keyFor(n),C=readCacheEntry(this.cacheRoot,n.name,S);if(!C||C.script!==this.options.script)return this.log(`[gjsify build-cache] ${n.name}: miss ${S} — running "${this.options.script}"`),!1;let N=restoreCacheEntry(this.cacheRoot,n,C);if(N===null)return this.log(`[gjsify build-cache] ${n.name}: entry ${S} unrestorable — running "${this.options.script}"`),!1;let F=C.dirs.length>0?C.dirs.join(`, `):`no output dirs`;return this.log(`[gjsify build-cache] ${n.name}: hit ${S} — ${N===`restored`?`restored ${F}`:`${F} up to date`} (skipped "${this.options.script}")`),!0}catch(S){return this.log(`[gjsify build-cache] ${n.name}: cache error (${S.message}) — running uncached`),!1}}snapshotOutputs(n){try{return snapshotOutputDirs(n.location)}catch{return{}}}storeAfterSuccess(n,S){try{if(buildCacheOptedOut(n))return;let C=this.keyFor(n),N=modifiedOutputDirs(n.location,S);if(storeCacheEntry(this.cacheRoot,n,C,this.options.script,N)){let S=N.length>0?N.join(`, `):`no output dirs modified`;this.log(`[gjsify build-cache] ${n.name}: stored ${C} (${S})`)}}catch(S){this.log(`[gjsify build-cache] ${n.name}: store failed (${S.message}) — continuing`)}}}});function editDistance(n,S){if(n===S)return 0;if(n.length===0)return S.length;if(S.length===0)return n.length;let C=Array.from({length:S.length+1},(n,S)=>S),N=Array.from({length:S.length+1},()=>0);for(let F=1;F<=n.length;F++){N[0]=F;for(let I=1;I<=S.length;I++){let H=n[F-1]===S[I-1]?0:1;N[I]=Math.min(C[I]+1,N[I-1]+1,C[I-1]+H)}[C,N]=[N,C]}return C[S.length]}function suggestClosest(n,S){if(S.length===0)return;let C=n.toLowerCase(),N=Math.max(2,Math.floor(n.length/3)),F,I=1/0;for(let n of S){let S=editDistance(C,n.toLowerCase());S<I&&(I=S,F=n)}return F!==void 0&&I<=N?F:void 0}var GF=__esmMin(()=>{});function collectTransitiveClosure(n,S,C){let N=new Map;for(let n of S)N.set(n.name,n);let F=new Set,I=[],H=[n];for(;H.length>0;){let n=H.pop();if(F.has(n.name))continue;F.add(n.name),I.push(n);let S=n.manifest,W=[S.dependencies,C?S.devDependencies:void 0,S.optionalDependencies];for(let n of W)if(n)for(let[S,C]of Object.entries(n)){if(typeof C!=`string`||!C.startsWith(`workspace:`))continue;let n=N.get(S);n&&(F.has(n.name)||H.push(n))}}return I}async function runOne$1(n,S,C,N,F,I){if(I&&I.tryRestore(n))return;let H=I?.snapshotOutputs(n),W=N===`gjsify`?[`run`,S,...C]:[`run`,S,...C.length>0?[`--`,...C]:[]];F&&ve.error(`[${n.name}] $ ${N} ${W.join(` `)}`);let{code:q}=await spawnToCompletion(N,W,{completion:`exit`,cwd:n.location,color:!0});if(q!==0)throw Error(`${N} ${W.join(` `)} exited with code ${q}`);I&&H&&I.storeAfterSuccess(n,H)}function detectPackageManager(){if(isGjs()||usingSelfShim())return`gjsify`;let n=process.env.npm_config_user_agent??``;return n.startsWith(`yarn/`)?`yarn`:n.startsWith(`gjsify/`)?`gjsify`:`npm`}var KF,qF=__esmMin(()=>{ye(),_P(),GM(),qM(),WF(),th(),DF(),GF(),KF={command:`workspace <name> <script> [args..]`,description:"Run a workspace script. Both `workspace <name> <script>` and the yarn spelling `workspace <name> run <script>` work.",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}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip the script for a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run it and store the output dirs it modified. Also applies to the deps run via --with-dependencies. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}),handler:async n=>{let S=findWorkspaceRoot(process.cwd())??process.cwd(),C=discoverWorkspaces(S),N=C.find(S=>S.name===n.name);if(!N){let N=suggestClosest(n.name,C.map(n=>n.name)),F=N?` — did you mean "${N}"?`:``;return ve.error(`gjsify workspace: no workspace named "${n.name}"${F} (discovered ${C.length} workspace(s) under ${S})`),process.exit(1)}let F=detectPackageManager(),I=n.verbose===!0,H=n[`with-dependencies`]===!0,W=n[`continue-on-error`]===!0,q=n.script,Y=n.args??[];q===`run`&&Y.length>0&&([q,...Y]=Y);let X=N.manifest.scripts??{};if(typeof X[q]!=`string`){let S=suggestClosest(q,Object.keys(X));return ve.error(`gjsify workspace: workspace "${n.name}" has no script "${q}"`+(S?` — did you mean "${S}"?`:``)),process.exit(1)}let Z;Z=H?topologicalSort(buildDependencyGraph(collectTransitiveClosure(N,C,n[`include-dev`]===!0),{includeDev:n[`include-dev`]===!0})):[N];let te=n.cached??buildCacheEnabledByEnv()?new BuildCacheRunner({root:S,workspaces:C,script:q,args:Y,targets:Z.map(n=>n.name)}):void 0,ne=[];for(let n of Z){if(typeof(n.manifest.scripts??{})[q]!=`string`){I&&ve.error(`[${n.name}] (no "${q}" script — skipping)`);continue}try{await runOne$1(n,q,Y,F,I,te)}catch(S){let C=S instanceof Error?S:Error(String(S));if(ve.error(`[${n.name}] ${C.message}`),!W)return process.exit(1);ne.push({workspace:n.name,error:C})}}return ne.length>0?(ve.error(`gjsify workspace: ${ne.length} workspace(s) failed: ${ne.map(n=>n.workspace).join(`, `)}`),process.exit(1)):process.exit(0)}},__name$1(runOne$1,`runOne`)});async function runCheck(n,S){let C=[],N=detectPackageManager();if(N===`gjsify`&&readPackageJson$2(js(n.location,`package.json`))?.scripts?.check===void 0)return 0;let F=N===`gjsify`?[`run`,`check`]:[`run`,`check`,`--if-present`];try{let{code:I}=await spawnToCompletion(N,F,{completion:`exit`,cwd:n.location,stdio:S===null?`inherit`:`pipe`,onSpawn:n=>{let N=!process.stdout.isTTY;if(S!==null&&n.stdout&&n.stderr){let F=`[${S}] `;C.push(prefixLines(n.stdout,process.stdout,F,N)),C.push(prefixLines(n.stderr,process.stderr,F,N))}}});for(let n of C)n();return I??1}catch{for(let n of C)n();return 1}}var JF,YF=__esmMin(()=>{ye(),LF(),_P(),KM(),Hs(),Dm(),GM(),qM(),qF(),JF={command:`check`,description:"Run `npm run check` (TypeScript type-check) across the current workspace. In a workspace root: walks every package with a `check` script (excludes @girs/*; honours --include/--exclude). In a single package: runs the local `check` script directly. Symmetric peer of `gjsify format` / `lint` / `fix`. (Legacy system-dep `gjsify check` is now `gjsify system-check` — see #254.)",builder:n=>n.option(`include`,{description:`Only run in workspaces matching these glob patterns (repeatable).`,type:`string`,array:!0}).option(`exclude`,{description:`Skip workspaces matching these glob patterns (repeatable). Always excludes @girs/*.`,type:`string`,array:!0}).option(`parallel`,{description:`Run workspace checks in parallel (default). Use --no-parallel to run them sequentially with full per-workspace output.`,type:`boolean`,alias:`p`,default:!0}).option(`jobs`,{description:`Max parallel workers (when --parallel). Default: os.cpus().length.`,type:`number`,alias:`j`}).option(`verbose`,{description:`Log the per-workspace command before spawning.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=findWorkspaceRoot(S);if(C&&S!==C&&readPackageJson$2(js(S,`package.json`))?.scripts?.check){n.verbose&&ve.log(`[check] cwd=${S} → npm run check`);let{code:C}=await spawnToCompletion(detectPackageManager(),[`run`,`check`],{cwd:S,completion:`exit`});return process.exit(C??1)}if(!C)return ve.error("gjsify check: no workspace root found from cwd. Run inside a workspace (or a package within one) with `npm run check` defined."),process.exit(1);let N=discoverWorkspaces(C),F=[`@girs/*`,...n.exclude??[]],I=filterWorkspaces(N,{include:n.include,exclude:F}).filter(n=>n.manifest.scripts?.check!==void 0);if(I.length===0)return ve.error("gjsify check: no workspaces with a `check` script found."),process.exit(1);if(n.verbose&&ve.log(`[check] root=${C} workspaces=${I.length} parallel=${n.parallel?`yes`:`no`}`),!n.parallel){let S=0,C=0;for(let N of I){n.verbose&&ve.log(`[check] → ${N.name}`);let F=await runCheck(N,null);F!==0&&(C++,S===0&&(S=F))}return S!==0&&ve.error(`gjsify check: failures in ${C} workspace(s)`),process.exit(S)}let H=n.jobs??Math.max(1,cpus().length),W=[],q=0,Y=[];for(let n=0;n<H;n++)Y.push((async()=>{for(;;){let n=q++;if(n>=I.length)return;let S=I[n],C=await runCheck(S,S.name);C!==0&&W.push({name:S.name,code:C})}})());if(await Promise.all(Y),W.length>0){ve.error(`\ngjsify check: ${W.length} of ${I.length} workspace(s) failed:`);for(let n of W)ve.error(` ✗ ${n.name} (exit ${n.code})`);return process.exit(1)}n.verbose&&ve.log(`\ngjsify check: ${I.length} workspace(s) green.`),process.exit(0)}}});function manifestPath(){let n=Ps(fileURLToPath(import.meta.url)),S=[js(n,`..`,`..`,`showcases.json`),js(n,`..`,`showcases.json`)];return S.find(n=>existsSync(n))??S[0]}function discoverShowcases(){let n=manifestPath();if(!existsSync(n))return[];let S;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch{return[]}if(!Array.isArray(S.showcases))return[];let C=S.showcases.map(n=>({name:n.name,packageName:n.package,category:n.category,description:n.description??``}));return C.sort((n,S)=>n.category.localeCompare(S.category)||n.name.localeCompare(S.name)),C}function findShowcase(n){return discoverShowcases().find(S=>S.name===n)}var XF=__esmMin(()=>{Vl(),Hs(),gn()});function parseSpec(n){if(!n)throw Error(`dlx: empty package spec`);if(n.startsWith(`./`)||n.startsWith(`../`)||As(n)||existsSync(n))return{kind:`local`,path:Os(n)};let S=n,C,N=n.lastIndexOf(`@`);if(N>0&&(S=n.slice(0,N),C=n.slice(N+1)),!ZF.test(S))throw Error(`dlx: invalid package name "${S}"`);return{kind:`registry`,name:S,version:C,spec:n}}var ZF,QF=__esmMin(()=>{Vl(),Hs(),ZF=/^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/});function resolveGjsEntry(n,S){let C=js(n,`package.json`);if(!existsSync(C))throw Error(`dlx: no package.json found at ${n}`);let N=JSON.parse(readFileSync(C,`utf-8`)),F=N.gjsify?.bin,I=N.gjsify?.main,H=N.main,W,q=null,Y=!1;if(S!==null){if(!F||!F[S]){let C=F?Object.keys(F).join(`, `):`(none)`;throw Error(`dlx: package "${N.name??n}" has no GJS bin named "${S}" — known: ${C}`)}W=F[S],q=S}else if(F&&Object.keys(F).length===1){let n=Object.keys(F)[0];W=F[n],q=n}else I?W=I:H&&(W=H,Y=!0);if(F&&Object.keys(F).length>1&&S===null){let S=Object.keys(F).join(`, `);throw Error(`dlx: package "${N.name??n}" defines multiple GJS bins — pass one of: ${S}`)}if(!W)throw Error(`dlx: package "${N.name??n}" has no GJS entry — set \`gjsify.main\` (or \`gjsify.bin\`) in its package.json`);let X=Os(n,W);if(!existsSync(X))throw Error(`dlx: GJS entry not found: ${X}`);return{bundlePath:X,binName:q,fromFallback:Y}}function resolveNodeEntry(n){let S=js(n,`package.json`);if(!existsSync(S))throw Error(`no package.json found at ${n}`);let C=JSON.parse(readFileSync(S,`utf-8`)),N=C.gjsify?.example?.node;if(N){let S=Os(n,N);if(!existsSync(S))throw Error(`declared node entry not found: ${S} (gjsify.example.node)`);return S}let F=C.gjsify?.main??(C.gjsify?.bin?Object.values(C.gjsify.bin)[0]:void 0)??C.main;if(!F)throw Error(`package "${C.name??n}" has no entry to derive a node bundle from — set \`gjsify.example.node\` to its \`--app node\` bundle path.`);let I=F.replace(/\.gjs\.(js|mjs|cjs)$/,``).replace(/\.(js|mjs|cjs)$/,``),H=[`${I}.node.mjs`,`${I}.node.js`,`${I}.node.cjs`];for(let S of H){let C=Os(n,S);if(existsSync(C))return C}throw Error(`package "${C.name??n}" has no \`--app node\` bundle — looked for ${H.join(`, `)}.\n Build one (e.g. \`gjsify build src/app.ts --app node --outfile dist/app.node.mjs\`) or set \`gjsify.example.node\` to its path.`)}var $F=__esmMin(()=>{Vl(),Hs()});function lexCompare(n,S){return n<S?-1:+(n>S)}function createCacheKey(n){let S=[...n.packages].sort(lexCompare),C=Object.entries(n.registries??{}).sort(([n],[S])=>lexCompare(n,S)),N=JSON.stringify([S,C]);return createHash(`sha256`).update(N).digest(`hex`)}function dlxCacheRoot(){let n=process.env.XDG_CACHE_HOME,S=js(n&&n.length>0?n:js(homedir(),`.cache`),`gjsify`,`dlx`);return mkdirSync(S,{recursive:!0}),S}function cacheDirFor(n){let S=js(dlxCacheRoot(),n);return mkdirSync(S,{recursive:!0}),S}function makePrepareDir(n){let S=js(n,`${Date.now().toString(16)}-${process.pid.toString(16)}`);return mkdirSync(S,{recursive:!0}),S}function getValidCachedPkg(n,S=tI){let C=js(n,`pkg`),N;try{N=lstatSync(C)}catch(n){if(n.code===`ENOENT`)return;throw n}if(!N.isSymbolicLink())return;let F;try{F=realpathSync(C)}catch{return}return Date.now()-N.mtime.getTime()<=S*eI?F:void 0}function symlinkSwap(n,S,C={}){let N=C.junctions??dirLinksAreJunctions(),F=js(n,`pkg`),I=js(n,`pkg.tmp-${Date.now().toString(16)}-${process.pid.toString(16)}`);linkDirSync(I,S);try{N&&rmSync(F,{force:!0,recursive:!1,maxRetries:10,retryDelay:100}),renameSync(I,F)}catch(n){let C=n.code;if(C===`EBUSY`||C===`EPERM`||C===`EEXIST`||C===`EACCES`){rmSync(I,{force:!0});try{return realpathSync(F)}catch{return realpathSync(S)}}throw n}return realpathSync(F)}function resolveInstalledPkgDir(n,S){return Os(n,`node_modules`,S)}var eI,tI,nI=__esmMin(()=>{No(),Vl(),Dm(),Hs(),BF(),eI=6e4,tI=1440*7});async function ensurePkgDir(n,S){if(n.kind===`local`)return{pkgDir:n.path,cachedPkgName:null};let C=[n.spec,...S.extraSpecs??[]],N=cacheDirFor(createCacheKey({packages:C})),F=S.cacheMaxAge>0?getValidCachedPkg(N,S.cacheMaxAge):void 0;if(F)return{pkgDir:resolveInstalledPkgDir(F,n.name),cachedPkgName:n.name};let I=makePrepareDir(N),H=makeProgressReporter({enabled:!S.verbose});return await installPackages({prefix:I,specs:C,verbose:S.verbose,registry:S.registry,lockfile:!0,frozen:S.frozen,progress:H}),{pkgDir:resolveInstalledPkgDir(symlinkSwap(N,I),n.name),cachedPkgName:n.name}}function splitBinAndArgs(n,S,C){if(!S)return{binName:null,extraArgs:C};let N=js(n,`package.json`);if(existsSync(N))try{let n=JSON.parse(readFileSync(N,`utf-8`)).gjsify?.bin;if(n&&Object.prototype.hasOwnProperty.call(n,S))return{binName:S,extraArgs:C}}catch{}return{binName:null,extraArgs:[S,...C]}}var rI,iI=__esmMin(()=>{ye(),yP(),QF(),$F(),nI(),yF(),Vl(),Hs(),rI={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 S=parseSpec(n.spec),C=n.reinstall?0:n[`cache-max-age`],{pkgDir:N,cachedPkgName:F}=await ensurePkgDir(S,{verbose:n.verbose,registry:n.registry,cacheMaxAge:C,frozen:n.frozen}),I=(n[`--`]??[]).map(n=>String(n)),H=[...n.extraArgs??[],...I],{binName:W,extraArgs:q}=splitBinAndArgs(N,n.binOrArg,H),Y=resolveGjsEntry(N,W);Y.fromFallback&&ve.warn(`[gjsify dlx] package "${F??S.kind}" declares no \`gjsify.main\` — falling back to package.json#main. Add \`gjsify.main\` to silence.`),await runGjsBundle(Y.bundlePath,q,{completion:`exit`,exitOnSuccess:!0})}}});async function loadNpmrc(n){let S=[],C=js(n,`.npmrc`);existsSync(C)&&S.push(readFileSync(C,`utf-8`));let N=process.env.NPM_CONFIG_USERCONFIG;if(N&&existsSync(N))S.push(readFileSync(N,`utf-8`));else{let n=js(homedir(),`.npmrc`);existsSync(n)&&S.push(readFileSync(n,`utf-8`))}return parseNpmrc(S.join(`
|
|
913
|
-
`).replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(n,S)=>process.env[S]??``))}function hasAnyAuthToken(n){return Object.keys(n.authTokens).length>0}function hasAnyCredential(n){return hasAnyAuthToken(n)||Object.keys(n.basicAuth).length>0}var
|
|
911
|
+
`);for(let N of[...S].sort()){let S=js(n,N);if(!existsSync(S)){C.update(`${N} absent\n`);continue}let F=[];walkFiles(S,N,F);for(let n of F){if(n.link!==void 0){C.update(`${n.rel} link:${n.link}\n`);continue}try{C.update(`${n.rel} ${hashFileStream(n.abs)}\n`)}catch{C.update(`${n.rel} unreadable\n`)}}}return C.digest(`hex`)}function outputUnits(n){let S=[];for(let C of HF){let N=js(n,C);if(!existsSync(N))continue;let F;try{F=readdirSync(N).filter(n=>n!==`node_modules`&&!isBuildInfo(n))}catch{continue}let I=F.every(n=>{try{return lstatSync(js(N,n)).isDirectory()}catch{return!1}});if(F.length===0||!I){S.push(C);continue}for(let n of[...F].sort())S.push(`${C}/${n}`)}return S}function signatureOf(n,S){let C=[];walkFiles(js(n,S),S,C);let N=createHash(`sha256`);for(let n of C){let S=`link`;if(n.link===void 0)try{let C=lstatSync(n.abs);S=`${C.size}:${C.mtimeMs}`}catch{S=`gone`}N.update(`${n.rel} ${S}\n`)}return N.digest(`hex`)}function snapshotOutputDirs(n){let S={};for(let n of HF)S[n]=null;for(let C of outputUnits(n))S[C]=signatureOf(n,C);return S}function modifiedOutputDirs(n,S){let C=[];for(let N of outputUnits(n))signatureOf(n,N)!==(S[N]??null)&&C.push(N);return C.sort()}function composeCacheKey(n){let S=createHash(`sha256`);S.update(`gjsify-build-cache/v3
|
|
912
|
+
`),S.update(`script:${n.script}\n`);for(let C of n.args??[])S.update(`arg:${C}\n`);for(let C of Object.keys(n.toolchain).sort())S.update(`tool:${C}@${n.toolchain[C]}\n`);S.update(`self:${n.ownHash}\n`);let C=n.depHashes instanceof Map?n.depHashes:new Map(Object.entries(n.depHashes));for(let n of[...C.keys()].sort())S.update(`dep:${n} ${C.get(n)}\n`);return S.digest(`hex`).slice(0,32)}function resolveToolchainVersions(n){let S={};for(let C of UF){let N=`none`;try{let S=readFileSync(js(n,`node_modules`,...C.split(`/`),`package.json`),`utf-8`),F=JSON.parse(S);typeof F.version==`string`&&(N=F.version)}catch{}C===`@gjsify/cli`&&N===`none`&&(N=readOwnCliVersion()??`none`),S[C]=N}return S}function readOwnCliVersion(){try{let n=Ps(fileURLToPath(import.meta.url));for(let S=0;S<4;S++){let S=js(n,`package.json`);if(existsSync(S)){let n=JSON.parse(readFileSync(S,`utf-8`));if(n.name===`@gjsify/cli`&&typeof n.version==`string`)return n.version}n=Ps(n)}}catch{}return null}function copyDirRecursive(n,S){mkdirSync(S,{recursive:!0});for(let C of readdirSync(n).sort()){let N=js(n,C),F=js(S,C),I=lstatSync(N);if(I.isSymbolicLink())replicateLinkSync(N,F);else if(I.isDirectory())copyDirRecursive(N,F);else if(I.isFile()){copyFileSync(N,F);try{chmodSync(F,I.mode&511)}catch{}}}}function buildCacheEntryDir(n,S,C){return js(n,sanitizePackageDirName(S),C)}function readCacheEntry(n,S,C){let N=js(WF(n,S,C),`manifest.json`);try{let F=JSON.parse(readFileSync(N,`utf-8`));if(F.version!==1||F.layout!==`v3`||F.package!==S||F.key!==C||!Array.isArray(F.dirs))return null;for(let N of F.dirs)if(!existsSync(js(WF(n,S,C),`outputs`,N)))return null;return F}catch{return null}}function storeCacheEntry(n,S,C,N,F){let I=WF(n,S.name,C),H=`${I}.tmp-${process.pid}`;try{rmSync(H,{recursive:!0,force:!0}),mkdirSync(js(H,`outputs`),{recursive:!0});for(let n of F)copyDirRecursive(js(S.location,n),js(H,`outputs`,n));let W=new Date().toISOString(),q={version:1,layout:`v3`,package:S.name,script:N,key:C,dirs:[...F],outputsHash:hashOutputDirs(S.location,F),createdAt:W,usedAt:W};return writeFileSync(js(H,`manifest.json`),JSON.stringify(q,null,2)),rmSync(I,{recursive:!0,force:!0}),renameSync(H,I),pruneCacheEntries(n,S.name),q}catch{try{rmSync(H,{recursive:!0,force:!0})}catch{}return null}}function restoreCacheEntry(n,S,C){let N=WF(n,S.name,C.key);try{if(C.dirs.length>0&&hashOutputDirs(S.location,C.dirs)===C.outputsHash)return touchManifestUsed(N,C),`up-to-date`;for(let n of C.dirs){let C=js(S.location,n);rmSync(C,{recursive:!0,force:!0}),copyDirRecursive(js(N,`outputs`,n),C)}return touchManifestUsed(N,C),C.dirs.length>0?`restored`:`up-to-date`}catch{return null}}function touchManifestUsed(n,S){try{S.usedAt=new Date().toISOString(),writeFileSync(js(n,`manifest.json`),JSON.stringify(S,null,2))}catch{}}function pruneCacheEntries(n,S,C=2){let N=js(n,sanitizePackageDirName(S)),F;try{F=readdirSync(N)}catch{return}let I=[];for(let n of F){if(n.includes(`.tmp-`)){try{rmSync(js(N,n),{recursive:!0,force:!0})}catch{}continue}let S=``;try{let C=JSON.parse(readFileSync(js(N,n,`manifest.json`),`utf-8`));S=C.usedAt??C.createdAt??``}catch{}I.push({name:n,stamp:S})}if(!(I.length<=C)){I.sort((n,S)=>n.stamp<S.stamp?1:n.stamp>S.stamp?-1:0);for(let n of I.slice(C))try{rmSync(js(N,n.name),{recursive:!0,force:!0})}catch{}}}function buildCacheOptedOut(n){return n.manifest.gjsify?.buildCache===!1}var HF,UF,isBuildInfo,WF,BuildCacheRunner,GF=__esmMin(()=>{ye(),No(),Vl(),Hs(),gn(),GM(),VF(),HF=[`lib`,`dist`,`dist-templates`],UF=[`@gjsify/cli`,`@gjsify/tsc`,`rolldown`,`typescript`],isBuildInfo=n=>n.endsWith(`.tsbuildinfo`),WF=buildCacheEntryDir,BuildCacheRunner=class{options;cacheRoot;graph;toolchain;ownHashes=new Map;closures=new Map;keys=new Map;log;constructor(n){this.options=n,this.cacheRoot=buildCacheRoot(n.root),this.graph=buildDependencyGraph(n.workspaces,{includeDev:!0,includePeer:!0,includeOptional:!0}),this.toolchain=resolveToolchainVersions(n.root),this.log=n.log??(n=>ve.error(n));for(let S of n.targets??[])if(this.graph.byName.has(S)){this.ownHashOf(S);for(let n of this.closureOf(S))this.ownHashOf(n)}}ownHashOf(n){let S=this.ownHashes.get(n);if(S===void 0){let C=this.graph.byName.get(n);S=C?hashPackageInputs(C.location):`unknown-workspace`,this.ownHashes.set(n,S)}return S}closureOf(n){let S=this.closures.get(n);if(S===void 0){let C=new Set,N=[...this.graph.edges.get(n)??[]];for(;N.length>0;){let S=N.shift();if(!(S===n||C.has(S))){C.add(S);for(let F of this.graph.edges.get(S)??[])!C.has(F)&&F!==n&&N.push(F)}}S=[...C].sort(),this.closures.set(n,S)}return S}keyFor(n){let S=this.keys.get(n.name);if(S===void 0){let C=new Map;for(let S of this.closureOf(n.name))C.set(S,this.ownHashOf(S));S=composeCacheKey({script:this.options.script,args:this.options.args,toolchain:this.toolchain,ownHash:this.ownHashOf(n.name),depHashes:C}),this.keys.set(n.name,S)}return S}tryRestore(n){try{if(buildCacheOptedOut(n))return this.log(`[gjsify build-cache] ${n.name}: opted out (gjsify.buildCache=false) — running uncached`),!1;let S=this.keyFor(n),C=readCacheEntry(this.cacheRoot,n.name,S);if(!C||C.script!==this.options.script)return this.log(`[gjsify build-cache] ${n.name}: miss ${S} — running "${this.options.script}"`),!1;let N=restoreCacheEntry(this.cacheRoot,n,C);if(N===null)return this.log(`[gjsify build-cache] ${n.name}: entry ${S} unrestorable — running "${this.options.script}"`),!1;let F=C.dirs.length>0?C.dirs.join(`, `):`no output dirs`;return this.log(`[gjsify build-cache] ${n.name}: hit ${S} — ${N===`restored`?`restored ${F}`:`${F} up to date`} (skipped "${this.options.script}")`),!0}catch(S){return this.log(`[gjsify build-cache] ${n.name}: cache error (${S.message}) — running uncached`),!1}}snapshotOutputs(n){try{return snapshotOutputDirs(n.location)}catch{return{}}}storeAfterSuccess(n,S){try{if(buildCacheOptedOut(n))return;let C=this.keyFor(n),N=modifiedOutputDirs(n.location,S);if(storeCacheEntry(this.cacheRoot,n,C,this.options.script,N)){let S=N.length>0?N.join(`, `):`no output dirs modified`;this.log(`[gjsify build-cache] ${n.name}: stored ${C} (${S})`)}}catch(S){this.log(`[gjsify build-cache] ${n.name}: store failed (${S.message}) — continuing`)}}}});function editDistance(n,S){if(n===S)return 0;if(n.length===0)return S.length;if(S.length===0)return n.length;let C=Array.from({length:S.length+1},(n,S)=>S),N=Array.from({length:S.length+1},()=>0);for(let F=1;F<=n.length;F++){N[0]=F;for(let I=1;I<=S.length;I++){let H=n[F-1]===S[I-1]?0:1;N[I]=Math.min(C[I]+1,N[I-1]+1,C[I-1]+H)}[C,N]=[N,C]}return C[S.length]}function suggestClosest(n,S){if(S.length===0)return;let C=n.toLowerCase(),N=Math.max(2,Math.floor(n.length/3)),F,I=1/0;for(let n of S){let S=editDistance(C,n.toLowerCase());S<I&&(I=S,F=n)}return F!==void 0&&I<=N?F:void 0}var KF=__esmMin(()=>{});function collectTransitiveClosure(n,S,C){let N=new Map;for(let n of S)N.set(n.name,n);let F=new Set,I=[],H=[n];for(;H.length>0;){let n=H.pop();if(F.has(n.name))continue;F.add(n.name),I.push(n);let S=n.manifest,W=[S.dependencies,C?S.devDependencies:void 0,S.optionalDependencies];for(let n of W)if(n)for(let[S,C]of Object.entries(n)){if(typeof C!=`string`||!C.startsWith(`workspace:`))continue;let n=N.get(S);n&&(F.has(n.name)||H.push(n))}}return I}async function runOne$1(n,S,C,N,F,I){if(I&&I.tryRestore(n))return;let H=I?.snapshotOutputs(n),W=N===`gjsify`?[`run`,S,...C]:[`run`,S,...C.length>0?[`--`,...C]:[]];F&&ve.error(`[${n.name}] $ ${N} ${W.join(` `)}`);let{code:q}=await spawnToCompletion(N,W,{completion:`exit`,cwd:n.location,color:!0});if(q!==0)throw Error(`${N} ${W.join(` `)} exited with code ${q}`);I&&H&&I.storeAfterSuccess(n,H)}function detectPackageManager(){if(isGjs()||usingSelfShim())return`gjsify`;let n=process.env.npm_config_user_agent??``;return n.startsWith(`yarn/`)?`yarn`:n.startsWith(`gjsify/`)?`gjsify`:`npm`}var qF,JF=__esmMin(()=>{ye(),_P(),GM(),qM(),GF(),th(),OF(),KF(),qF={command:`workspace <name> <script> [args..]`,description:"Run a workspace script. Both `workspace <name> <script>` and the yarn spelling `workspace <name> run <script>` work.",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}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip the script for a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run it and store the output dirs it modified. Also applies to the deps run via --with-dependencies. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}),handler:async n=>{let S=findWorkspaceRoot(process.cwd())??process.cwd(),C=discoverWorkspaces(S),N=C.find(S=>S.name===n.name);if(!N){let N=suggestClosest(n.name,C.map(n=>n.name)),F=N?` — did you mean "${N}"?`:``;return ve.error(`gjsify workspace: no workspace named "${n.name}"${F} (discovered ${C.length} workspace(s) under ${S})`),process.exit(1)}let F=detectPackageManager(),I=n.verbose===!0,H=n[`with-dependencies`]===!0,W=n[`continue-on-error`]===!0,q=n.script,Y=n.args??[];q===`run`&&Y.length>0&&([q,...Y]=Y);let X=N.manifest.scripts??{};if(typeof X[q]!=`string`){let S=suggestClosest(q,Object.keys(X));return ve.error(`gjsify workspace: workspace "${n.name}" has no script "${q}"`+(S?` — did you mean "${S}"?`:``)),process.exit(1)}let Z;Z=H?topologicalSort(buildDependencyGraph(collectTransitiveClosure(N,C,n[`include-dev`]===!0),{includeDev:n[`include-dev`]===!0})):[N];let te=n.cached??buildCacheEnabledByEnv()?new BuildCacheRunner({root:S,workspaces:C,script:q,args:Y,targets:Z.map(n=>n.name)}):void 0,ne=[];for(let n of Z){if(typeof(n.manifest.scripts??{})[q]!=`string`){I&&ve.error(`[${n.name}] (no "${q}" script — skipping)`);continue}try{await runOne$1(n,q,Y,F,I,te)}catch(S){let C=S instanceof Error?S:Error(String(S));if(ve.error(`[${n.name}] ${C.message}`),!W)return process.exit(1);ne.push({workspace:n.name,error:C})}}return ne.length>0?(ve.error(`gjsify workspace: ${ne.length} workspace(s) failed: ${ne.map(n=>n.workspace).join(`, `)}`),process.exit(1)):process.exit(0)}},__name$1(runOne$1,`runOne`)});async function runCheck(n,S){let C=[],N=detectPackageManager();if(N===`gjsify`&&readPackageJson$2(js(n.location,`package.json`))?.scripts?.check===void 0)return 0;let F=N===`gjsify`?[`run`,`check`]:[`run`,`check`,`--if-present`];try{let{code:I}=await spawnToCompletion(N,F,{completion:`exit`,cwd:n.location,stdio:S===null?`inherit`:`pipe`,onSpawn:n=>{let N=!process.stdout.isTTY;if(S!==null&&n.stdout&&n.stderr){let F=`[${S}] `;C.push(prefixLines(n.stdout,process.stdout,F,N)),C.push(prefixLines(n.stderr,process.stderr,F,N))}}});for(let n of C)n();return I??1}catch{for(let n of C)n();return 1}}var YF,XF=__esmMin(()=>{ye(),RF(),_P(),KM(),Hs(),Dm(),GM(),qM(),JF(),YF={command:`check`,description:"Run `npm run check` (TypeScript type-check) across the current workspace. In a workspace root: walks every package with a `check` script (excludes @girs/*; honours --include/--exclude). In a single package: runs the local `check` script directly. Symmetric peer of `gjsify format` / `lint` / `fix`. (Legacy system-dep `gjsify check` is now `gjsify system-check` — see #254.)",builder:n=>n.option(`include`,{description:`Only run in workspaces matching these glob patterns (repeatable).`,type:`string`,array:!0}).option(`exclude`,{description:`Skip workspaces matching these glob patterns (repeatable). Always excludes @girs/*.`,type:`string`,array:!0}).option(`parallel`,{description:`Run workspace checks in parallel (default). Use --no-parallel to run them sequentially with full per-workspace output.`,type:`boolean`,alias:`p`,default:!0}).option(`jobs`,{description:`Max parallel workers (when --parallel). Default: os.cpus().length.`,type:`number`,alias:`j`}).option(`verbose`,{description:`Log the per-workspace command before spawning.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=findWorkspaceRoot(S);if(C&&S!==C&&readPackageJson$2(js(S,`package.json`))?.scripts?.check){n.verbose&&ve.log(`[check] cwd=${S} → npm run check`);let{code:C}=await spawnToCompletion(detectPackageManager(),[`run`,`check`],{cwd:S,completion:`exit`});return process.exit(C??1)}if(!C)return ve.error("gjsify check: no workspace root found from cwd. Run inside a workspace (or a package within one) with `npm run check` defined."),process.exit(1);let N=discoverWorkspaces(C),F=[`@girs/*`,...n.exclude??[]],I=filterWorkspaces(N,{include:n.include,exclude:F}).filter(n=>n.manifest.scripts?.check!==void 0);if(I.length===0)return ve.error("gjsify check: no workspaces with a `check` script found."),process.exit(1);if(n.verbose&&ve.log(`[check] root=${C} workspaces=${I.length} parallel=${n.parallel?`yes`:`no`}`),!n.parallel){let S=0,C=0;for(let N of I){n.verbose&&ve.log(`[check] → ${N.name}`);let F=await runCheck(N,null);F!==0&&(C++,S===0&&(S=F))}return S!==0&&ve.error(`gjsify check: failures in ${C} workspace(s)`),process.exit(S)}let H=n.jobs??Math.max(1,cpus().length),W=[],q=0,Y=[];for(let n=0;n<H;n++)Y.push((async()=>{for(;;){let n=q++;if(n>=I.length)return;let S=I[n],C=await runCheck(S,S.name);C!==0&&W.push({name:S.name,code:C})}})());if(await Promise.all(Y),W.length>0){ve.error(`\ngjsify check: ${W.length} of ${I.length} workspace(s) failed:`);for(let n of W)ve.error(` ✗ ${n.name} (exit ${n.code})`);return process.exit(1)}n.verbose&&ve.log(`\ngjsify check: ${I.length} workspace(s) green.`),process.exit(0)}}});function manifestPath(){let n=Ps(fileURLToPath(import.meta.url)),S=[js(n,`..`,`..`,`showcases.json`),js(n,`..`,`showcases.json`)];return S.find(n=>existsSync(n))??S[0]}function discoverShowcases(){let n=manifestPath();if(!existsSync(n))return[];let S;try{S=JSON.parse(readFileSync(n,`utf-8`))}catch{return[]}if(!Array.isArray(S.showcases))return[];let C=S.showcases.map(n=>({name:n.name,packageName:n.package,category:n.category,description:n.description??``}));return C.sort((n,S)=>n.category.localeCompare(S.category)||n.name.localeCompare(S.name)),C}function findShowcase(n){return discoverShowcases().find(S=>S.name===n)}var ZF=__esmMin(()=>{Vl(),Hs(),gn()});function parseSpec(n){if(!n)throw Error(`dlx: empty package spec`);if(n.startsWith(`./`)||n.startsWith(`../`)||As(n)||existsSync(n))return{kind:`local`,path:Os(n)};let S=n,C,N=n.lastIndexOf(`@`);if(N>0&&(S=n.slice(0,N),C=n.slice(N+1)),!QF.test(S))throw Error(`dlx: invalid package name "${S}"`);return{kind:`registry`,name:S,version:C,spec:n}}var QF,$F=__esmMin(()=>{Vl(),Hs(),QF=/^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/});function resolveGjsEntry(n,S){let C=js(n,`package.json`);if(!existsSync(C))throw Error(`dlx: no package.json found at ${n}`);let N=JSON.parse(readFileSync(C,`utf-8`)),F=N.gjsify?.bin,I=N.gjsify?.main,H=N.main,W,q=null,Y=!1;if(S!==null){if(!F||!F[S]){let C=F?Object.keys(F).join(`, `):`(none)`;throw Error(`dlx: package "${N.name??n}" has no GJS bin named "${S}" — known: ${C}`)}W=F[S],q=S}else if(F&&Object.keys(F).length===1){let n=Object.keys(F)[0];W=F[n],q=n}else I?W=I:H&&(W=H,Y=!0);if(F&&Object.keys(F).length>1&&S===null){let S=Object.keys(F).join(`, `);throw Error(`dlx: package "${N.name??n}" defines multiple GJS bins — pass one of: ${S}`)}if(!W)throw Error(`dlx: package "${N.name??n}" has no GJS entry — set \`gjsify.main\` (or \`gjsify.bin\`) in its package.json`);let X=Os(n,W);if(!existsSync(X))throw Error(`dlx: GJS entry not found: ${X}`);return{bundlePath:X,binName:q,fromFallback:Y}}function resolveNodeEntry(n){let S=js(n,`package.json`);if(!existsSync(S))throw Error(`no package.json found at ${n}`);let C=JSON.parse(readFileSync(S,`utf-8`)),N=C.gjsify?.example?.node;if(N){let S=Os(n,N);if(!existsSync(S))throw Error(`declared node entry not found: ${S} (gjsify.example.node)`);return S}let F=C.gjsify?.main??(C.gjsify?.bin?Object.values(C.gjsify.bin)[0]:void 0)??C.main;if(!F)throw Error(`package "${C.name??n}" has no entry to derive a node bundle from — set \`gjsify.example.node\` to its \`--app node\` bundle path.`);let I=F.replace(/\.gjs\.(js|mjs|cjs)$/,``).replace(/\.(js|mjs|cjs)$/,``),H=[`${I}.node.mjs`,`${I}.node.js`,`${I}.node.cjs`];for(let S of H){let C=Os(n,S);if(existsSync(C))return C}throw Error(`package "${C.name??n}" has no \`--app node\` bundle — looked for ${H.join(`, `)}.\n Build one (e.g. \`gjsify build src/app.ts --app node --outfile dist/app.node.mjs\`) or set \`gjsify.example.node\` to its path.`)}var eI=__esmMin(()=>{Vl(),Hs()});function lexCompare(n,S){return n<S?-1:+(n>S)}function createCacheKey(n){let S=[...n.packages].sort(lexCompare),C=Object.entries(n.registries??{}).sort(([n],[S])=>lexCompare(n,S)),N=JSON.stringify([S,C]);return createHash(`sha256`).update(N).digest(`hex`)}function dlxCacheRoot(){let n=process.env.XDG_CACHE_HOME,S=js(n&&n.length>0?n:js(homedir(),`.cache`),`gjsify`,`dlx`);return mkdirSync(S,{recursive:!0}),S}function cacheDirFor(n){let S=js(dlxCacheRoot(),n);return mkdirSync(S,{recursive:!0}),S}function makePrepareDir(n){let S=js(n,`${Date.now().toString(16)}-${process.pid.toString(16)}`);return mkdirSync(S,{recursive:!0}),S}function getValidCachedPkg(n,S=nI){let C=js(n,`pkg`),N;try{N=lstatSync(C)}catch(n){if(n.code===`ENOENT`)return;throw n}if(!N.isSymbolicLink())return;let F;try{F=realpathSync(C)}catch{return}return Date.now()-N.mtime.getTime()<=S*tI?F:void 0}function symlinkSwap(n,S,C={}){let N=C.junctions??dirLinksAreJunctions(),F=js(n,`pkg`),I=js(n,`pkg.tmp-${Date.now().toString(16)}-${process.pid.toString(16)}`);linkDirSync(I,S);try{N&&rmSync(F,{force:!0,recursive:!1,maxRetries:10,retryDelay:100}),renameSync(I,F)}catch(n){let C=n.code;if(C===`EBUSY`||C===`EPERM`||C===`EEXIST`||C===`EACCES`){rmSync(I,{force:!0});try{return realpathSync(F)}catch{return realpathSync(S)}}throw n}return realpathSync(F)}function resolveInstalledPkgDir(n,S){return Os(n,`node_modules`,S)}var tI,nI,rI=__esmMin(()=>{No(),Vl(),Dm(),Hs(),VF(),tI=6e4,nI=1440*7});async function ensurePkgDir(n,S){if(n.kind===`local`)return{pkgDir:n.path,cachedPkgName:null};let C=[n.spec,...S.extraSpecs??[]],N=cacheDirFor(createCacheKey({packages:C})),F=S.cacheMaxAge>0?getValidCachedPkg(N,S.cacheMaxAge):void 0;if(F)return{pkgDir:resolveInstalledPkgDir(F,n.name),cachedPkgName:n.name};let I=makePrepareDir(N),H=makeProgressReporter({enabled:!S.verbose});return await installPackages({prefix:I,specs:C,verbose:S.verbose,registry:S.registry,lockfile:!0,frozen:S.frozen,progress:H}),{pkgDir:resolveInstalledPkgDir(symlinkSwap(N,I),n.name),cachedPkgName:n.name}}function splitBinAndArgs(n,S,C){if(!S)return{binName:null,extraArgs:C};let N=js(n,`package.json`);if(existsSync(N))try{let n=JSON.parse(readFileSync(N,`utf-8`)).gjsify?.bin;if(n&&Object.prototype.hasOwnProperty.call(n,S))return{binName:S,extraArgs:C}}catch{}return{binName:null,extraArgs:[S,...C]}}var iI,aI=__esmMin(()=>{ye(),yP(),$F(),eI(),wP(),rI(),bF(),Vl(),Hs(),iI={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,"parse-positional-numbers":!1}).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 S=parseSpec(n.spec),C=n.reinstall?0:n[`cache-max-age`],{pkgDir:N,cachedPkgName:F}=await ensurePkgDir(S,{verbose:n.verbose,registry:n.registry,cacheMaxAge:C,frozen:n.frozen}),I=[...n.extraArgs??[],...doubleDashArgs(n)],{binName:H,extraArgs:W}=splitBinAndArgs(N,n.binOrArg,I),q=resolveGjsEntry(N,H);q.fromFallback&&ve.warn(`[gjsify dlx] package "${F??S.kind}" declares no \`gjsify.main\` — falling back to package.json#main. Add \`gjsify.main\` to silence.`),await runGjsBundle(q.bundlePath,W,{completion:`exit`,exitOnSuccess:!0})}}});async function loadNpmrc(n){let S=[],C=js(n,`.npmrc`);existsSync(C)&&S.push(readFileSync(C,`utf-8`));let N=process.env.NPM_CONFIG_USERCONFIG;if(N&&existsSync(N))S.push(readFileSync(N,`utf-8`));else{let n=js(homedir(),`.npmrc`);existsSync(n)&&S.push(readFileSync(n,`utf-8`))}return parseNpmrc(S.join(`
|
|
913
|
+
`).replace(/\$\{([A-Z_][A-Z0-9_]*)\}/gi,(n,S)=>process.env[S]??``))}function hasAnyAuthToken(n){return Object.keys(n.authTokens).length>0}function hasAnyCredential(n){return hasAnyAuthToken(n)||Object.keys(n.basicAuth).length>0}var oI=__esmMin(()=>{Vl(),Dm(),Hs(),ep()});function readCliVersion(){let n=cliVersion();return n===`unknown`?void 0:n}function runningAs(n){return n?`[gjsify ${n}] `:``}async function resolveShowcaseDir(n,S,C=[]){let N=resolveLocalShowcaseDir(n);if(N)return N;let{pkgDir:F}=await ensurePkgDir(parseSpec(S?`${n.packageName}@${S}`:n.packageName),{verbose:!1,cacheMaxAge:1440*7,frozen:!1,extraSpecs:C});return F}function resolveLocalShowcaseDir(n){try{let S=createRequire(import.meta.url).resolve(`${n.packageName}/package.json`);if(existsSync(S))return Ps(S)}catch{}return null}function gtkRuntimeSpecs(n){let S=`${process.platform}-${process.arch}`;if(![`win32-x64`,`darwin-arm64`,`darwin-x64`].includes(S))return[];let C=`@gjsify/gtk-runtime-${S}`;return[n?`${C}@${n}`:C]}async function preflightDeclaredRuntimes(n,S){try{return declaredRuntimesFromPackument(await fetchPackument(n.packageName,{npmrc:await loadNpmrc(process.cwd()),fullMetadata:!0}),S)}catch{return}}function declaredRuntimesFromPackument(n,S){let C=S??n[`dist-tags`]?.latest,N=C?n.versions?.[C]:void 0;if(N)return readDeclaredRuntimes(N)}async function runShowcaseOnRuntime(n,S,C){if(resolveLocalShowcaseDir(n)===null){let N=await preflightDeclaredRuntimes(n,C);if(N!==void 0){let C=checkRuntimeSupported(S,N,n.name);if(!C.ok)return ve.error(C.message),process.exit(1)}}let N;try{N=await resolveShowcaseDir(n,C,[C?`@gjsify/node-gi@${C}`:`@gjsify/node-gi`,...gtkRuntimeSpecs(C)])}catch(S){return ve.error(`Could not resolve showcase "${n.name}": ${S.message}`),process.exit(1)}let F={};try{F=JSON.parse(readFileSync(`${N}/package.json`,`utf-8`))}catch{}let I=checkRuntimeSupported(S,readDeclaredRuntimes(F),n.name);if(!I.ok)return ve.error(I.message),process.exit(1);let H;try{H=resolveNodeEntry(N)}catch(N){let I=typeof F.name==`string`?`${F.name}@${C??`?`}`:n.packageName;return ve.error(`Cannot run showcase "${n.name}" on ${S}: ${N.message}\n\n ${I} declares --runtime ${S} but ships no \`--app node\` bundle, so that\n version of the showcase cannot run there. You are running gjsify ${C??`(unknown)`},\n and \`showcase\` pins the showcase to the CLI's own version.\n\n ${sI}\n\n Or run it on GJS, which every showcase ships: gjsify showcase ${n.name} --runtime gjs`),process.exit(1)}ve.log(`Running showcase: ${n.name} ${runningAs(C)}on ${S} (${H})\n`);try{await runRuntimeBundle(S,H,[],{completion:`exit`,exitOnSuccess:!0})}catch(n){return ve.error(`${n.message}\n\n The showcase and the \`@gjsify/node-gi\` bridge it needs are both installed by THIS CLI\n (gjsify ${C??`(unknown)`}) into its own cache, so a missing bridge points at the CLI\n rather than at anything in your project.\n\n ${sI}`),process.exit(1)}}var sI,cI,lI=__esmMin(()=>{ye(),ZF(),dN(),gs(),Hs(),Vl(),aI(),ep(),oI(),$F(),np(),eI(),xP(),Ah(),sI=`A package runner reuses a CACHED copy of an unpinned bin. Force the current one:
|
|
914
914
|
npx @gjsify/cli@latest showcase <name>
|
|
915
915
|
bunx @gjsify/cli@latest showcase <name>
|
|
916
|
-
deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,
|
|
916
|
+
deno run -A --reload --min-dep-age 0 npm:@gjsify/cli@latest showcase <name>`,cI={command:`showcase [name]`,description:`List or run curated gjsify showcase applications.`,builder:n=>n.positional(`name`,{description:`Showcase name to run (omit to list all)`,type:`string`}).option(`json`,{description:`Output as JSON`,type:`boolean`,default:!1}).option(`list`,{description:`List available showcases`,type:`boolean`,default:!1}).option(`runtime`,{type:`string`,choices:Oh,defaultDescription:`gjs when gjs is installed, else the host runtime`,description:"Runtime to run the showcase on: gjs | node | bun | deno (default: gjs when installed, else the host runtime). node/bun/deno run its `--app node` bundle."}),handler:async n=>{if(!n.name||n.list){let S=discoverShowcases();if(n.json){ve.log(JSON.stringify(S,null,2));return}if(S.length===0){ve.log("No showcases found. The CLI ships a curated list in `showcases.json`; if it is missing the CLI install is incomplete.");return}let C=new Map;for(let n of S){let S=C.get(n.category)??[];S.push(n),C.set(n.category,S)}ve.log(`Available gjsify showcases:
|
|
917
917
|
`);for(let[n,S]of C){ve.log(` ${n.toUpperCase()}:`);let C=Math.max(...S.map(n=>n.name.length));for(let n of S){let S=` `.repeat(C-n.name.length+2),N=n.description?`${S}${n.description}`:``;ve.log(` ${n.name}${N}`)}ve.log(``)}ve.log(`Run a showcase: gjsify showcase <name>`);return}let S=findShowcase(n.name);if(!S)return ve.error(`Unknown showcase: "${n.name}"`),ve.error(`Run "gjsify showcase" to list available showcases.`),process.exit(1);let C=n.runtime??defaultExampleRuntime();if(!isExampleRuntime(C))return ve.error(`Unknown --runtime "${C}" (expected: ${Oh.join(`, `)}).`),process.exit(1);if(requiresGjsSystemDeps(C)){let n=runMinimalChecks().filter(n=>!n.found&&n.severity===`required`);if(n.length>0){ve.error(`Missing system dependencies:
|
|
918
|
-
`);for(let S of n)ve.error(` ✗ ${S.name}`);let S=buildInstallCommand(detectPackageManager$1(),n);return S&&ve.error(`\nInstall with:\n ${S}`),process.exit(1)}}let N=readCliVersion();if(C!==`gjs`){await runShowcaseOnRuntime(S,C,N);return}let F=N?`${S.packageName}@${N}`:S.packageName;ve.log(`Running showcase: ${S.name} ${runningAs(N)}(via gjsify dlx ${F})\n`);try{let{runCli:n}=await Promise.resolve().then(()=>(
|
|
919
|
-
`),F(Error(CI));return}C.name===`up`||C.name===`k`?(I=(I-1+S.length)%S.length,render(S,I,!1)):C.name===`down`||C.name===`j`?(I=(I+1)%S.length,render(S,I,!1)):(C.name===`return`||C.name===`enter`)&&(cleanup(),N(S[I].value))}};on.on(`keypress`,onKeypress)})}function promptTemplate(n){return n.length===0?Promise.reject(Error(`No templates available.`)):promptChoice(`Select a template`,n.map(n=>({value:n,label:n.name,description:n.description})))}function promptRuntime(n,S){return promptChoice(`Select a runtime`,n.map(n=>({value:n,label:n,description:hI[n]??``})),n.indexOf(S))}function promptPackageManager(n,S){return promptChoice(`Select a package manager`,n.map(n=>({value:n,label:n,description:``})),n.indexOf(S))}async function settle(n,S){switch(n.kind){case`value`:return n.value;case`auto`:return ve.error(n.notice),n.value;case`prompt`:try{return await S(n.choices,n.initial)}catch(n){if(!isCancelled(n))throw n;ve.error(`Cancelled.`);return}case`error`:ve.error(`Error: ${n.message}`);return}}async function promptSetup(n){let{offered:S,install:C,interactive:N}=n,F=await settle(selectRuntime({flag:n.runtime,offered:S,manager:n.packageManager,interactive:N}),(n,S)=>promptRuntime(n,S));if(F===void 0)return;let I=await settle(selectPackageManager({flag:n.packageManager,runtime:F,install:C,interactive:N}),(n,S)=>promptPackageManager(n,S));if(I!==void 0)return{runtime:F,packageManager:I}}var SI,CI,wI=__esmMin(()=>{ye(),sn(),Ml(),gI(),_I(),SI={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},CI=`Cancelled by user`}),TI,EI=__esmMin(()=>{ye(),xI(),wI(),TI={command:`create [project-name]`,description:`Scaffold a new Gjsify project in a new directory.`,builder:n=>{let S=discoverTemplates(),C=S.map(n=>n.name),N=[...new Set(S.flatMap(n=>supportedRuntimes(n)))];return n.positional(`project-name`,{describe:`Name of the project directory to create`,type:`string`,default:`my-gjs-app`}).option(`template`,{alias:`t`,describe:`Template to scaffold from`,type:`string`,choices:C.length>0?C:void 0}).option(`runtime`,{alias:`r`,describe:`Runtime to set the project up for. Decides which package managers are offered and which start script the next steps name.`,type:`string`,choices:N.length>0?N:void 0}).option(`force`,{alias:`f`,describe:`Scaffold into a non-empty directory`,type:`boolean`,default:!1}).option(`install`,{describe:`Install dependencies after scaffolding`,type:`boolean`,default:!1}).option(`package-manager`,{alias:`p`,describe:"Package manager to install with, and to name in the printed next steps. Must be one the chosen runtime can install for. `gjsify` is the only one that works on a host with no Node.js.",type:`string`,choices:dI})},handler:async n=>{let S=!!process.stdin.isTTY,C=discoverTemplates(),N=n.template;if(!N){if(!S){let n=C.map(n=>n.name).join(`, `);return ve.error(`Error: --template is required in non-interactive mode. Available templates: ${n||`(none)`}`),process.exit(1)}let n=await promptTemplate(C).catch(n=>{if(!isCancelled(n))throw n;ve.error(`Cancelled.`)});if(n===void 0)return process.exit(1);N=n.name}let F=C.find(n=>n.name===N),I=await promptSetup({offered:F?supportedRuntimes(F):[],runtime:n.runtime,packageManager:n[`package-manager`],install:n.install,interactive:S});if(I===void 0)return process.exit(1);await createProject({projectName:n[`project-name`],template:N,runtime:I.runtime,force:n.force,install:n.install,packageManager:I.packageManager})}}});function defaultTargetFor(n){let S=Fs(n,Is(n));return Os(Ps(n),S)}var DI,OI,kI=__esmMin(()=>{ye(),Dh(),Cl(),Hs(),Ac(),DI=promisify(execFile),OI={command:`gresource <xml>`,description:"Compile a GResource XML descriptor into a binary .gresource bundle (wraps `glib-compile-resources`).",builder:n=>n.positional(`xml`,{description:`Path to the .gresource.xml descriptor`,type:`string`,normalize:!0,demandOption:!0}).option(`sourcedir`,{description:`Directory containing the resource files referenced by <xml>`,type:`string`,normalize:!0}).option(`target`,{alias:`t`,description:`Output .gresource file (default: <xml-without-.xml> next to <xml>)`,type:`string`,normalize:!0}).option(`verbose`,{description:`Print the underlying glib-compile-resources invocation`,type:`boolean`,default:!1}),handler:async n=>{let S=Os(n.xml),C=n.target?Os(n.target):defaultTargetFor(S),N=[`--sourcedir=${n.sourcedir?Os(n.sourcedir):Ps(S)}`,`--target=${C}`,S];n.verbose&&ve.log(`[gjsify gresource] glib-compile-resources ${N.join(` `)}`),await mkdir$1(Ps(C),{recursive:!0});try{let{stdout:S,stderr:F}=await DI(`glib-compile-resources`,N);S&&process.stdout.write(S),F&&process.stderr.write(F),n.verbose&&ve.log(`[gjsify gresource] wrote ${C}`)}catch(n){let S=n;S?.code===`ENOENT`?ve.error(`[gjsify gresource] glib-compile-resources not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(S?.stderr&&process.stderr.write(S.stderr),ve.error(`[gjsify gresource] glib-compile-resources failed${S?.code===void 0?``:` (exit ${S.code})`}`)),process.exitCode=typeof S?.code==`number`?S.code:1}}}});function mergeCatalogues(n){let S=n.template,C=new Set;for(let{locale:S}of n.catalogues){if(C.has(S))throw Error(`mergeCatalogues: two catalogues both claim locale "${S}". msgfmt APPENDS each --locale, so the chain would emit a duplicate key (desktop-file-validate: "multiple keys named Name[${S}]"; appstreamcli: "tag-duplicated") from two exit-0 calls. Merge them into one .po first (msgcat --use-first) and pass that.`);C.add(S)}for(let[C,N]of n.catalogues.entries()){let F=js(n.workDir,`${C}${n.extension}`),I=[n.mode,`--template=${S}`,`--locale=${N.locale}`,`--output-file=${F}`,N.po];n.onCall?.(I),execFileSync(`msgfmt`,I,{stdio:`pipe`}),S=F}return S}var AI=__esmMin(()=>{Dh(),Hs()});async function listLanguages(n){return(await readdir$1(n)).filter(n=>n.endsWith(`.po`)&&!n.startsWith(`.`)).map(n=>n.slice(0,-3)).sort()}function stripXmlComments(n){return n.replace(/<!--[\s\S]*?-->/g,``)}async function ensureDir(n){await mkdir$1(n,{recursive:!0})}async function fileExists(n){try{return await stat$1(n),!0}catch{return!1}}async function compileMerged(n){let S=await listLanguages(n.poDir);if(S.length===0){ve.warn(`[gjsify gettext] no .po files found in ${n.poDir}`);return}let C=js(n.outDir,n.filename);await ensureDir(n.outDir);let N=await mkdtemp$1(js(tmpdir(),`gjsify-gettext-`));try{let F=await readFile$1(mergeCatalogues({mode:`--${n.format}`,template:n.template,extension:`-${Fs(n.template).replace(/\.in$/,``)}`,catalogues:S.map(S=>({locale:S,po:js(n.poDir,`${S}.po`)})),workDir:N,onCall:n.verbose?n=>ve.log(`[gjsify gettext] msgfmt ${n.join(` `)}`):void 0}),`utf-8`);await writeFile$1(C,n.removeXmlComments&&n.format===`xml`?stripXmlComments(F):F)}finally{await rm$1(N,{recursive:!0,force:!0})}n.verbose&&ve.log(`[gjsify gettext] merged ${S.length} language(s) into ${C}`)}async function compileCatalogues(n){let S=await listLanguages(n.poDir);if(S.length===0){ve.warn(`[gjsify gettext] no .po files found in ${n.poDir}`);return}for(let C of S){let S=js(n.outDir,C,`LC_MESSAGES`);await ensureDir(S);let N=[`--output-file=${js(S,n.filename)}`,js(n.poDir,`${C}.po`)];n.verbose&&ve.log(`[gjsify gettext] msgfmt ${N.join(` `)}`),await jI(`msgfmt`,N)}n.verbose&&ve.log(`[gjsify gettext] compiled ${S.length} language(s) into ${n.outDir}`)}function defaultFilename(n,S,C){switch(S){case`mo`:return`${n}.mo`;case`desktop`:return`${n}.desktop`;case`xml`:return C?Fs(C.replace(/\.in$/,``)):`${n}.xml`}}var jI,MI,NI=__esmMin(()=>{ye(),Dh(),Cl(),Dm(),Hs(),Ac(),AI(),jI=promisify(execFile),MI={command:`gettext <poDir> <outDir>`,description:`Compile gettext .po files to .mo (per-language locale tree), or merge every catalogue into a .desktop / AppStream template via msgfmt --desktop / --xml.`,builder:n=>n.positional(`poDir`,{description:`Directory containing <lang>.po files`,type:`string`,normalize:!0,demandOption:!0}).positional(`outDir`,{description:`Output directory (locale tree for --format=mo, plain dir for xml/desktop)`,type:`string`,normalize:!0,demandOption:!0}).option(`domain`,{description:"Text domain / application ID (e.g. `org.pixelrpg.maker`)",type:`string`,normalize:!0,demandOption:!0}).option(`format`,{description:`Output format`,type:`string`,choices:[`mo`,`xml`,`desktop`],default:`mo`}).option(`template`,{description:"Required for --format=xml|desktop: the file msgfmt substitutes into. Its SUFFIX matters — msgfmt --xml finds its ITS rules by filename pattern, so an AppStream template must be named `*.metainfo.xml[.in]`.",type:`string`,normalize:!0}).option(`metainfo`,{description:`Deprecated alias for --template.`,type:`string`,normalize:!0,hidden:!0}).option(`filename`,{description:`Override the output filename (defaults to <domain>.<ext>)`,type:`string`,normalize:!0}).option(`remove-xml-comments`,{description:`For --format=xml: strip XML comments from the compiled output`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print each msgfmt invocation`,type:`boolean`,default:!1}),handler:async n=>{let S=Os(n.poDir),C=Os(n.outDir),N=n.domain,F=n.format??`mo`,I=n.template??n.metainfo,H=I?Os(I):void 0,W=n.filename??defaultFilename(N,F,H),q=!!n.verbose,Y=!!n[`remove-xml-comments`];if(!await fileExists(S)){ve.error(`[gjsify gettext] PO directory does not exist: ${S}`),process.exitCode=1;return}if(F!==`mo`&&H===void 0){ve.error(`[gjsify gettext] --format=${F} needs a template to substitute into: pass \`--template <file>\`. msgfmt has no way to produce this format from .po files alone.`+(F===`xml`?" Name it `*.metainfo.xml[.in]` — msgfmt --xml finds its ITS rules by filename pattern.":``)),process.exitCode=1;return}try{F===`mo`?await compileCatalogues({poDir:S,outDir:C,filename:W,verbose:q}):await compileMerged({poDir:S,outDir:C,format:F,template:H,filename:W,removeXmlComments:Y,verbose:q})}catch(n){let S=n;S?.code===`ENOENT`?ve.error(`[gjsify gettext] msgfmt not found. Install it via your distro (package: gettext).`):(S?.stderr&&process.stderr.write(S.stderr),ve.error(`[gjsify gettext] msgfmt failed${S?.code===void 0?``:` (exit ${S.code})`}`)),process.exitCode=typeof S?.code==`number`?S.code:1}}}}),PI,FI,II=__esmMin(()=>{ye(),Dh(),Cl(),Hs(),Ac(),PI=promisify(execFile),FI={command:`gsettings <schemadir>`,description:"Compile GSettings schema XML files into a binary gschemas.compiled (wraps `glib-compile-schemas`).",builder:n=>n.positional(`schemadir`,{description:`Directory containing *.gschema.xml descriptors`,type:`string`,normalize:!0,demandOption:!0}).option(`targetdir`,{alias:`t`,description:`Directory to write gschemas.compiled (default: <schemadir>)`,type:`string`,normalize:!0}).option(`strict`,{description:`Abort on any schema warning (passes --strict to glib-compile-schemas)`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print the underlying glib-compile-schemas invocation`,type:`boolean`,default:!1}),handler:async n=>{let S=Os(n.schemadir),C=n.targetdir?Os(n.targetdir):S,N=[];n.strict&&N.push(`--strict`),N.push(`--targetdir=${C}`),N.push(S),n.verbose&&ve.log(`[gjsify gsettings] glib-compile-schemas ${N.join(` `)}`),await mkdir$1(C,{recursive:!0});try{let{stdout:S,stderr:F}=await PI(`glib-compile-schemas`,N);S&&process.stdout.write(S),F&&process.stderr.write(F),n.verbose&&ve.log(`[gjsify gsettings] wrote ${C}/gschemas.compiled`)}catch(n){let S=n;S?.code===`ENOENT`?ve.error(`[gjsify gsettings] glib-compile-schemas not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(S?.stderr&&process.stderr.write(S.stderr),ve.error(`[gjsify gsettings] glib-compile-schemas failed${S?.code===void 0?``:` (exit ${S.code})`}`)),process.exitCode=typeof S?.code==`number`?S.code:1}}}});function readPackageJson(n){let S=Os(n,`package.json`),C;try{C=readFileSync(S,`utf-8`)}catch{throw Error(`gjsify flatpak: no package.json found at ${S}`)}try{return JSON.parse(C)}catch(n){throw Error(`gjsify flatpak: package.json at ${S} is not valid JSON: ${n.message}`)}}function looksLikeAppId(n){return typeof n==`string`&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*){2,}$/.test(n)}function defaultCiContainer(n,S){return`ghcr.io/flathub-infra/flatpak-github-actions:${`${n}-${S}`}`}var LI=__esmMin(()=>{Vl(),Hs()});function resolveRuntime(n,S){let C=S.runtime??n?.runtime??`gnome`;if(C!==`gnome`&&C!==`freedesktop`)throw Error(`gjsify flatpak: unknown runtime "${C}" (expected "gnome" or "freedesktop")`);let N=S.runtimeVersion??n?.runtimeVersion??(C===`gnome`?`50`:`24.08`);return C===`gnome`?{runtime:C,runtimeId:`org.gnome.Platform`,sdk:`org.gnome.Sdk`,runtimeVersion:N}:{runtime:C,runtimeId:`org.freedesktop.Platform`,sdk:`org.freedesktop.Sdk`,runtimeVersion:N}}function deriveAppendPath(n){let S=[];for(let C of n){let n=/^org\.freedesktop\.Sdk\.Extension\.([A-Za-z0-9-]+)$/.exec(C);n&&S.push(`/usr/lib/sdk/${n[1]}/bin`)}return S.push(`/app/bin`),S}var RI,zI,BI=__esmMin(()=>{RI=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],zI=[]});function pickFlatpakBuildKeys(n,S){let C=n??{},N={},F=[];for(let n of HI){let I=C[n];if(I!==void 0){N[n]=I;continue}let H=S[n];H!==void 0&&F.push(n),N[n]=H}return{values:N,fromLegacy:F}}function resolveShipFlatpakSettings(n){let S=n.ship.flatpak??{},{values:C,fromLegacy:N}=pickFlatpakBuildKeys(S,n.flatpak),F=resolveRuntime(C,{}),I=C.sdkExtensions??[],{appendPath:H,finishArgs:W,cleanup:q}=C;return{settings:{runtime:F.runtimeId,runtimeVersion:F.runtimeVersion,sdk:F.sdk,branch:S.branch??`stable`,sdkExtensions:[...I],appendPath:H??(I.length>0?deriveAppendPath(I):[]),finishArgs:W??(n.kind===`cli`?zI:RI),cleanup:q??[]},warnings:N.length===0?[]:[deprecationWarning(N)]}}function deprecationWarning(n){let S=n.map(n=>`gjsify.flatpak.${n}`).join(`, `),C=n.map(n=>`gjsify.ship.flatpak.${n}`).join(`, `);return`DEPRECATION: ${S} ${n.length>1?`are`:`is`} read by \`gjsify ship\` for compatibility and will be removed in ${VI}. Move ${n.length>1?`them`:`it`} to ${C} — both spellings resolve until then, and \`gjsify.ship.flatpak\` wins where both are set. The app METADATA in \`gjsify.flatpak\` (name, summary, developer, categories, licence) is NOT deprecated: both blocks describe the same application and either may carry it (ADR 0024 § 8).`}var VI,HI,WI=__esmMin(()=>{BI(),VI=`1.0.0`,HI=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return GI}function validateAppMetadata(n){let S=n.metadata,C=n.configKey,N=[];return(!S.developer?.id||!S.developer?.name)&&N.push({field:`${C}.developer`,hint:`Set \`${C}.developer = { "id": "io.github.you", "name": "Your Name" }\` in package.json. The id is reverse-DNS.`}),S.summary||N.push({field:`${C}.summary`,hint:`One-line app summary, ≤80 chars, no trailing period. Example: "Learn 6502 assembly language".`}),S.description||N.push({field:`${C}.description`,hint:`Plain text (split on blank lines) or DescriptionBlock[] for rich content with bullet lists + translator hints.`}),S.license?.project||N.push({field:`${C}.license.project`,hint:`SPDX identifier of the project license, e.g. "MIT", "GPL-3.0-or-later".`}),S.homepageUrl||N.push({field:`${C}.homepageUrl`,hint:`Required by Flathub. Example: "https://github.com/you/your-repo".`}),N}function renderMetainfoApp$1(n){return renderMetainfo(n,`desktop-application`)}function renderMetainfoCli$1(n){return renderMetainfo(n,`console-application`)}function renderDesktopEntry(n){let S=n.metadata,C=(S.categories??[`Utility`]).join(`;`)+`;`,N=S.keywords?.length?`Keywords=${S.keywords.join(`;`)};\n`:``,F=S.provides?.mimetypes??[],I=F.length?`MimeType=${F.join(`;`)};\n`:``;return substitute(loadDesktopTemplate(),{NAME:n.name,SUMMARY:S.summary??n.name,COMMAND:`${n.command}${execFieldCode(F)}`,APP_ID:n.appId,CATEGORIES_LINE:C,KEYWORDS_LINE:N,MIMETYPES_LINE:I})}function execFieldCode(n){return n.some(n=>n.startsWith(`x-scheme-handler/`))?` %u`:n.length>0?` %f`:``}function renderMetainfo(n,S){let C=n.metadata,N=n.copyrightYear??new Date().getFullYear(),F=C.developer?.name??``,I=[];I.push(`<?xml version="1.0" encoding="UTF-8"?>`),I.push(`<!-- Copyright ${N} ${escapeXml(F)} -->`),I.push(`<component type="${S}">`),I.push(` <id>${escapeXml(n.appId)}</id>`),I.push(` <metadata_license>${escapeXml(C.license?.metadata??`CC0-1.0`)}</metadata_license>`),I.push(` <project_license>${escapeXml(C.license?.project??``)}</project_license>`),I.push(` <name>${escapeXml(n.name)}</name>`),pushTranslatorHint(I,C.summaryTranslatorHint,` `),I.push(` <summary>${escapeXml(C.summary??n.name)}</summary>`),C.iconRemote&&I.push(` <icon type="remote">${escapeXml(C.iconRemote)}</icon>`),I.push(` <description>`);for(let n of renderDescriptionBlocks(C.description??``,` `))I.push(n);if(I.push(` </description>`),C.developer?.id&&C.developer?.name){I.push(` <developer id="${escapeXml(C.developer.id)}">`);let n=C.developer.nameTranslatable===!0?``:` translate="no"`;I.push(` <name${n}>${escapeXml(C.developer.name)}</name>`),C.developer.email&&I.push(` <email>${escapeXml(C.developer.email)}</email>`),I.push(` </developer>`)}S===`desktop-application`&&I.push(` <launchable type="desktop-id">${escapeXml(n.appId)}.desktop</launchable>`),C.screenshots?.length&&(I.push(` <screenshots>`),C.screenshots.forEach((n,S)=>{let C=n.type??(S===0?`default`:void 0),N=C?` type="${escapeXml(C)}"`:``,F=n.environment?` environment="${escapeXml(n.environment)}"`:``;I.push(` <screenshot${N}${F}>`),I.push(` <image>${escapeXml(n.url)}</image>`),n.caption&&(pushTranslatorHint(I,n.captionTranslatorHint,` `),I.push(` <caption>${escapeXml(n.caption)}</caption>`)),I.push(` </screenshot>`)}),I.push(` </screenshots>`)),C.homepageUrl&&I.push(` <url type="homepage">${escapeXml(C.homepageUrl)}</url>`),C.bugtrackerUrl&&I.push(` <url type="bugtracker">${escapeXml(C.bugtrackerUrl)}</url>`),C.vcsBrowserUrl&&I.push(` <url type="vcs-browser">${escapeXml(C.vcsBrowserUrl)}</url>`),C.donationUrl&&I.push(` <url type="donation">${escapeXml(C.donationUrl)}</url>`),C.translateUrl&&I.push(` <url type="translate">${escapeXml(C.translateUrl)}</url>`);let H=normaliseContentRating(C.contentRating);if(H.attributes&&Object.keys(H.attributes).length>0){I.push(` <content_rating type="${escapeXml(H.type)}">`);for(let[n,S]of Object.entries(H.attributes))I.push(` <content_attribute id="${escapeXml(n)}">${escapeXml(S)}</content_attribute>`);I.push(` </content_rating>`)}else I.push(` <content_rating type="${escapeXml(H.type)}" />`);if(C.releases?.length){I.push(` <releases>`);for(let n of C.releases)if(n.description===void 0)I.push(` <release version="${escapeXml(n.version)}" date="${escapeXml(n.date)}" />`);else{I.push(` <release version="${escapeXml(n.version)}" date="${escapeXml(n.date)}">`),I.push(` <description>`);for(let S of renderDescriptionBlocks(n.description,` `))I.push(S);I.push(` </description>`),I.push(` </release>`)}I.push(` </releases>`)}if(C.categories?.length){I.push(` <categories>`);for(let n of C.categories)I.push(` <category>${escapeXml(n)}</category>`);I.push(` </categories>`)}if(C.keywords?.length){I.push(` <keywords>`);for(let n of C.keywords)I.push(` <keyword>${escapeXml(n)}</keyword>`);I.push(` </keywords>`)}if(S===`desktop-application`&&C.branding&&(I.push(` <branding>`),I.push(` <color type="primary" scheme_preference="light">${escapeXml(C.branding.accentLight)}</color>`),I.push(` <color type="primary" scheme_preference="dark">${escapeXml(C.branding.accentDark)}</color>`),I.push(` </branding>`)),C.kudos?.length){I.push(` <kudos>`);for(let n of C.kudos)I.push(` <kudo>${escapeXml(n)}</kudo>`);I.push(` </kudos>`)}let W=C.provides?.binaries??[n.command],q=C.provides?.mimetypes??[],Y=C.provides?.dbus??[];if(W.length||q.length||Y.length){I.push(` <provides>`);for(let n of W)I.push(` <binary>${escapeXml(n)}</binary>`);for(let n of q)I.push(` <mediatype>${escapeXml(n)}</mediatype>`);for(let n of Y)I.push(` <dbus type="${escapeXml(n.type)}">${escapeXml(n.id)}</dbus>`);I.push(` </provides>`)}if(C.supports?.controls?.length||C.supports?.internet){I.push(` <supports>`);for(let n of C.supports.controls??[])I.push(` <control>${escapeXml(n)}</control>`);C.supports.internet&&I.push(` <internet>${escapeXml(C.supports.internet)}</internet>`),I.push(` </supports>`)}if(C.requires?.displayLengthMin||C.requires?.controls?.length||C.requires?.internet){I.push(` <requires>`),C.requires.displayLengthMin&&I.push(` <display_length compare="ge">${C.requires.displayLengthMin}</display_length>`);for(let n of C.requires.controls??[])I.push(` <control>${escapeXml(n)}</control>`);C.requires.internet&&I.push(` <internet>${escapeXml(C.requires.internet)}</internet>`),I.push(` </requires>`)}if(C.recommends?.displayLengthMin||C.recommends?.controls?.length){I.push(` <recommends>`),C.recommends.displayLengthMin&&I.push(` <display_length compare="ge">${C.recommends.displayLengthMin}</display_length>`);for(let n of C.recommends.controls??[])I.push(` <control>${escapeXml(n)}</control>`);I.push(` </recommends>`)}return I.push(`</component>`),I.join(`
|
|
918
|
+
`);for(let S of n)ve.error(` ✗ ${S.name}`);let S=buildInstallCommand(detectPackageManager$1(),n);return S&&ve.error(`\nInstall with:\n ${S}`),process.exit(1)}}let N=readCliVersion();if(C!==`gjs`){await runShowcaseOnRuntime(S,C,N);return}let F=N?`${S.packageName}@${N}`:S.packageName;ve.log(`Running showcase: ${S.name} ${runningAs(N)}(via gjsify dlx ${F})\n`);try{let{runCli:n}=await Promise.resolve().then(()=>(gH(),hH));await n([`dlx`,F])}catch(n){ve.error(n.message),process.exit(1)}}}});function resolveTemplatesRoot(){let n=Ps(fileURLToPath(import.meta.url)),S=[js(n,`..`,`dist-templates`),js(n,`dist-templates`)];try{let n=createRequire(import.meta.url).resolve(`@gjsify/create-app/package.json`);S.splice(1,0,js(Ps(n),`dist-templates`))}catch{}return S.find(n=>existsSync(n))}function discoverTemplates(){let n=resolveTemplatesRoot();if(!n)return[];let S=[];for(let C of readdirSync(n)){let N=js(n,C),F=js(N,`package.json`);if(!statSync(N).isDirectory()||!existsSync(F))continue;let I=uI[C]??``;try{let n=JSON.parse(readFileSync(F,`utf-8`));typeof n.description==`string`&&n.description.trim()&&(I=n.description)}catch{}S.push({name:C,description:I,path:N})}return S.sort((n,S)=>n.name.localeCompare(S.name)),S}function findTemplate(n){return discoverTemplates().find(S=>S.name===n)}var uI,dI=__esmMin(()=>{Vl(),gs(),Hs(),gn(),uI={"gtk-minimal":`Minimal GTK4 app — Gtk.Window + Gtk.Label (no Adwaita, no Blueprint).`,cli:`Command-line tool using yargs (Node.js + GJS).`,"adw-canvas2d":`Adwaita app with HTML Canvas 2D rendering (Blueprint UI).`,"adw-webgl":`Adwaita app with WebGL + three.js (Blueprint UI).`,"adw-game":`Adwaita game shell using Excalibur.js, WebGL → Canvas2D fallback.`,"web-server-hono":`HTTP server using Hono (Web-standard fetch-style API).`,"web-server-express":`HTTP server using Express (familiar Node.js stack).`}});function runScriptCommand(n){return mI[n]}function packageManagersForRuntime(n){return hI[n]}function hostRuntime(){let n=globalThis;return n.Bun===void 0?n.Deno===void 0?n.imports?.gi===void 0?`node`:`gjs`:`deno`:`bun`}function defaultRuntimeFor(n,S){if(S)return n.find(n=>packageManagersForRuntime(n)?.includes(S));let C=hostRuntime();return n.includes(C)?C:n[0]}function startScriptFor(n){return n===`gjs`?`start`:`start:${n}`}var fI,pI,mI,hI,gI,_I=__esmMin(()=>{fI=[`npm`,`yarn`,`pnpm`,`gjsify`,`bun`,`deno`],pI={npm:[`install`,`--no-audit`,`--no-fund`],yarn:[`install`],pnpm:[`install`],gjsify:[`install`],bun:[`install`],deno:[`install`]},mI={npm:`npm run`,yarn:`yarn`,pnpm:`pnpm`,gjsify:`gjsify run`,bun:`bun run`,deno:`deno task`},hI={gjs:[`gjsify`],node:[`npm`,`yarn`,`pnpm`,`gjsify`],bun:[`bun`],deno:[`deno`]},gI={gjs:`GNOME JavaScript — no Node.js needed at runtime.`,node:`Node.js — gi:// via the @gjsify/node-gi bridge.`,bun:`Bun — runs the same --app node bundle.`,deno:`Deno — runs the same --app node bundle.`}});function selectRuntime(n){let{flag:S,offered:C,manager:N,interactive:F}=n;if(S!==void 0)return C.length>0&&!C.includes(S)?{kind:`error`,message:`this template does not run on "${S}". Declared runtimes: ${C.join(`, `)}.`}:{kind:`value`,value:S};if(C.length===1)return{kind:`value`,value:C[0]};if(C.length===0)return{kind:`error`,message:`this template declares no runtime this scaffolder can install for.`};let I=defaultRuntimeFor(C,N);return I===void 0?{kind:`error`,message:`no runtime this template declares installs with "${N}". Declared runtimes: ${C.join(`, `)}.`}:N===void 0?F?{kind:`prompt`,choices:C,initial:I}:{kind:`auto`,value:I,notice:`--runtime not given, using "${I}". Runs on: ${C.join(`, `)}.`}:{kind:`auto`,value:I,notice:`Setting up for ${I} — the runtime ${N} installs for.`}}function selectPackageManager(n){let{flag:S,runtime:C,install:N,interactive:F}=n,I=packageManagersForRuntime(C);return I===void 0||I.length===0?{kind:`error`,message:`no package manager known for runtime "${C}".`}:S===void 0?I.length===1?{kind:`auto`,value:I[0],notice:`Using ${I[0]} — the only package manager that installs for ${C}.`}:F?{kind:`prompt`,choices:I,initial:I[0]}:N?{kind:`error`,message:`--package-manager is required with --install in non-interactive mode. Package managers for ${C}: ${I.join(`, `)}.`}:{kind:`auto`,value:I[0],notice:`--package-manager not given, using "${I[0]}" for ${C}.`}:I.includes(S)?{kind:`value`,value:S}:{kind:`error`,message:`"${S}" cannot install a project you intend to run on ${C}. Package managers for ${C}: ${I.join(`, `)}.`}}var vI=__esmMin(()=>{_I()});function applicationIdFor(n){let S=n.replace(/[^A-Za-z0-9_-]/g,`-`);return`org.gjsify.${/^[0-9]/.test(S)?`app-${S}`:S}`}function sanitizeProjectName(n){let S=n.trim();if(!S)throw Error(`Project name cannot be empty.`);let C=S.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[._-]+/,``).replace(/[._-]+$/,``);if(!C)throw Error(`"${n}" is not a valid npm package name.`);return C}function isDirEmpty(n){return existsSync(n)?readdirSync(n).length===0:!0}async function createProject(n){let S=sanitizeProjectName(n.projectName),{template:C,force:N=!1,install:F=!1}=n,I=findTemplate(C);if(!I){let n=discoverTemplates().map(n=>n.name).join(`, `);throw Error(`Unknown template "${C}". Available templates: ${n||`(none — run "yarn build" first)`}`)}let H=supportedRuntimes(I),W=n.runtime??defaultRuntimeFor(H,n.packageManager)??hostRuntime(),q=packageManagersForRuntime(W);if(!q)throw Error(`Template "${I.name}" was asked for runtime "${W}", which this version of @gjsify/create-app has no installer mapping for. Upgrade it, or pick one of: ${H.join(`, `)||`(none)`}.`);let Y=n.packageManager??q[0];if(!q.includes(Y))throw Error(`"${Y}" cannot install a project you intend to run on ${W}. Package managers for ${W}: ${q.join(`, `)}.`);let X=Os(process.cwd(),S);if(existsSync(X)&&!isDirEmpty(X)&&!N)return ve.error(`Error: Directory "${S}" exists and is not empty. Use --force to scaffold into it anyway.`),process.exit(1);if(ve.log(`Creating new Gjsify project in ${X} (template: ${I.name})...`),mkdirSync(X,{recursive:!0}),cpSync(I.path,X,{recursive:!0}),substituteTemplateSentinels(X,S),F){let n=[...pI[Y]];ve.log(`Running ${Y} ${n[0]}...`);let S=spawnSync(Y,n,{cwd:X,stdio:`inherit`,shell:!0});S.error?ve.warn(`${Y} install could not start (${S.error.message}); re-run it manually.`):S.status!==0&&ve.warn(`${Y} install failed; re-run it manually in the project directory.`)}printNextSteps(S,I,F,Y,W)}function substituteTemplateSentinels(n,S){let C=[[yI,S],[bI,applicationIdFor(S)]],N=new Set([`node_modules`,`dist`,`lib`]),F=[n];for(;F.length>0;){let n=F.pop();for(let S of readdirSync(n,{withFileTypes:!0})){let I=js(n,S.name);if(S.isDirectory()){N.has(S.name)||F.push(I);continue}if(!S.isFile())continue;let H=S.name.lastIndexOf(`.`),W=H>=0?S.name.slice(H):``;if(!xI.has(W))continue;let q=readFileSync(I,`utf-8`),Y=q;for(let[n,S]of C)Y=Y.replaceAll(n,S);Y!==q&&writeFileSync(I,Y)}}}function printNextSteps(n,S,C,N,F){let I=runScriptCommand(N),H=templateScripts(S),W=startScriptFor(F);ve.log(``),ve.log(`Project created from template "${S.name}", set up for ${F}.`),ve.log(``),ve.log(`Next steps:`),ve.log(` cd ${n}`),C||ve.log(` ${N} install`),F===`gjs`&&H.dev?ve.log(` ${I} dev`):(ve.log(` ${I} build`),ve.log(` ${I} ${W}`)),ve.log(``);let q=supportedRuntimes(S).filter(n=>n!==F&&H[startScriptFor(n)]);if(q.length>0){ve.log(`Also runs on ${q.join(`, `)}:`);for(let n of q)ve.log(` ${I} ${startScriptFor(n)}`);ve.log(``)}}function templateManifest(n){try{return JSON.parse(readFileSync(js(n.path,`package.json`),`utf-8`))}catch{return{}}}function templateScripts(n){let S=templateManifest(n).scripts;return S?Object.fromEntries(Object.entries(S).filter(n=>typeof n[1]==`string`)):{}}function supportedRuntimes(n){let S=templateManifest(n).gjsify?.example?.runtimes;return Array.isArray(S)?S.filter(n=>typeof n==`string`&&packageManagersForRuntime(n)!==void 0):[]}var yI,bI,xI,SI=__esmMin(()=>{ye(),Dh(),Vl(),Hs(),dI(),_I(),vI(),yI=`new-gjsify-app`,bI=`org.gjsify.example`,xI=new Set([`.json`,`.md`,`.ts`,`.tsx`,`.js`,`.mjs`,`.cjs`,`.blp`,`.html`,`.css`,`.scss`,`.xml`,`.ui`,`.txt`])});function isCancelled(n){return n instanceof Error&&n.message===wI}function render(n,S,C){C||an.write(`\x1b[${n.length}A`);for(let C=0;C<n.length;C++){let N=n[C],F=C===S?`${CI.cyan}❯${CI.reset}`:` `,I=C===S?`${CI.bold}${CI.green}${N.label}${CI.reset}`:N.label,H=N.description?` ${CI.dim}${N.description}${CI.reset}`:``;an.write(`\x1b[2K\r ${F} ${I}${H}\n`)}}function promptChoice(n,S,C=0){return S.length===0?Promise.reject(Error(`Nothing to choose for "${n}".`)):new Promise((N,F)=>{let I=C>=0&&C<S.length?C:0;an.write(`${CI.bold}${n}${CI.reset} ${CI.dim}(↑/↓ to navigate, Enter to confirm, Ctrl+C to cancel)${CI.reset}\n`),render(S,I,!0),emitKeypressEvents(on),on.isTTY&&on.setRawMode(!0),on.resume();let cleanup=()=>{on.removeListener(`keypress`,onKeypress),on.isTTY&&on.setRawMode(!1),on.pause()},onKeypress=(n,C)=>{if(C){if(C.ctrl&&C.name===`c`){cleanup(),an.write(`
|
|
919
|
+
`),F(Error(wI));return}C.name===`up`||C.name===`k`?(I=(I-1+S.length)%S.length,render(S,I,!1)):C.name===`down`||C.name===`j`?(I=(I+1)%S.length,render(S,I,!1)):(C.name===`return`||C.name===`enter`)&&(cleanup(),N(S[I].value))}};on.on(`keypress`,onKeypress)})}function promptTemplate(n){return n.length===0?Promise.reject(Error(`No templates available.`)):promptChoice(`Select a template`,n.map(n=>({value:n,label:n.name,description:n.description})))}function promptRuntime(n,S){return promptChoice(`Select a runtime`,n.map(n=>({value:n,label:n,description:gI[n]??``})),n.indexOf(S))}function promptPackageManager(n,S){return promptChoice(`Select a package manager`,n.map(n=>({value:n,label:n,description:``})),n.indexOf(S))}async function settle(n,S){switch(n.kind){case`value`:return n.value;case`auto`:return ve.error(n.notice),n.value;case`prompt`:try{return await S(n.choices,n.initial)}catch(n){if(!isCancelled(n))throw n;ve.error(`Cancelled.`);return}case`error`:ve.error(`Error: ${n.message}`);return}}async function promptSetup(n){let{offered:S,install:C,interactive:N}=n,F=await settle(selectRuntime({flag:n.runtime,offered:S,manager:n.packageManager,interactive:N}),(n,S)=>promptRuntime(n,S));if(F===void 0)return;let I=await settle(selectPackageManager({flag:n.packageManager,runtime:F,install:C,interactive:N}),(n,S)=>promptPackageManager(n,S));if(I!==void 0)return{runtime:F,packageManager:I}}var CI,wI,TI=__esmMin(()=>{ye(),sn(),Ml(),_I(),vI(),CI={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,cyan:`\x1B[36m`,green:`\x1B[32m`},wI=`Cancelled by user`}),EI,DI=__esmMin(()=>{ye(),SI(),TI(),EI={command:`create [project-name]`,description:`Scaffold a new Gjsify project in a new directory.`,builder:n=>{let S=discoverTemplates(),C=S.map(n=>n.name),N=[...new Set(S.flatMap(n=>supportedRuntimes(n)))];return n.positional(`project-name`,{describe:`Name of the project directory to create`,type:`string`,default:`my-gjs-app`}).option(`template`,{alias:`t`,describe:`Template to scaffold from`,type:`string`,choices:C.length>0?C:void 0}).option(`runtime`,{alias:`r`,describe:`Runtime to set the project up for. Decides which package managers are offered and which start script the next steps name.`,type:`string`,choices:N.length>0?N:void 0}).option(`force`,{alias:`f`,describe:`Scaffold into a non-empty directory`,type:`boolean`,default:!1}).option(`install`,{describe:`Install dependencies after scaffolding`,type:`boolean`,default:!1}).option(`package-manager`,{alias:`p`,describe:"Package manager to install with, and to name in the printed next steps. Must be one the chosen runtime can install for. `gjsify` is the only one that works on a host with no Node.js.",type:`string`,choices:fI})},handler:async n=>{let S=!!process.stdin.isTTY,C=discoverTemplates(),N=n.template;if(!N){if(!S){let n=C.map(n=>n.name).join(`, `);return ve.error(`Error: --template is required in non-interactive mode. Available templates: ${n||`(none)`}`),process.exit(1)}let n=await promptTemplate(C).catch(n=>{if(!isCancelled(n))throw n;ve.error(`Cancelled.`)});if(n===void 0)return process.exit(1);N=n.name}let F=C.find(n=>n.name===N),I=await promptSetup({offered:F?supportedRuntimes(F):[],runtime:n.runtime,packageManager:n[`package-manager`],install:n.install,interactive:S});if(I===void 0)return process.exit(1);await createProject({projectName:n[`project-name`],template:N,runtime:I.runtime,force:n.force,install:n.install,packageManager:I.packageManager})}}});function defaultTargetFor(n){let S=Fs(n,Is(n));return Os(Ps(n),S)}var OI,kI,AI=__esmMin(()=>{ye(),Dh(),Cl(),Hs(),Ac(),OI=promisify(execFile),kI={command:`gresource <xml>`,description:"Compile a GResource XML descriptor into a binary .gresource bundle (wraps `glib-compile-resources`).",builder:n=>n.positional(`xml`,{description:`Path to the .gresource.xml descriptor`,type:`string`,normalize:!0,demandOption:!0}).option(`sourcedir`,{description:`Directory containing the resource files referenced by <xml>`,type:`string`,normalize:!0}).option(`target`,{alias:`t`,description:`Output .gresource file (default: <xml-without-.xml> next to <xml>)`,type:`string`,normalize:!0}).option(`verbose`,{description:`Print the underlying glib-compile-resources invocation`,type:`boolean`,default:!1}),handler:async n=>{let S=Os(n.xml),C=n.target?Os(n.target):defaultTargetFor(S),N=[`--sourcedir=${n.sourcedir?Os(n.sourcedir):Ps(S)}`,`--target=${C}`,S];n.verbose&&ve.log(`[gjsify gresource] glib-compile-resources ${N.join(` `)}`),await mkdir$1(Ps(C),{recursive:!0});try{let{stdout:S,stderr:F}=await OI(`glib-compile-resources`,N);S&&process.stdout.write(S),F&&process.stderr.write(F),n.verbose&&ve.log(`[gjsify gresource] wrote ${C}`)}catch(n){let S=n;S?.code===`ENOENT`?ve.error(`[gjsify gresource] glib-compile-resources not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(S?.stderr&&process.stderr.write(S.stderr),ve.error(`[gjsify gresource] glib-compile-resources failed${S?.code===void 0?``:` (exit ${S.code})`}`)),process.exitCode=typeof S?.code==`number`?S.code:1}}}});function mergeCatalogues(n){let S=n.template,C=new Set;for(let{locale:S}of n.catalogues){if(C.has(S))throw Error(`mergeCatalogues: two catalogues both claim locale "${S}". msgfmt APPENDS each --locale, so the chain would emit a duplicate key (desktop-file-validate: "multiple keys named Name[${S}]"; appstreamcli: "tag-duplicated") from two exit-0 calls. Merge them into one .po first (msgcat --use-first) and pass that.`);C.add(S)}for(let[C,N]of n.catalogues.entries()){let F=js(n.workDir,`${C}${n.extension}`),I=[n.mode,`--template=${S}`,`--locale=${N.locale}`,`--output-file=${F}`,N.po];n.onCall?.(I),execFileSync(`msgfmt`,I,{stdio:`pipe`}),S=F}return S}var jI=__esmMin(()=>{Dh(),Hs()});async function listLanguages(n){return(await readdir$1(n)).filter(n=>n.endsWith(`.po`)&&!n.startsWith(`.`)).map(n=>n.slice(0,-3)).sort()}function stripXmlComments(n){return n.replace(/<!--[\s\S]*?-->/g,``)}async function ensureDir(n){await mkdir$1(n,{recursive:!0})}async function fileExists(n){try{return await stat$1(n),!0}catch{return!1}}async function compileMerged(n){let S=await listLanguages(n.poDir);if(S.length===0){ve.warn(`[gjsify gettext] no .po files found in ${n.poDir}`);return}let C=js(n.outDir,n.filename);await ensureDir(n.outDir);let N=await mkdtemp$1(js(tmpdir(),`gjsify-gettext-`));try{let F=await readFile$1(mergeCatalogues({mode:`--${n.format}`,template:n.template,extension:`-${Fs(n.template).replace(/\.in$/,``)}`,catalogues:S.map(S=>({locale:S,po:js(n.poDir,`${S}.po`)})),workDir:N,onCall:n.verbose?n=>ve.log(`[gjsify gettext] msgfmt ${n.join(` `)}`):void 0}),`utf-8`);await writeFile$1(C,n.removeXmlComments&&n.format===`xml`?stripXmlComments(F):F)}finally{await rm$1(N,{recursive:!0,force:!0})}n.verbose&&ve.log(`[gjsify gettext] merged ${S.length} language(s) into ${C}`)}async function compileCatalogues(n){let S=await listLanguages(n.poDir);if(S.length===0){ve.warn(`[gjsify gettext] no .po files found in ${n.poDir}`);return}for(let C of S){let S=js(n.outDir,C,`LC_MESSAGES`);await ensureDir(S);let N=[`--output-file=${js(S,n.filename)}`,js(n.poDir,`${C}.po`)];n.verbose&&ve.log(`[gjsify gettext] msgfmt ${N.join(` `)}`),await MI(`msgfmt`,N)}n.verbose&&ve.log(`[gjsify gettext] compiled ${S.length} language(s) into ${n.outDir}`)}function defaultFilename(n,S,C){switch(S){case`mo`:return`${n}.mo`;case`desktop`:return`${n}.desktop`;case`xml`:return C?Fs(C.replace(/\.in$/,``)):`${n}.xml`}}var MI,NI,PI=__esmMin(()=>{ye(),Dh(),Cl(),Dm(),Hs(),Ac(),jI(),MI=promisify(execFile),NI={command:`gettext <poDir> <outDir>`,description:`Compile gettext .po files to .mo (per-language locale tree), or merge every catalogue into a .desktop / AppStream template via msgfmt --desktop / --xml.`,builder:n=>n.positional(`poDir`,{description:`Directory containing <lang>.po files`,type:`string`,normalize:!0,demandOption:!0}).positional(`outDir`,{description:`Output directory (locale tree for --format=mo, plain dir for xml/desktop)`,type:`string`,normalize:!0,demandOption:!0}).option(`domain`,{description:"Text domain / application ID (e.g. `org.pixelrpg.maker`)",type:`string`,normalize:!0,demandOption:!0}).option(`format`,{description:`Output format`,type:`string`,choices:[`mo`,`xml`,`desktop`],default:`mo`}).option(`template`,{description:"Required for --format=xml|desktop: the file msgfmt substitutes into. Its SUFFIX matters — msgfmt --xml finds its ITS rules by filename pattern, so an AppStream template must be named `*.metainfo.xml[.in]`.",type:`string`,normalize:!0}).option(`metainfo`,{description:`Deprecated alias for --template.`,type:`string`,normalize:!0,hidden:!0}).option(`filename`,{description:`Override the output filename (defaults to <domain>.<ext>)`,type:`string`,normalize:!0}).option(`remove-xml-comments`,{description:`For --format=xml: strip XML comments from the compiled output`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print each msgfmt invocation`,type:`boolean`,default:!1}),handler:async n=>{let S=Os(n.poDir),C=Os(n.outDir),N=n.domain,F=n.format??`mo`,I=n.template??n.metainfo,H=I?Os(I):void 0,W=n.filename??defaultFilename(N,F,H),q=!!n.verbose,Y=!!n[`remove-xml-comments`];if(!await fileExists(S)){ve.error(`[gjsify gettext] PO directory does not exist: ${S}`),process.exitCode=1;return}if(F!==`mo`&&H===void 0){ve.error(`[gjsify gettext] --format=${F} needs a template to substitute into: pass \`--template <file>\`. msgfmt has no way to produce this format from .po files alone.`+(F===`xml`?" Name it `*.metainfo.xml[.in]` — msgfmt --xml finds its ITS rules by filename pattern.":``)),process.exitCode=1;return}try{F===`mo`?await compileCatalogues({poDir:S,outDir:C,filename:W,verbose:q}):await compileMerged({poDir:S,outDir:C,format:F,template:H,filename:W,removeXmlComments:Y,verbose:q})}catch(n){let S=n;S?.code===`ENOENT`?ve.error(`[gjsify gettext] msgfmt not found. Install it via your distro (package: gettext).`):(S?.stderr&&process.stderr.write(S.stderr),ve.error(`[gjsify gettext] msgfmt failed${S?.code===void 0?``:` (exit ${S.code})`}`)),process.exitCode=typeof S?.code==`number`?S.code:1}}}}),FI,II,LI=__esmMin(()=>{ye(),Dh(),Cl(),Hs(),Ac(),FI=promisify(execFile),II={command:`gsettings <schemadir>`,description:"Compile GSettings schema XML files into a binary gschemas.compiled (wraps `glib-compile-schemas`).",builder:n=>n.positional(`schemadir`,{description:`Directory containing *.gschema.xml descriptors`,type:`string`,normalize:!0,demandOption:!0}).option(`targetdir`,{alias:`t`,description:`Directory to write gschemas.compiled (default: <schemadir>)`,type:`string`,normalize:!0}).option(`strict`,{description:`Abort on any schema warning (passes --strict to glib-compile-schemas)`,type:`boolean`,default:!0}).option(`verbose`,{description:`Print the underlying glib-compile-schemas invocation`,type:`boolean`,default:!1}),handler:async n=>{let S=Os(n.schemadir),C=n.targetdir?Os(n.targetdir):S,N=[];n.strict&&N.push(`--strict`),N.push(`--targetdir=${C}`),N.push(S),n.verbose&&ve.log(`[gjsify gsettings] glib-compile-schemas ${N.join(` `)}`),await mkdir$1(C,{recursive:!0});try{let{stdout:S,stderr:F}=await FI(`glib-compile-schemas`,N);S&&process.stdout.write(S),F&&process.stderr.write(F),n.verbose&&ve.log(`[gjsify gsettings] wrote ${C}/gschemas.compiled`)}catch(n){let S=n;S?.code===`ENOENT`?ve.error(`[gjsify gsettings] glib-compile-schemas not found. Install it via your distro (package: glib2-devel / libglib2.0-dev).`):(S?.stderr&&process.stderr.write(S.stderr),ve.error(`[gjsify gsettings] glib-compile-schemas failed${S?.code===void 0?``:` (exit ${S.code})`}`)),process.exitCode=typeof S?.code==`number`?S.code:1}}}});function readPackageJson(n){let S=Os(n,`package.json`),C;try{C=readFileSync(S,`utf-8`)}catch{throw Error(`gjsify flatpak: no package.json found at ${S}`)}try{return JSON.parse(C)}catch(n){throw Error(`gjsify flatpak: package.json at ${S} is not valid JSON: ${n.message}`)}}function looksLikeAppId(n){return typeof n==`string`&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*){2,}$/.test(n)}function defaultCiContainer(n,S){return`ghcr.io/flathub-infra/flatpak-github-actions:${`${n}-${S}`}`}var RI=__esmMin(()=>{Vl(),Hs()});function resolveRuntime(n,S){let C=S.runtime??n?.runtime??`gnome`;if(C!==`gnome`&&C!==`freedesktop`)throw Error(`gjsify flatpak: unknown runtime "${C}" (expected "gnome" or "freedesktop")`);let N=S.runtimeVersion??n?.runtimeVersion??(C===`gnome`?`50`:`24.08`);return C===`gnome`?{runtime:C,runtimeId:`org.gnome.Platform`,sdk:`org.gnome.Sdk`,runtimeVersion:N}:{runtime:C,runtimeId:`org.freedesktop.Platform`,sdk:`org.freedesktop.Sdk`,runtimeVersion:N}}function deriveAppendPath(n){let S=[];for(let C of n){let n=/^org\.freedesktop\.Sdk\.Extension\.([A-Za-z0-9-]+)$/.exec(C);n&&S.push(`/usr/lib/sdk/${n[1]}/bin`)}return S.push(`/app/bin`),S}var zI,BI,VI=__esmMin(()=>{zI=[`--device=dri`,`--share=ipc`,`--socket=fallback-x11`,`--socket=wayland`],BI=[]});function pickFlatpakBuildKeys(n,S){let C=n??{},N={},F=[];for(let n of WI){let I=C[n];if(I!==void 0){N[n]=I;continue}let H=S[n];H!==void 0&&F.push(n),N[n]=H}return{values:N,fromLegacy:F}}function resolveShipFlatpakSettings(n){let S=n.ship.flatpak??{},{values:C,fromLegacy:N}=pickFlatpakBuildKeys(S,n.flatpak),F=resolveRuntime(C,{}),I=C.sdkExtensions??[],{appendPath:H,finishArgs:W,cleanup:q}=C;return{settings:{runtime:F.runtimeId,runtimeVersion:F.runtimeVersion,sdk:F.sdk,branch:S.branch??`stable`,sdkExtensions:[...I],appendPath:H??(I.length>0?deriveAppendPath(I):[]),finishArgs:W??(n.kind===`cli`?BI:zI),cleanup:q??[]},warnings:N.length===0?[]:[deprecationWarning(N)]}}function deprecationWarning(n){let S=n.map(n=>`gjsify.flatpak.${n}`).join(`, `),C=n.map(n=>`gjsify.ship.flatpak.${n}`).join(`, `);return`DEPRECATION: ${S} ${n.length>1?`are`:`is`} read by \`gjsify ship\` for compatibility and will be removed in ${HI}. Move ${n.length>1?`them`:`it`} to ${C} — both spellings resolve until then, and \`gjsify.ship.flatpak\` wins where both are set. The app METADATA in \`gjsify.flatpak\` (name, summary, developer, categories, licence) is NOT deprecated: both blocks describe the same application and either may carry it (ADR 0024 § 8).`}var HI,WI,GI=__esmMin(()=>{VI(),HI=`1.0.0`,WI=[`runtime`,`runtimeVersion`,`sdkExtensions`,`appendPath`,`finishArgs`,`cleanup`]});function loadDesktopTemplate(){return KI}function validateAppMetadata(n){let S=n.metadata,C=n.configKey,N=[];return(!S.developer?.id||!S.developer?.name)&&N.push({field:`${C}.developer`,hint:`Set \`${C}.developer = { "id": "io.github.you", "name": "Your Name" }\` in package.json. The id is reverse-DNS.`}),S.summary||N.push({field:`${C}.summary`,hint:`One-line app summary, ≤80 chars, no trailing period. Example: "Learn 6502 assembly language".`}),S.description||N.push({field:`${C}.description`,hint:`Plain text (split on blank lines) or DescriptionBlock[] for rich content with bullet lists + translator hints.`}),S.license?.project||N.push({field:`${C}.license.project`,hint:`SPDX identifier of the project license, e.g. "MIT", "GPL-3.0-or-later".`}),S.homepageUrl||N.push({field:`${C}.homepageUrl`,hint:`Required by Flathub. Example: "https://github.com/you/your-repo".`}),N}function renderMetainfoApp$1(n){return renderMetainfo(n,`desktop-application`)}function renderMetainfoCli$1(n){return renderMetainfo(n,`console-application`)}function renderDesktopEntry(n){let S=n.metadata,C=(S.categories??[`Utility`]).join(`;`)+`;`,N=S.keywords?.length?`Keywords=${S.keywords.join(`;`)};\n`:``,F=S.provides?.mimetypes??[],I=F.length?`MimeType=${F.join(`;`)};\n`:``;return substitute(loadDesktopTemplate(),{NAME:n.name,SUMMARY:S.summary??n.name,COMMAND:`${n.command}${execFieldCode(F)}`,APP_ID:n.appId,CATEGORIES_LINE:C,KEYWORDS_LINE:N,MIMETYPES_LINE:I})}function execFieldCode(n){return n.some(n=>n.startsWith(`x-scheme-handler/`))?` %u`:n.length>0?` %f`:``}function renderMetainfo(n,S){let C=n.metadata,N=n.copyrightYear??new Date().getFullYear(),F=C.developer?.name??``,I=[];I.push(`<?xml version="1.0" encoding="UTF-8"?>`),I.push(`<!-- Copyright ${N} ${escapeXml(F)} -->`),I.push(`<component type="${S}">`),I.push(` <id>${escapeXml(n.appId)}</id>`),I.push(` <metadata_license>${escapeXml(C.license?.metadata??`CC0-1.0`)}</metadata_license>`),I.push(` <project_license>${escapeXml(C.license?.project??``)}</project_license>`),I.push(` <name>${escapeXml(n.name)}</name>`),pushTranslatorHint(I,C.summaryTranslatorHint,` `),I.push(` <summary>${escapeXml(C.summary??n.name)}</summary>`),C.iconRemote&&I.push(` <icon type="remote">${escapeXml(C.iconRemote)}</icon>`),I.push(` <description>`);for(let n of renderDescriptionBlocks(C.description??``,` `))I.push(n);if(I.push(` </description>`),C.developer?.id&&C.developer?.name){I.push(` <developer id="${escapeXml(C.developer.id)}">`);let n=C.developer.nameTranslatable===!0?``:` translate="no"`;I.push(` <name${n}>${escapeXml(C.developer.name)}</name>`),C.developer.email&&I.push(` <email>${escapeXml(C.developer.email)}</email>`),I.push(` </developer>`)}S===`desktop-application`&&I.push(` <launchable type="desktop-id">${escapeXml(n.appId)}.desktop</launchable>`),C.screenshots?.length&&(I.push(` <screenshots>`),C.screenshots.forEach((n,S)=>{let C=n.type??(S===0?`default`:void 0),N=C?` type="${escapeXml(C)}"`:``,F=n.environment?` environment="${escapeXml(n.environment)}"`:``;I.push(` <screenshot${N}${F}>`),I.push(` <image>${escapeXml(n.url)}</image>`),n.caption&&(pushTranslatorHint(I,n.captionTranslatorHint,` `),I.push(` <caption>${escapeXml(n.caption)}</caption>`)),I.push(` </screenshot>`)}),I.push(` </screenshots>`)),C.homepageUrl&&I.push(` <url type="homepage">${escapeXml(C.homepageUrl)}</url>`),C.bugtrackerUrl&&I.push(` <url type="bugtracker">${escapeXml(C.bugtrackerUrl)}</url>`),C.vcsBrowserUrl&&I.push(` <url type="vcs-browser">${escapeXml(C.vcsBrowserUrl)}</url>`),C.donationUrl&&I.push(` <url type="donation">${escapeXml(C.donationUrl)}</url>`),C.translateUrl&&I.push(` <url type="translate">${escapeXml(C.translateUrl)}</url>`);let H=normaliseContentRating(C.contentRating);if(H.attributes&&Object.keys(H.attributes).length>0){I.push(` <content_rating type="${escapeXml(H.type)}">`);for(let[n,S]of Object.entries(H.attributes))I.push(` <content_attribute id="${escapeXml(n)}">${escapeXml(S)}</content_attribute>`);I.push(` </content_rating>`)}else I.push(` <content_rating type="${escapeXml(H.type)}" />`);if(C.releases?.length){I.push(` <releases>`);for(let n of C.releases)if(n.description===void 0)I.push(` <release version="${escapeXml(n.version)}" date="${escapeXml(n.date)}" />`);else{I.push(` <release version="${escapeXml(n.version)}" date="${escapeXml(n.date)}">`),I.push(` <description>`);for(let S of renderDescriptionBlocks(n.description,` `))I.push(S);I.push(` </description>`),I.push(` </release>`)}I.push(` </releases>`)}if(C.categories?.length){I.push(` <categories>`);for(let n of C.categories)I.push(` <category>${escapeXml(n)}</category>`);I.push(` </categories>`)}if(C.keywords?.length){I.push(` <keywords>`);for(let n of C.keywords)I.push(` <keyword>${escapeXml(n)}</keyword>`);I.push(` </keywords>`)}if(S===`desktop-application`&&C.branding&&(I.push(` <branding>`),I.push(` <color type="primary" scheme_preference="light">${escapeXml(C.branding.accentLight)}</color>`),I.push(` <color type="primary" scheme_preference="dark">${escapeXml(C.branding.accentDark)}</color>`),I.push(` </branding>`)),C.kudos?.length){I.push(` <kudos>`);for(let n of C.kudos)I.push(` <kudo>${escapeXml(n)}</kudo>`);I.push(` </kudos>`)}let W=C.provides?.binaries??[n.command],q=C.provides?.mimetypes??[],Y=C.provides?.dbus??[];if(W.length||q.length||Y.length){I.push(` <provides>`);for(let n of W)I.push(` <binary>${escapeXml(n)}</binary>`);for(let n of q)I.push(` <mediatype>${escapeXml(n)}</mediatype>`);for(let n of Y)I.push(` <dbus type="${escapeXml(n.type)}">${escapeXml(n.id)}</dbus>`);I.push(` </provides>`)}if(C.supports?.controls?.length||C.supports?.internet){I.push(` <supports>`);for(let n of C.supports.controls??[])I.push(` <control>${escapeXml(n)}</control>`);C.supports.internet&&I.push(` <internet>${escapeXml(C.supports.internet)}</internet>`),I.push(` </supports>`)}if(C.requires?.displayLengthMin||C.requires?.controls?.length||C.requires?.internet){I.push(` <requires>`),C.requires.displayLengthMin&&I.push(` <display_length compare="ge">${C.requires.displayLengthMin}</display_length>`);for(let n of C.requires.controls??[])I.push(` <control>${escapeXml(n)}</control>`);C.requires.internet&&I.push(` <internet>${escapeXml(C.requires.internet)}</internet>`),I.push(` </requires>`)}if(C.recommends?.displayLengthMin||C.recommends?.controls?.length){I.push(` <recommends>`),C.recommends.displayLengthMin&&I.push(` <display_length compare="ge">${C.recommends.displayLengthMin}</display_length>`);for(let n of C.recommends.controls??[])I.push(` <control>${escapeXml(n)}</control>`);I.push(` </recommends>`)}return I.push(`</component>`),I.join(`
|
|
920
920
|
`)+`
|
|
921
|
-
`}function renderDescriptionBlocks(n,S){let C=typeof n==`string`?stringToBlocks(n):n,N=[];for(let n of C)if(`p`in n)pushTranslatorHint(N,n.translatorHint,S),N.push(`${S}<p>${escapeXml(n.p.trim().replace(/\s+/g,` `))}</p>`);else{pushTranslatorHint(N,n.translatorHint,S),N.push(`${S}<ul>`);for(let C of n.ul)typeof C==`string`?N.push(`${S} <li>${escapeXml(C)}</li>`):(pushTranslatorHint(N,C.translatorHint,`${S} `),N.push(`${S} <li>${escapeXml(C.item)}</li>`));N.push(`${S}</ul>`)}return N}function stringToBlocks(n){return n.trim().split(/\n\n+/).map(n=>({p:n.trim().replace(/\s+/g,` `)}))}function pushTranslatorHint(n,S,C){S&&n.push(`${C}<!-- TRANSLATORS: ${S} -->`)}function normaliseContentRating(n){return n===void 0?{type:`oars-1.1`}:typeof n==`string`?{type:n}:{type:n.type??`oars-1.1`,attributes:n.attributes}}function substitute(n,S){let C=n;for(let[n,N]of Object.entries(S))C=C.split(`{{${n}}}`).join(N);return C}function escapeXml(n){return n.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var
|
|
921
|
+
`}function renderDescriptionBlocks(n,S){let C=typeof n==`string`?stringToBlocks(n):n,N=[];for(let n of C)if(`p`in n)pushTranslatorHint(N,n.translatorHint,S),N.push(`${S}<p>${escapeXml(n.p.trim().replace(/\s+/g,` `))}</p>`);else{pushTranslatorHint(N,n.translatorHint,S),N.push(`${S}<ul>`);for(let C of n.ul)typeof C==`string`?N.push(`${S} <li>${escapeXml(C)}</li>`):(pushTranslatorHint(N,C.translatorHint,`${S} `),N.push(`${S} <li>${escapeXml(C.item)}</li>`));N.push(`${S}</ul>`)}return N}function stringToBlocks(n){return n.trim().split(/\n\n+/).map(n=>({p:n.trim().replace(/\s+/g,` `)}))}function pushTranslatorHint(n,S,C){S&&n.push(`${C}<!-- TRANSLATORS: ${S} -->`)}function normaliseContentRating(n){return n===void 0?{type:`oars-1.1`}:typeof n==`string`?{type:n}:{type:n.type??`oars-1.1`,attributes:n.attributes}}function substitute(n,S){let C=n;for(let[n,N]of Object.entries(S))C=C.split(`{{${n}}}`).join(N);return C}function escapeXml(n){return n.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}var KI,qI=__esmMin(()=>{KI=`[Desktop Entry]
|
|
922
922
|
Name={{NAME}}
|
|
923
923
|
Comment={{SUMMARY}}
|
|
924
924
|
Exec={{COMMAND}}
|
|
@@ -932,7 +932,7 @@ StartupWMClass={{APP_ID}}
|
|
|
932
932
|
`}function loadFlathubCliTemplate(){return`{
|
|
933
933
|
"skip-icons-check": true
|
|
934
934
|
}
|
|
935
|
-
`}function toMetadataInputs(n){return{appId:n.appId,name:n.name,command:n.command,kind:n.kind,metadata:n.flatpak,configKey:`gjsify.flatpak`}}function validateScaffoldInputs(n){return validateAppMetadata(toMetadataInputs(n))}function renderMetainfoApp(n){return renderMetainfoApp$1(toMetadataInputs(n))}function renderMetainfoCli(n){return renderMetainfoCli$1(toMetadataInputs(n))}function renderDesktop(n){return renderDesktopEntry(toMetadataInputs(n))}function renderFlathubJson(n){return n===`cli`?loadFlathubCliTemplate():loadFlathubAppTemplate()}var
|
|
935
|
+
`}function toMetadataInputs(n){return{appId:n.appId,name:n.name,command:n.command,kind:n.kind,metadata:n.flatpak,configKey:`gjsify.flatpak`}}function validateScaffoldInputs(n){return validateAppMetadata(toMetadataInputs(n))}function renderMetainfoApp(n){return renderMetainfoApp$1(toMetadataInputs(n))}function renderMetainfoCli(n){return renderMetainfoCli$1(toMetadataInputs(n))}function renderDesktop(n){return renderDesktopEntry(toMetadataInputs(n))}function renderFlathubJson(n){return n===`cli`?loadFlathubCliTemplate():loadFlathubAppTemplate()}var JI=__esmMin(()=>{qI()});function oxcBindingSuffix(){let n=process.platform,S=process.arch,C;if(n===`linux`)C=`linux`;else if(n===`darwin`)C=`darwin`;else if(n===`win32`)C=`win32`;else throw Error(`[gjsify oxc] Unsupported platform: ${n}`);let N;if(S===`x64`)N=`x64`;else if(S===`arm64`)N=`arm64`;else throw Error(`[gjsify oxc] Unsupported arch on ${C}: ${S}`);if(C===`linux`){let n=hostLibc(`linux`)===`musl`?`musl`:`gnu`;return`${C}-${N}-${n}`}return C===`win32`?`${C}-${N}-msvc`:`${C}-${N}`}function bindingPackageName(n){return`${n===`oxlint`?`@oxlint`:`@oxfmt`}/binding-${oxcBindingSuffix()}`}function probeNodeModules(n,S,C){let N=js(n,`node_modules`,S,C);return existsSync(N)?N:null}function findOxcLauncher(n,S=process.cwd()){let C=js(`bin`,n),N=probeNodeModules(S,n,C);if(N)return N;let F=findWorkspaceRoot(S);if(F&&F!==S){let S=probeNodeModules(F,n,C);if(S)return S}let I=Os(S,`..`);for(let S=0;S<6;S++){let S=probeNodeModules(I,n,C);if(S)return S;let N=Os(I,`..`);if(N===I)break;I=N}throw new OxcNotFoundError(n,S)}function findOxlintConfig(n=process.cwd()){return findConfigFile(n,[`.oxlintrc.json`])}function findOxfmtConfig(n=process.cwd()){return findConfigFile(n,[`.oxfmtrc`,`.oxfmtrc.json`])}function findConfigFile(n,S){let C=n;for(let n=0;n<12;n++){for(let n of S){let S=js(C,n);if(existsSync(S))return S}let n=Os(C,`..`);if(n===C)break;C=n}return null}async function tryLoadNativeOxfmt(){return YI||(YI=(async()=>{if(!isGjs())return null;try{activateNativePrebuilds();let n=`@gjsify/oxfmt-native`,S=await import(pathToFileURL(resolveNpmPackage(n,{bundleUrl:import.meta.url})??createRequire(import.meta.url).resolve(n)).href);return S.hasNativeOxfmt()?S:null}catch{return null}})(),YI)}async function shouldUseNativeOxfmt(){let n=(globalThis.process?.env??{}).GJSIFY_OXFMT;if(n===`npm`)return!1;if(n===`native`){if(!await tryLoadNativeOxfmt())throw Error(`GJSIFY_OXFMT=native but @gjsify/oxfmt-native is not loadable (no prebuild for this architecture, or not running under GJS).`);return!0}return isGjs()?await tryLoadNativeOxfmt()!==null:!1}async function runOxc(n,S,C={}){if(n===`oxfmt`&&await shouldUseNativeOxfmt()){let n=await tryLoadNativeOxfmt();if(!n)throw Error(`@gjsify/oxfmt-native not loadable`);return C.verbose&&ve.log(`[gjsify oxc] @gjsify/oxfmt-native (in-process) ${S.join(` `)}`),n.runOxfmt(S)}return spawnOxcLauncher(n,S,C)}function spawnOxcLauncher(n,S,C={}){let N=C.cwd??process.cwd(),F=findOxcLauncher(n,N),I=nodeBinary();return C.verbose&&ve.log(`[gjsify oxc] ${I} ${F} ${S.join(` `)}`),spawnToCompletion(I,[F,...S],{completion:`return`,cwd:N,notFound:()=>new OxcNotFoundError(n,N,I)}).then(({code:S,signal:C})=>C===null?S??0:(ve.error(`[gjsify oxc] ${n} terminated by signal ${C}`),1))}function runOxlint(n,S={}){return runOxc(`oxlint`,n,S)}function runOxfmt(n,S={}){return runOxc(`oxfmt`,n,S)}function loadOxlintTemplate(){return`{
|
|
936
936
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
|
937
937
|
"categories": {
|
|
938
938
|
"correctness": "error"
|
|
@@ -1021,11 +1021,11 @@ StartupWMClass={{APP_ID}}
|
|
|
1021
1021
|
"**/*.metainfo.xml"
|
|
1022
1022
|
]
|
|
1023
1023
|
}
|
|
1024
|
-
`}function printOxcNotFound(n){ve.error(n.message)}function setOxcExitCode(n){process.exitCode=n,n!==0&&gjsExit(n)}function hasOxcDevDep(n=process.cwd(),S=`oxfmt`){let C=js(n,`package.json`);if(!existsSync(C))return!1;try{let n=JSON.parse(readFileSync(C,`utf-8`));return!!(n?.devDependencies?.[S]||n?.dependencies?.[S])}catch{return!1}}var OxcNotFoundError,
|
|
1024
|
+
`}function printOxcNotFound(n){ve.error(n.message)}function setOxcExitCode(n){process.exitCode=n,n!==0&&gjsExit(n)}function hasOxcDevDep(n=process.cwd(),S=`oxfmt`){let C=js(n,`package.json`);if(!existsSync(C))return!1;try{let n=JSON.parse(readFileSync(C,`utf-8`));return!!(n?.devDependencies?.[S]||n?.dependencies?.[S])}catch{return!1}}var OxcNotFoundError,YI,XI=__esmMin(()=>{ye(),Vl(),Hs(),gs(),gn(),uF(),qM(),YM(),vN(),xP(),_P(),th(),OxcNotFoundError=class extends Error{tool;cwd;missingInterpreter;constructor(n,S,C){let N=(()=>{try{return bindingPackageName(n)}catch{return`@${n===`oxlint`?`oxlint`:`oxfmt`}/binding-<platform>`}})();super(C===void 0?`[gjsify oxc] ${n} not found.\n Expected: ${n}/bin/${n} in node_modules of ${S} or any workspace root above it.\n Install it via: gjsify install -D ${n}\n (this adds ${n} to devDependencies; the matching ${N} napi binding lands automatically as an optionalDependency.)`:`[gjsify oxc] cannot run ${n}: no \`${C}\` binary on PATH.\n ${n} IS installed — its launcher was found. What is missing is the\n interpreter that runs it: ${n}'s launcher is a Node ESM script.\n`+(n===`oxfmt`?" For a Node-free formatter install the GI bridge:\n gjsify install -D @gjsify/oxfmt-native\n (`gjsify format`/`fix` then run oxfmt in-process under GJS.)":" oxlint has no native GJS bridge yet — its JS-plugin host lives in the\n Node launcher — so `gjsify lint` needs Node on the host for now.")),this.tool=n,this.cwd=S,this.missingInterpreter=C,this.name=`OxcNotFoundError`}},YI=null});function writeIfFresh(n,S,C,N){return existsSync(n)&&!C?(ve.log(`[gjsify flatpak init] skipped ${N}: ${n} (exists; --force to overwrite)`),null):(mkdirSync(Ps(n),{recursive:!0}),writeFileSync(n,S,`utf-8`),ve.log(`[gjsify flatpak init] wrote ${N}: ${n}`),n)}function friendlyName(n,S){if(n.startsWith(`@`))return n.slice(n.indexOf(`/`)+1);if(n===S){let n=S.split(`.`);return n[n.length-1]??S}return n}function mergeArrays(n,S){if(!(!n?.length&&!S?.length))return[...n??[],...S??[]]}function deriveModuleName(n){let S=n.split(`.`);return S[S.length-1]||n}var ZI,QI=__esmMin(()=>{ye(),Vl(),Hs(),RI(),VI(),GI(),JI(),nP(),XI(),ZI={command:`init`,description:"Generate Flatpak manifest + MetaInfo XML + .desktop + flathub.json from `gjsify.flatpak` config.",builder:n=>n.option(`app-id`,{description:"Reverse-DNS app id (default: `gjsify.flatpak.appId` or package.json#name)",type:`string`}).option(`runtime`,{description:`Runtime family`,choices:[`gnome`,`freedesktop`]}).option(`runtime-version`,{description:`Runtime version (default: gnome -> 50, freedesktop -> 24.08)`,type:`string`}).option(`kind`,{description:`App kind: "app" (default, desktop) or "cli" (console-application MetaInfo, no .desktop)`,choices:[`app`,`cli`]}).option(`cli-only`,{description:"(Deprecated) Alias for `--kind cli`. Use --kind instead.",type:`boolean`,default:!1}).option(`manifest`,{description:"Output path for the manifest. Default: `<app-id>.json` in cwd.",type:`string`,normalize:!0}).option(`metainfo`,{description:"Output path for the MetaInfo XML. Default: `data/<app-id>.metainfo.xml.in` in cwd.",type:`string`,normalize:!0}).option(`desktop`,{description:"Output path for the .desktop entry (app kind only). Default: `data/<app-id>.desktop.in`.",type:`string`,normalize:!0}).option(`flathub-json`,{description:"Output path for the flathub.json policy stub. Default: `flathub.json` in cwd.",type:`string`,normalize:!0}).option(`command`,{description:`Binary name in /app/bin (default: app id)`,type:`string`}).option(`sdk-extension`,{description:`Extra SDK extension (repeatable)`,type:`string`,array:!0}).option(`finish-arg`,{description:`Extra finish-arg (repeatable). Override defaults entirely with multiple --finish-arg.`,type:`string`,array:!0}).option(`force`,{description:`Overwrite existing output files (manifest, metainfo, desktop, flathub.json)`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print the resolved manifest fields before writing`,type:`boolean`,default:!1}).option(`format`,{description:"Run `oxfmt --write` on the generated JS/TS files when `oxfmt` is detected in the project. Default: true. Pass --no-format to skip. Note: oxfmt formats JS/TS only — the JSON/XML/.desktop manifests generated here are not reformatted (CSS/JSON formatting was dropped in the oxc migration).",type:`boolean`,default:!0}),handler:async n=>{let S=await new Config().forCommand().catch(()=>({})),C=S.flatpak??{},N=process.cwd(),F=readPackageJson(N),I=n.appId??C.appId??(looksLikeAppId(F.name)?F.name:void 0);if(!I)throw Error(`gjsify flatpak init: no app id available. Pass --app-id, set gjsify.flatpak.appId in package.json, or rename the package to a reverse-DNS id like org.example.MyApp.`);let H=n.kind??C.kind??(n.cliOnly?`cli`:`app`),W=pickFlatpakBuildKeys(S.ship?.flatpak,C).values,{runtime:q,runtimeId:Y,sdk:X,runtimeVersion:Z}=resolveRuntime(W,{runtime:n.runtime,runtimeVersion:n.runtimeVersion}),te=mergeArrays(W.sdkExtensions,n.sdkExtension),ne=W.appendPath??(te?.length?deriveAppendPath(te):void 0),re=n.command??C.command??I,ie=n.finishArg,ae=ie===void 0?W.finishArgs??(H===`cli`?BI:zI):ie,oe={id:I,runtime:Y,"runtime-version":Z,sdk:X};te?.length&&(oe[`sdk-extensions`]=te),ne?.length&&(oe[`build-options`]={"append-path":ne.join(`:`)}),oe.command=re,oe[`finish-args`]=ae;let se=W.cleanup;se?.length&&(oe.cleanup=se);let Q=[];C.modules?.length?Q.push(...C.modules):(C.extraModules?.length&&Q.push(...C.extraModules),Q.push({name:deriveModuleName(I),buildsystem:`meson`,sources:[{type:`dir`,path:`.`}]})),oe.modules=Q;let ce=[],trackWrite=n=>{n&&ce.push(n)};trackWrite(writeIfFresh(Os(N,n.manifest??`${I}.json`),JSON.stringify(oe,null,2)+`
|
|
1025
1025
|
`,n.force??!1,`manifest`));let le=F.name??I,ue={appId:I,name:C.name??friendlyName(le,I),command:re,kind:H,flatpak:C},de=validateScaffoldInputs(ue);if(de.length>0){ve.warn(`[gjsify flatpak init] Manifest written, but MetaInfo / .desktop are skipped — config gaps:`);for(let n of de)ve.warn(` - ${n.field}: ${n.hint}`);ve.warn(`
|
|
1026
|
-
Fill these fields in package.json#gjsify.flatpak (or .gjsifyrc.*) and re-run with --force.`)}else{let S=H===`cli`?renderMetainfoCli(ue):renderMetainfoApp(ue);trackWrite(writeIfFresh(Os(N,n.metainfo??`data/${I}.metainfo.xml.in`),S,n.force??!1,`metainfo`)),H===`app`&&(trackWrite(writeIfFresh(Os(N,n.desktop??`data/${I}.desktop.in`),renderDesktop(ue),n.force??!1,`desktop`)),C.icon||ve.warn(`[gjsify flatpak init] No gjsify.flatpak.icon set. Flathub requires a scalable SVG at\n data/icons/hicolor/scalable/apps/${I}.svg`)),trackWrite(writeIfFresh(Os(N,n.flathubJson??`flathub.json`),renderFlathubJson(H),n.force??!1,`flathub.json`))}let fe=ce.filter(n=>/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(n));if(fe.length>0&&n.format!==!1&&hasOxcDevDep(N))try{await runOxfmt([`--write`,...fe],{cwd:N})}catch(n){if(n instanceof OxcNotFoundError)ve.warn("[gjsify flatpak init] post-format skipped: oxfmt declared but binding not installed. Run `gjsify install` then re-run with --force, or pass --no-format.");else throw n}n.verbose&&(ve.log(`[gjsify flatpak init] kind=${H} runtime=${Y} ${Z} sdk=${X}`),ve.log(`[gjsify flatpak init] command=${re} finish-args=${JSON.stringify(ae)}`))}}});function findDefaultManifest(n){return scanForManifest(n)??`flatpak.json`}function scanForManifest(n){let S=[];try{S=readdirSync(n)}catch{return}for(let C of S)if(C.endsWith(`.json`)&&!(C===`package.json`||C===`tsconfig.json`||C.startsWith(`.`)))try{let S=JSON.parse(readFileSync(Os(n,C),`utf-8`));if(typeof S.id==`string`&&typeof S.runtime==`string`&&Array.isArray(S.modules))return C}catch{}}function readManifestAppId(n){let S=readFileSync(n,`utf-8`),C=JSON.parse(S);if(typeof C.id!=`string`)throw Error(`gjsify flatpak build: ${n} has no string "id" field`);return C.id}async function runFlatpakBuilder(n,S){return runProc(`flatpak-builder`,n,S,{notFoundHint:"flatpak-builder not found. Install via your distro (Fedora: `sudo dnf install flatpak-builder`)."})}async function runFlatpak(n,S){return runProc(`flatpak`,n,S,{notFoundHint:`flatpak not found. Install via your distro and add Flathub: see https://flathub.org/setup.`})}async function runTar(n,S){return runProc(`tar`,n,S,{notFoundHint:`tar not found.`})}async function runProc(n,S,C,N){C.verbose&&ve.log(`[gjsify flatpak] ${n} ${S.join(` `)}`);let{code:F}=await spawnToCompletion(n,S,{completion:`exit`,notFound:()=>Error(`gjsify flatpak: ${N.notFoundHint}`)});if(F!==0)throw Error(`gjsify flatpak: ${n} exited with status ${F}`)}var
|
|
1026
|
+
Fill these fields in package.json#gjsify.flatpak (or .gjsifyrc.*) and re-run with --force.`)}else{let S=H===`cli`?renderMetainfoCli(ue):renderMetainfoApp(ue);trackWrite(writeIfFresh(Os(N,n.metainfo??`data/${I}.metainfo.xml.in`),S,n.force??!1,`metainfo`)),H===`app`&&(trackWrite(writeIfFresh(Os(N,n.desktop??`data/${I}.desktop.in`),renderDesktop(ue),n.force??!1,`desktop`)),C.icon||ve.warn(`[gjsify flatpak init] No gjsify.flatpak.icon set. Flathub requires a scalable SVG at\n data/icons/hicolor/scalable/apps/${I}.svg`)),trackWrite(writeIfFresh(Os(N,n.flathubJson??`flathub.json`),renderFlathubJson(H),n.force??!1,`flathub.json`))}let fe=ce.filter(n=>/\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/.test(n));if(fe.length>0&&n.format!==!1&&hasOxcDevDep(N))try{await runOxfmt([`--write`,...fe],{cwd:N})}catch(n){if(n instanceof OxcNotFoundError)ve.warn("[gjsify flatpak init] post-format skipped: oxfmt declared but binding not installed. Run `gjsify install` then re-run with --force, or pass --no-format.");else throw n}n.verbose&&(ve.log(`[gjsify flatpak init] kind=${H} runtime=${Y} ${Z} sdk=${X}`),ve.log(`[gjsify flatpak init] command=${re} finish-args=${JSON.stringify(ae)}`))}}});function findDefaultManifest(n){return scanForManifest(n)??`flatpak.json`}function scanForManifest(n){let S=[];try{S=readdirSync(n)}catch{return}for(let C of S)if(C.endsWith(`.json`)&&!(C===`package.json`||C===`tsconfig.json`||C.startsWith(`.`)))try{let S=JSON.parse(readFileSync(Os(n,C),`utf-8`));if(typeof S.id==`string`&&typeof S.runtime==`string`&&Array.isArray(S.modules))return C}catch{}}function readManifestAppId(n){let S=readFileSync(n,`utf-8`),C=JSON.parse(S);if(typeof C.id!=`string`)throw Error(`gjsify flatpak build: ${n} has no string "id" field`);return C.id}async function runFlatpakBuilder(n,S){return runProc(`flatpak-builder`,n,S,{notFoundHint:"flatpak-builder not found. Install via your distro (Fedora: `sudo dnf install flatpak-builder`)."})}async function runFlatpak(n,S){return runProc(`flatpak`,n,S,{notFoundHint:`flatpak not found. Install via your distro and add Flathub: see https://flathub.org/setup.`})}async function runTar(n,S){return runProc(`tar`,n,S,{notFoundHint:`tar not found.`})}async function runProc(n,S,C,N){C.verbose&&ve.log(`[gjsify flatpak] ${n} ${S.join(` `)}`);let{code:F}=await spawnToCompletion(n,S,{completion:`exit`,notFound:()=>Error(`gjsify flatpak: ${N.notFoundHint}`)});if(F!==0)throw Error(`gjsify flatpak: ${n} exited with status ${F}`)}var $I,eL=__esmMin(()=>{ye(),Vl(),Hs(),_P(),$I={command:`build [manifest]`,description:"Build the Flatpak via `flatpak-builder`. Wraps a typical install + export + bundle + tarball pipeline.",builder:n=>n.positional(`manifest`,{description:`Path to the Flatpak manifest (default: first *.json that looks like a manifest in cwd)`,type:`string`,normalize:!0}).option(`build-dir`,{description:`flatpak-builder working directory`,type:`string`,default:`flatpak-build`,normalize:!0}).option(`install`,{description:"After build, run `flatpak-builder --user --install` to install locally",type:`boolean`,default:!1}).option(`repo`,{description:"Export the build into the given OSTree repo (passes `--repo=<dir>` to flatpak-builder)",type:`string`,normalize:!0}).option(`bundle`,{description:"After --repo export, build a single-file bundle (`flatpak build-bundle`) at this path",type:`string`,normalize:!0}).option(`tarball`,{description:`Create a tarball of the build dir (parity with the legacy build-flatpak.sh tarball step)`,type:`string`,normalize:!0}).option(`force-clean`,{description:`Pass --force-clean to flatpak-builder (default true)`,type:`boolean`,default:!0}).option(`sandbox`,{description:`Pass --sandbox to flatpak-builder (default true)`,type:`boolean`,default:!0}).option(`delete-build-dirs`,{description:`Pass --delete-build-dirs to flatpak-builder (default true)`,type:`boolean`,default:!0}).option(`install-deps-from`,{description:"Pass --install-deps-from to flatpak-builder (e.g. `flathub`)",type:`string`}).option(`verbose`,{description:`Print the underlying flatpak-builder invocations`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=Os(S,n.manifest??findDefaultManifest(S));if(!existsSync(C))throw Error(`gjsify flatpak build: manifest ${C} not found`);let N=Os(S,n.buildDir??`flatpak-build`),F=[];if(n.forceClean!==!1&&F.push(`--force-clean`),n.sandbox!==!1&&F.push(`--sandbox`),n.deleteBuildDirs!==!1&&F.push(`--delete-build-dirs`),n.installDepsFrom&&F.push(`--install-deps-from=${n.installDepsFrom}`),existsSync(N)&&rmSync(N,{recursive:!0,force:!0}),await runFlatpakBuilder([...F,N,C],{verbose:n.verbose}),n.install&&await runFlatpakBuilder([`--user`,`--install`,`--force-clean`,N,C],{verbose:n.verbose}),n.repo){let F=Os(S,n.repo);mkdirSync(Ps(F),{recursive:!0}),await runFlatpakBuilder([`--repo=${F}`,`--force-clean`,N,C],{verbose:n.verbose})}if(n.bundle){if(!n.repo)throw Error(`gjsify flatpak build: --bundle requires --repo (the bundle is built from the OSTree repo).`);let N=Os(S,n.bundle);mkdirSync(Ps(N),{recursive:!0}),await runFlatpak([`build-bundle`,Os(S,n.repo),N,readManifestAppId(C)],{verbose:n.verbose})}if(n.tarball){let C=Os(S,n.tarball);mkdirSync(Ps(C),{recursive:!0}),await runTar([`-czf`,C,`-C`,N,`.`],{verbose:n.verbose})}return ve.log(`[gjsify flatpak build] done (${N})`),process.exit(0)}}});function detectLockfile(n){return existsSync(Os(n,`yarn.lock`))?`yarn.lock`:existsSync(Os(n,`package-lock.json`))?`package-lock.json`:`yarn.lock`}var tL,nL=__esmMin(()=>{ye(),_P(),Vl(),Hs(),tL={command:`deps`,description:"Generate Flatpak offline-cache sources from a yarn.lock / package-lock.json (wraps `flatpak-node-generator`).",builder:n=>n.option(`lockfile`,{description:`Path to lockfile (default: yarn.lock or package-lock.json in cwd)`,type:`string`,normalize:!0}).option(`type`,{description:`Lockfile type. Default: detected from filename.`,choices:[`yarn`,`npm`]}).option(`out`,{description:`Output JSON sources file`,type:`string`,default:`flatpak-node-sources.json`,normalize:!0}).option(`xdg-layout`,{description:`Pass --xdg-layout (recommended for Yarn Berry / PnP setups)`,type:`boolean`,default:!0}).option(`electron-node-headers`,{description:`Pass --electron-node-headers`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print the underlying flatpak-node-generator invocation`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=Os(S,n.lockfile??detectLockfile(S));if(!existsSync(C))throw Error(`gjsify flatpak deps: lockfile ${C} not found (use --lockfile to override)`);let N=n.type??(C.endsWith(`package-lock.json`)?`npm`:`yarn`),F=Os(S,n.out??`flatpak-node-sources.json`);mkdirSync(Ps(F),{recursive:!0});let I=[N,C,`-o`,F];n.xdgLayout!==!1&&I.push(`--xdg-layout`),n.electronNodeHeaders&&I.push(`--electron-node-headers`),n.verbose&&ve.log(`[gjsify flatpak deps] flatpak-node-generator ${I.join(` `)}`);let H=await spawnToCompletion(`flatpak-node-generator`,I,{completion:`return`,notFound:()=>Error("gjsify flatpak deps: flatpak-node-generator not found. Install via `pipx install flatpak-node-generator` (see https://github.com/flatpak/flatpak-builder-tools/tree/master/node).")});if(H.code!==0)throw Error(`gjsify flatpak deps: flatpak-node-generator exited with ${describeExit(H)}`);ve.log(`[gjsify flatpak deps] wrote ${F}`)}}});function parseSri(n){if(!n)return null;let S=n.indexOf(`-`);if(S<=0||S===n.length-1)return null;let C=n.slice(0,S),N=n.slice(S+1).replace(/=+$/,``),F=$e.from(N,`base64`).toString(`hex`);return F.length<4?null:{algorithm:C,hex:F}}function parseNpmLike(n){let S=[],C=n,N=C.packages;if(N&&typeof N==`object`){for(let n of Object.values(N))n?.resolved&&n.integrity&&S.push({url:n.resolved,integrity:n.integrity});if(S.length>0)return S}return C.dependencies&&typeof C.dependencies==`object`&&collectV1Deps(C.dependencies,S),S}function collectV1Deps(n,S){for(let C of Object.values(n))C?.resolved&&C.integrity&&S.push({url:C.resolved,integrity:C.integrity}),C?.dependencies&&collectV1Deps(C.dependencies,S)}function parseYarnClassic(n){if(/^__metadata:/m.test(n))throw Error("gjsify flatpak sources: Yarn Berry (v2+) yarn.lock is not supported — its `checksum` is a cache hash, not a tarball SRI. Run `gjsify install` to produce a gjsify-lock.json, or use a classic (v1) yarn.lock.");let S=[],C=0;for(let N of n.split(/\n\s*\n/)){let n=N.match(/^\s+resolved\s+"([^"]+)"/m);if(!n)continue;let F=n[1].replace(/#.*$/,``),I=N.match(/^\s+integrity\s+(\S+)/m);if(!I){C++;continue}S.push({url:F,integrity:I[1]})}return C>0&&ve.warn(`[gjsify flatpak sources] ${C} yarn.lock entr(y/ies) had no integrity (pre-1.x format) and were skipped — re-lock with a modern yarn or use \`gjsify install\`.`),S}function parsePnpm(n){let S=[],C=!1,N=null;for(let F of n.split(`
|
|
1027
1027
|
`)){let n=F.replace(/\r$/,``);if(/^packages:\s*$/.test(n)){C=!0;continue}if(C&&/^[^\s#]/.test(n)&&(C=!1),!C)continue;let I=n.match(/^ {2}(?:'([^']+)'|"([^"]+)"|([^\s#][^:]*)):\s*$/);if(I){N=I[1]??I[2]??I[3]??null;continue}let H=n.match(/resolution:\s*\{([^}]*)\}/);if(H&&N){let n=H[1].match(/integrity:\s*(sha\d+-[A-Za-z0-9+/=]+)/);if(!n)continue;let C=H[1].match(/tarball:\s*([^\s,}]+)/),F=C?C[1]:reconstructNpmTarballUrl(N);F&&S.push({url:F,integrity:n[1]})}}return S}function reconstructNpmTarballUrl(n){let S,C;if(n.startsWith(`/`)){let N=n.slice(1).replace(/_.*$/,``),F=N.lastIndexOf(`/`);if(F<=0)return null;S=N.slice(0,F),C=N.slice(F+1)}else{let N=n.replace(/\(.*\)$/,``),F=N.lastIndexOf(`@`);if(F<=0)return null;S=N.slice(0,F),C=N.slice(F+1)}if(!S||!C||/[@:/]/.test(C))return null;let N=S.slice(S.lastIndexOf(`/`)+1);return`https://registry.npmjs.org/${S}/-/${N}-${C}.tgz`}function detectType(n){let S=n.toLowerCase();return S.endsWith(`pnpm-lock.yaml`)?`pnpm`:S.endsWith(`yarn.lock`)?`yarn`:S.endsWith(`package-lock.json`)?`npm`:`gjsify`}function defaultLockfile(n){for(let S of[`gjsify-lock.json`,`package-lock.json`,`yarn.lock`,`pnpm-lock.yaml`])if(existsSync(js(n,S)))return S;return`gjsify-lock.json`}function parseLockfile(n,S){let C=readFileSync(n,`utf-8`);if(S===`yarn`)return parseYarnClassic(C);if(S===`pnpm`)return parsePnpm(C);let N;try{N=JSON.parse(C)}catch(S){throw Error(`gjsify flatpak sources: ${n} is not valid JSON: ${S.message}`)}return parseNpmLike(N)}function buildModuleSnippet(n,S){return[``,`# Add the generated sources to your app module and point XDG_CACHE_HOME`,`# at the vendored cache before running gjsify offline. Example module:`,`#`,`# {`,`# "name": "my-app",`,`# "buildsystem": "simple",`,`# "build-commands": [`,`# "export XDG_CACHE_HOME=\\"$(pwd)/${S}\\"",`,`# "gjsify install --immutable",`,`# "gjsify build src/main.ts --app gjs --outfile /app/bin/my-app"`,`# ],`,`# "sources": [`,`# { "type": "dir", "path": "." },`,`# "${n}"`,`# ]`,`# }`,``].join(`
|
|
1028
|
-
`)}var
|
|
1028
|
+
`)}var rL,iL,aL=__esmMin(()=>{ye(),Vl(),Hs(),lt(),rL=new Set([`sha256`,`sha512`]),iL={command:`sources`,description:"Generate an offline flatpak-builder `sources` array from any lockfile (gjsify-lock.json / package-lock.json / yarn.lock / pnpm-lock.yaml) for a no-network Flathub build.",builder:n=>n.option(`lockfile`,{description:`Path to the lockfile. Default: the first of gjsify-lock.json / package-lock.json / yarn.lock / pnpm-lock.yaml found in cwd.`,type:`string`,normalize:!0}).option(`type`,{description:`Lockfile format. Default: detected from the filename.`,choices:[`gjsify`,`npm`,`yarn`,`pnpm`]}).option(`out`,{description:`Output JSON sources file`,type:`string`,default:`gjsify-sources.json`,normalize:!0}).option(`cache-root`,{description:`Relative dir the tarballs download into; point XDG_CACHE_HOME here in the build. Tarballs land at <cache-root>/gjsify/tarballs/v1/<algo>/<shard>/<hex>.tgz.`,type:`string`,default:`flatpak-gjsify-cache`}).option(`print-module`,{description:`Also print a ready-to-paste flatpak manifest module snippet to stderr`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=Os(S,n.lockfile??defaultLockfile(S));if(!existsSync(C))throw Error(`gjsify flatpak sources: lockfile ${C} not found. Run \`gjsify install\` (or npm/yarn/pnpm) first, or pass --lockfile.`);let N=n.type??detectType(C),F=parseLockfile(C,N),I=n.cacheRoot??`flatpak-gjsify-cache`,H=new Map,W=0,q=0;for(let{url:n,integrity:S}of F){let C=parseSri(S);if(!C){W++;continue}if(!rL.has(C.algorithm)){q++;continue}let N=`${C.algorithm}:${C.hex}`;if(H.has(N))continue;let F={type:`file`,url:n,dest:`${I}/gjsify/tarballs/v1/${C.algorithm}/${C.hex.slice(0,2)}`,"dest-filename":`${C.hex}.tgz`};C.algorithm===`sha512`?F.sha512=C.hex:F.sha256=C.hex,H.set(N,F)}let Y=[...H.values()].sort((n,S)=>n.url<S.url?-1:+(n.url>S.url)),X=Os(S,n.out??`gjsify-sources.json`);mkdirSync(Ps(X),{recursive:!0}),writeFileSync(X,JSON.stringify(Y,null,2)+`
|
|
1029
1029
|
`),ve.log(`[gjsify flatpak sources] wrote ${X} — ${Y.length} tarball source(s) from ${N} lockfile (${F.length} locked entr${F.length===1?`y`:`ies`})`+(W?`, ${W} without a usable integrity skipped`:``)+(q?`, ${q} non-sha256/512 skipped`:``)),n.printModule&&ve.error(buildModuleSnippet(n.out??`gjsify-sources.json`,I))}}});function renderWorkflow(n){let S=`[${n.branches.map(n=>JSON.stringify(n)).join(`, `)}]`;return`name: Flatpak
|
|
1030
1030
|
|
|
1031
1031
|
on:
|
|
@@ -1054,81 +1054,85 @@ jobs:
|
|
|
1054
1054
|
manifest-path: ${n.manifest}
|
|
1055
1055
|
bundle: ${n.bundle}
|
|
1056
1056
|
cache-key: ${n.cacheKey}
|
|
1057
|
-
`}var
|
|
1057
|
+
`}var oL,sL=__esmMin(()=>{ye(),Vl(),Hs(),nP(),RI(),VI(),GI(),oL={command:`ci`,description:`Scaffold .github/workflows/flatpak.yml using the flathub-infra container + flatpak-builder@v6 action.`,builder:n=>n.option(`manifest`,{description:`Manifest path the workflow points at (default: <app-id>.json)`,type:`string`,normalize:!0}).option(`bundle`,{description:`Bundle filename produced by the action (default: <app-id>.flatpak)`,type:`string`,normalize:!0}).option(`runtime-image`,{description:"Container image override. Default derived from gjsify.flatpak.runtime + runtimeVersion (e.g. `ghcr.io/flathub-infra/flatpak-github-actions:gnome-50`).",type:`string`}).option(`branches`,{description:`Branches the workflow runs on push for (default: main)`,type:`string`,array:!0}).option(`out`,{description:`Output path`,type:`string`,default:`.github/workflows/flatpak.yml`,normalize:!0}).option(`cache-key`,{description:"Override the action `cache-key` (default: `flatpak-builder-${{ github.sha }}`)",type:`string`}).option(`force`,{description:`Overwrite an existing workflow file`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print resolved fields`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=await new Config().forCommand().catch(()=>({})),N=C.flatpak??{},F=readPackageJson(S),I=N.appId??(looksLikeAppId(F.name)?F.name:void 0);if(!I)throw Error(`gjsify flatpak ci: no app id available. Set gjsify.flatpak.appId in package.json or rename the package to a reverse-DNS id.`);let H=n.manifest??`${I}.json`,W=n.bundle??`${I}.flatpak`,q=pickFlatpakBuildKeys(C.ship?.flatpak,N).values,{runtime:Y,runtimeVersion:X}=resolveRuntime(q,{}),Z=n.runtimeImage??N.ciContainer??defaultCiContainer(Y,X),te=n.branches??N.ciBranches??[`main`],ne=n.cacheKey??"flatpak-builder-${{ github.sha }}",re=Os(S,n.out??`.github/workflows/flatpak.yml`);if(existsSync(re)&&!n.force){if(readFileSync(re,`utf-8`)===renderWorkflow({manifest:H,bundle:W,runtimeImage:Z,branches:te,cacheKey:ne})){ve.log(`[gjsify flatpak ci] ${re} already up to date`);return}throw Error(`gjsify flatpak ci: ${re} exists with different content. Pass --force to overwrite.`)}let ie=renderWorkflow({manifest:H,bundle:W,runtimeImage:Z,branches:te,cacheKey:ne});mkdirSync(Ps(re),{recursive:!0}),writeFileSync(re,ie,`utf-8`),n.verbose&&ve.log(`[gjsify flatpak ci] runtime-image=${Z} manifest=${H} bundle=${W}`),ve.log(`[gjsify flatpak ci] wrote ${re}`)}}});function resolveAppId(n,S,C){if(S.appId)return S.appId;try{let n=readPackageJson(C);if(looksLikeAppId(n.name))return n.name}catch{}if(n)return n.replace(/\.json$/,``)}function resolveManifestPath(n,S,C){if(n)return Os(C,n);if(S)return Os(C,`${S}.json`);let N=readdirSync(C).filter(n=>n.endsWith(`.json`)&&!n.startsWith(`package`));if(N.length===1)return Os(C,N[0]);throw Error(`gjsify flatpak check: no manifest path given and could not auto-detect. Pass the manifest as a positional argument.`)}async function runLinter(n,S,C){let N;try{N=await spawnToCompletion(n,S,{completion:`return`,stdio:C?`inherit`:`capture`})}catch(S){let C=S;return C.code===`ENOENT`?ve.error(`[gjsify flatpak check] ${n} not found in PATH.\nInstall via:\n flatpak install -y flathub org.flatpak.Builder\n alias ${n}="flatpak run --command=${n} org.flatpak.Builder"`):ve.error(`[gjsify flatpak check] ${n} failed to spawn: ${C.message}`),!1}let F=N.code===0;return ve.log(`[gjsify flatpak check] ${F?`OK`:`FAIL`}: ${n} ${S.join(` `)}`),!F&&!C&&(N.stdout?.trim()&&ve.log(N.stdout.trimEnd()),N.stderr?.trim()&&ve.error(N.stderr.trimEnd())),F}var cL,lL=__esmMin(()=>{ye(),Vl(),Hs(),_P(),RI(),nP(),cL={command:`check [manifest]`,description:`Run Flathub pre-submission linters: appstreamcli validate + flatpak-builder-lint.`,builder:n=>n.positional(`manifest`,{description:"Path to the Flatpak manifest. Auto-detects `<app-id>.json` if omitted.",type:`string`,normalize:!0}).option(`repo`,{description:"Built ostree-repo path. If given, also runs `flatpak-builder-lint repo`.",type:`string`,normalize:!0}).option(`metainfo`,{description:"MetaInfo XML path. Default: `data/<app-id>.metainfo.xml.in`.",type:`string`,normalize:!0}).option(`appstream`,{description:"Run `appstreamcli validate --strict` (default: true).",type:`boolean`,default:!0}).option(`builder-lint`,{description:"Run `flatpak-builder-lint manifest` (default: true).",type:`boolean`,default:!0}).option(`verbose`,{description:`Stream linter stdout/stderr verbatim.`,type:`boolean`,default:!1}),handler:async n=>{let S=(await new Config().forCommand().catch(()=>({}))).flatpak??{},C=process.cwd(),N=resolveAppId(n.manifest,S,C),F=resolveManifestPath(n.manifest,N,C),I=Os(C,n.metainfo??`data/${N??`unknown`}.metainfo.xml.in`),H=0;if(n.appstream!==!1&&(existsSync(I)?await runLinter(`appstreamcli`,[`validate`,`--strict`,I],n.verbose??!1)||H++:ve.warn(`[gjsify flatpak check] skipping appstreamcli — ${I} not found`)),n.builderLint!==!1){if(!existsSync(F))return ve.error(`[gjsify flatpak check] manifest not found: ${F}`),process.exit(1);await runLinter(`flatpak-builder-lint`,[`manifest`,F],n.verbose??!1)||H++,n.repo&&(await runLinter(`flatpak-builder-lint`,[`repo`,Os(C,n.repo)],n.verbose??!1)||H++)}if(H>0)return ve.error(`\n[gjsify flatpak check] ${H} check(s) failed.`),process.exit(1);ve.log(`[gjsify flatpak check] all checks passed.`)}}});async function resolveLatestTag$1(n,S){try{let{stdout:C}=await uL(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:n});return S&&ve.log(`[gjsify flatpak sync-flathub] resolved latest tag → ${C.trim()}`),C.trim()||null}catch{return null}}async function resolveCommitForTag(n,S,C){try{let{stdout:N}=await uL(`git`,[`rev-list`,`-n`,`1`,S],{cwd:n}),F=N.trim();if(!F)throw Error(`empty rev-list output`);return C&&ve.log(`[gjsify flatpak sync-flathub] resolved ${S} → ${F}`),F}catch(n){throw Error(`[gjsify flatpak sync-flathub] tag ${S} not found locally. Run \`git fetch --tags\` or pass --commit <sha>.\n underlying error: ${n instanceof Error?n.message:String(n)}`)}}function normaliseBranchSegment(n){return n.replace(/^v/,``).replace(/[^A-Za-z0-9._-]/g,`-`)}function flathubCacheRoot(){return js(process.env.XDG_CACHE_HOME||js(homedir(),`.cache`),`gjsify`,`flathub-sync`)}async function ensureClone(n,S,C){if(existsSync(js(n,`.git`))){C&&ve.log(`[gjsify flatpak sync-flathub] reusing clone at ${n}`),await gitInRepo(n,[`fetch`,`origin`],C);let S=await detectDefaultBranch(n,C);await gitInRepo(n,[`checkout`,S],C),await gitInRepo(n,[`reset`,`--hard`,`origin/${S}`],C);return}mkdirSync(Os(n,`..`),{recursive:!0});let N=`https://github.com/${S}.git`;C&&ve.log(`[gjsify flatpak sync-flathub] git clone ${N} ${n}`);try{await uL(`git`,[`clone`,N,n])}catch(n){throw n?.code===`ENOENT`?Error("[gjsify flatpak sync-flathub] `git` not found. Install git from your distro (Fedora: `dnf install git`, Debian: `apt install git`)."):n}}async function detectDefaultBranch(n,S){try{let{stdout:C}=await uL(`git`,[`remote`,`show`,`origin`],{cwd:n}),N=C.match(/HEAD branch: (\S+)/);if(N&&N[1]&&N[1]!==`(unknown)`)return S&&ve.log(`[gjsify flatpak sync-flathub] default branch → ${N[1]}`),N[1]}catch{}return`master`}async function gitInRepo(n,S,C){C&&ve.log(`[gjsify flatpak sync-flathub] git ${S.join(` `)} (in ${n})`);let N=await spawnToCompletion(`git`,S,{completion:`return`,cwd:n,notFound:()=>Error("[gjsify flatpak sync-flathub] `git` not found. Install it from your distro.")});if(N.code!==0)throw Error(`git ${S[0]} exited ${describeExit(N)}`)}async function ghCreate(n,S,C,N,F,I){let H=[`pr`,`create`,`--repo`,S,`--head`,C,`--title`,`Update to ${N}`,`--body`,F];I&&ve.log(`[gjsify flatpak sync-flathub] gh ${H.join(` `)} (in ${n})`);let W=await spawnToCompletion(`gh`,H,{completion:`return`,cwd:n,notFound:()=>Error("[gjsify flatpak sync-flathub] `gh` (GitHub CLI) not found. Install via `dnf install gh` (Fedora), `apt install gh` (Debian/Ubuntu), or `flatpak install -y flathub com.github.cli`.")});if(W.code!==0)throw Error(`gh pr create exited ${describeExit(W)}`)}function editManifest(n,S){let C=JSON.parse(n),N=C.modules??[];if(N.length===0)throw Error(`[gjsify flatpak sync-flathub] manifest has no modules`);let F=N[0].sources??[];if(F.length===0)throw Error(`[gjsify flatpak sync-flathub] modules[0] has no sources`);let I=S.sourceIndex??F.findIndex(n=>n.type===`git`);if(I<0||I>=F.length)throw Error(`[gjsify flatpak sync-flathub] no git source found in modules[0].sources (use --source-index <n>)`);let H=F[I];if(H.type!==`git`)throw Error(`[gjsify flatpak sync-flathub] modules[0].sources[${I}].type is "${H.type}", expected "git"`);H.tag=S.tag,H.commit=S.commit,H[`x-checker-data`]||={type:`git`,"tag-pattern":`^v(\\d+\\.\\d+\\.\\d+)$`,"version-scheme":`semantic`};let W=detectIndent$1(n);return JSON.stringify(C,null,W)+(n.endsWith(`
|
|
1058
1058
|
`)?`
|
|
1059
|
-
`:``)}function detectIndent$1(n){let S=n.match(/^\{\n( +)/);return S?S[1].length:2}var lL,uL,dL=__esmMin(()=>{ye(),Vl(),Hs(),Dm(),Dh(),_P(),Ac(),nP(),LI(),lL=promisify(execFile),uL={command:`sync-flathub`,description:`Update the per-app Flathub tracking-repo manifest to a new git tag + commit. Clones, edits, commits, optionally opens a PR.`,builder:n=>n.version(!1).option(`version`,{description:"Git tag to sync to. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `flathub/<appId>`.",type:`string`}).option(`commit`,{description:"Commit SHA to pin. Default: resolved via `git rev-list -n 1 <version>` in cwd.",type:`string`}).option(`branch`,{description:"Branch name in the flathub-repo. Default: `update-to-<version>`.",type:`string`}).option(`source-index`,{description:"Index into modules[0].sources[] to update (when manifest has multiple sources). Default: first `type: git` source.",type:`number`}).option(`pr`,{description:"After commit + push, open a PR via `gh pr create`. Pass `--no-pr` to skip and stop after push.",type:`boolean`,default:!0}).option(`dry-run`,{description:`Show what would be edited; touch no files, run no git commands.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every git / gh invocation before running.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=(await new Config().forCommand().catch(()=>({}))).flatpak??{},N=n.appId??C.appId??readPackageJson(S).name;if(!N)throw Error(`[gjsify flatpak sync-flathub] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let F=n.flathubRepo??C.flathubRepo??`flathub/${N}`,I=n.version??await resolveLatestTag$1(S,n.verbose);if(!I)throw Error(`[gjsify flatpak sync-flathub] no version resolved — pass --version vX.Y.Z or create a git tag locally.`);let H=n.commit??await resolveCommitForTag(S,I,n.verbose),W=n.branch??`update-to-${normaliseBranchSegment(I)}`;if(ve.log(`[gjsify flatpak sync-flathub] appId=${N}`),ve.log(`[gjsify flatpak sync-flathub] flathubRepo=${F}`),ve.log(`[gjsify flatpak sync-flathub] version=${I}`),ve.log(`[gjsify flatpak sync-flathub] commit=${H}`),ve.log(`[gjsify flatpak sync-flathub] branch=${W}`),n.dryRun){ve.log(`[gjsify flatpak sync-flathub] --dry-run set; not cloning / writing / pushing.`);return}let q=flathubCacheRoot(),Y=js(q,F.replace(`/`,`__`));mkdirSync(q,{recursive:!0}),await ensureClone(Y,F,n.verbose);let X=js(Y,`${N}.json`);if(!existsSync(X))throw Error(`[gjsify flatpak sync-flathub] Flathub manifest not found at ${X} — wrong appId / wrong flathub-repo?`);let Z=readFileSync(X,`utf-8`),te=editManifest(Z,{tag:I,commit:H,sourceIndex:n.sourceIndex});if(te===Z){ve.log(`[gjsify flatpak sync-flathub] manifest already at ${I} — nothing to do.`);return}if(writeFileSync(X,te,`utf-8`),ve.log(`[gjsify flatpak sync-flathub] manifest patched at ${X}`),await gitInRepo(Y,[`checkout`,`-B`,W],n.verbose),await gitInRepo(Y,[`add`,`.`],n.verbose),await gitInRepo(Y,[`commit`,`-m`,`Update to ${I}`],n.verbose),n.pr===!1){ve.log(`[gjsify flatpak sync-flathub] --no-pr set; branch ${W} committed locally in ${Y}.`);return}await gitInRepo(Y,[`push`,`-u`,`origin`,W,`--force-with-lease`],n.verbose),await ghCreate(Y,F,W,I,`Auto-generated by \`gjsify flatpak sync-flathub\`.\n\n- Version: \`${I}\`\n- Commit: \`${H}\`\n`,n.verbose)}},__name$1(resolveLatestTag$1,`resolveLatestTag`),__name$1(detectIndent$1,`detectIndent`)});async function loadFlathubSource(n,S){let C;if(n.against){if(!existsSync(n.against))throw Error(`[gjsify flatpak diff] --against path ${n.against} does not exist`);C=readFileSync(n.against,`utf-8`)}else C=await fetchFlathubManifest(n.flathubRepo,n.appId,n.verbose);let N;try{N=JSON.parse(C)}catch(n){throw Error(`[gjsify flatpak diff] failed to parse Flathub manifest as JSON: ${n.message}`)}let F=(N.modules??[])[0]?.sources??[];if(F.length===0)return null;let I=S??F.findIndex(n=>n?.type===`git`);return I<0||I>=F.length?null:F[I]??null}async function fetchFlathubManifest(n,S,C){for(let N of[`master`,`main`]){let F=`https://raw.githubusercontent.com/${n}/${N}/${S}.json`;C&&ve.log(`[gjsify flatpak diff] fetch ${F}`);try{let n=await fetch(F);if(n.ok)return await n.text();C&&ve.log(`[gjsify flatpak diff] ${N} → HTTP ${n.status}`)}catch(n){C&&ve.log(`[gjsify flatpak diff] ${N} fetch error: ${n.message}`)}}throw Error(`[gjsify flatpak diff] could not fetch flathub manifest from ${n} on master or main`)}async function resolveLatestTag(n,S){try{let{stdout:C}=await fL(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:n}),N=C.trim();return S&&ve.log(`[gjsify flatpak diff] local latest tag → ${N}`),N||null}catch{return null}}var fL,pL,mL=__esmMin(()=>{ye(),Vl(),Dh(),Ac(),nP(),LI(),fL=promisify(execFile),pL={command:`diff`,description:`Compare the per-app Flathub tracking-repo manifest against the local git state and report version / commit drift.`,builder:n=>n.version(!1).option(`version`,{description:"Local version to compare against. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `gjsify.flatpak.flathubRepo` or `flathub/<appId>`.",type:`string`}).option(`against`,{description:`Read the Flathub manifest from a local file instead of fetching it. Useful in CI or offline.`,type:`string`}).option(`detail`,{description:`Also print the full Flathub manifest source entry alongside the resolved local version.`,type:`boolean`,default:!1}).option(`source-index`,{description:`Index into modules[0].sources[] to inspect (when the manifest has multiple sources).`,type:`number`}).option(`verbose`,{description:`Echo fetch URL + resolved values.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=(await new Config().forCommand().catch(()=>({}))).flatpak??{},N=n.appId??C.appId??readPackageJson(S).name;if(!N)throw Error(`[gjsify flatpak diff] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let F=n.flathubRepo??C.flathubRepo??`flathub/${N}`,I=n.version??await resolveLatestTag(S,n.verbose),H=await loadFlathubSource({appId:N,flathubRepo:F,against:n.against,verbose:n.verbose},n.sourceIndex),W=H?.tag,q=H?.commit;if(ve.log(`[gjsify flatpak diff] appId=${N}`),ve.log(`[gjsify flatpak diff] flathubRepo=${F}`),ve.log(`[gjsify flatpak diff] flathub: tag=${W??`(missing)`} commit=${q??`(missing)`}`),ve.log(`[gjsify flatpak diff] local: tag=${I??`(none)`}`),n.detail&&H&&(ve.log(`[gjsify flatpak diff] flathub manifest source:`),ve.log(JSON.stringify(H,null,2))),!I){ve.warn("[gjsify flatpak diff] no local git tag found — cut a release (`git tag vX.Y.Z`) or pass --version vX.Y.Z to compare against an explicit value.");return}if(!W)return ve.warn("[gjsify flatpak diff] flathub manifest has no `tag` field on the inspected source."),process.exit(1);if(W===I){ve.log(`✅ in sync (${I})`);return}ve.log(`❌ drift detected — flathub=${W} vs local=${I}`),ve.log(` run \`gjsify flatpak sync-flathub --version ${I}\` to update the Flathub manifest.`),process.exit(1)}}});function resolveCliEntry(){return Os(Os(Ps(fileURLToPath(import.meta.url)),`..`,`..`),`index.js`)}async function runNode(n,S){let C=await spawnToCompletion(`node`,n,{completion:`return`,cwd:S});if(C.code!==0)throw Error(`sub-command exited with ${describeExit(C)}: node ${n.join(` `)}`)}var hL,gL,_L=__esmMin(()=>{ye(),Dh(),_P(),Ac(),gn(),Hs(),hL=promisify(execFile),gL={command:`release <version>`,description:"Cut a release end-to-end: regenerate Flathub assets, run linters, create + push the git tag, then open the Flathub PR. Each step delegates to the equivalent `gjsify flatpak <sub>` command.",builder:n=>n.version(!1).positional(`version`,{description:"Release tag, e.g. `v0.6.6`.",type:`string`,demandOption:!0}).option(`skip-init`,{description:"Skip the `flatpak init --force` regen step.",type:`boolean`,default:!1}).option(`skip-check`,{description:"Skip the `flatpak check` linter step.",type:`boolean`,default:!1}).option(`skip-tag`,{description:"Skip the `git tag` + `git push --tags` step (use when the tag was already created out-of-band).",type:`boolean`,default:!1}).option(`push-tag`,{description:`Push the created tag after creating it. Default: true.`,type:`boolean`,default:!0}).option(`flathub-repo`,{description:`Flathub tracking-repo override forwarded to sync-flathub.`,type:`string`}).option(`dry-run`,{description:`Print each step that would run without executing any of them.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every sub-command invocation.`,type:`boolean`,default:!1}),handler:async n=>{let S=typeof n.version==`string`?n.version.trim():``;if(!S)throw Error(`[gjsify flatpak release] missing <version> positional`);let C=resolveCliEntry(),N=process.cwd(),F=[];n.skipInit||F.push({name:`init`,args:[C,`flatpak`,`init`,`--force`]}),n.skipCheck||F.push({name:`check`,args:[C,`flatpak`,`check`]});let I=[C,`flatpak`,`sync-flathub`,`--version`,S];if(n.flathubRepo&&I.push(`--flathub-repo`,n.flathubRepo),n.verbose&&I.push(`--verbose`),ve.log(`[gjsify flatpak release] starting release of ${S}`),n.dryRun){ve.log(`[gjsify flatpak release] --dry-run set; printing plan only:`);for(let n of F)ve.log(` · ${n.name}: node ${n.args.join(` `)}`);n.skipTag||ve.log(` · tag: git tag ${S}${n.pushTag===!1?``:` && git push origin `+S}`),ve.log(` · sync: node ${I.join(` `)}`);return}for(let S of F)n.verbose&&ve.log(`[gjsify flatpak release] step ${S.name}: node ${S.args.join(` `)}`),await runNode(S.args,N),ve.log(`[gjsify flatpak release] ${S.name} ✔`);if(!n.skipTag){n.verbose&&ve.log(`[gjsify flatpak release] git tag ${S}`);try{await hL(`git`,[`tag`,S],{cwd:N}),ve.log(`[gjsify flatpak release] tag ${S} created`)}catch(n){throw Error(`[gjsify flatpak release] git tag failed (${n.message}). If the tag already exists, re-run with --skip-tag.`)}n.pushTag!==!1&&(n.verbose&&ve.log(`[gjsify flatpak release] git push origin ${S}`),await hL(`git`,[`push`,`origin`,S],{cwd:N}),ve.log(`[gjsify flatpak release] tag pushed`))}n.verbose&&ve.log(`[gjsify flatpak release] sync: node ${I.join(` `)}`),await runNode(I,N),ve.log(`[gjsify flatpak release] ✅ release ${S} complete`)}}}),vL,yL=__esmMin(()=>{ZI(),$I(),tL(),iL(),oL(),cL(),dL(),mL(),_L(),vL={command:`flatpak <subcommand>`,description:`Flatpak toolchain: init/build/deps/sources/ci/check/sync-flathub/diff/release subcommands for shipping GJS apps and CLIs as Flatpaks.`,builder:n=>n.command(XI.command,XI.description,XI.builder,XI.handler).command(QI.command,QI.description,QI.builder,QI.handler).command(eL.command,eL.description,eL.builder,eL.handler).command(rL.command,rL.description,rL.builder,rL.handler).command(aL.command,aL.description,aL.builder,aL.handler).command(sL.command,sL.description,sL.builder,sL.handler).command(uL.command,uL.description,uL.builder,uL.handler).command(pL.command,pL.description,pL.builder,pL.handler).command(gL.command,gL.description,gL.builder,gL.handler).demandCommand(1).strict()}});function concatBytes(n){let S=0;for(let C of n)S+=C.byteLength;let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.byteLength;return C}function encodeUtf8(n){return new TextEncoder().encode(n)}var bL=__esmMin(()=>{});function createArArchive(n){let S=[encodeUtf8(xL)];for(let C of n)S.push(buildMemberHeader(C)),S.push(C.data),C.data.byteLength%2==1&&S.push(encodeUtf8(`
|
|
1059
|
+
`:``)}function detectIndent$1(n){let S=n.match(/^\{\n( +)/);return S?S[1].length:2}var uL,dL,fL=__esmMin(()=>{ye(),Vl(),Hs(),Dm(),Dh(),_P(),Ac(),nP(),RI(),uL=promisify(execFile),dL={command:`sync-flathub`,description:`Update the per-app Flathub tracking-repo manifest to a new git tag + commit. Clones, edits, commits, optionally opens a PR.`,builder:n=>n.version(!1).option(`version`,{description:"Git tag to sync to. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `flathub/<appId>`.",type:`string`}).option(`commit`,{description:"Commit SHA to pin. Default: resolved via `git rev-list -n 1 <version>` in cwd.",type:`string`}).option(`branch`,{description:"Branch name in the flathub-repo. Default: `update-to-<version>`.",type:`string`}).option(`source-index`,{description:"Index into modules[0].sources[] to update (when manifest has multiple sources). Default: first `type: git` source.",type:`number`}).option(`pr`,{description:"After commit + push, open a PR via `gh pr create`. Pass `--no-pr` to skip and stop after push.",type:`boolean`,default:!0}).option(`dry-run`,{description:`Show what would be edited; touch no files, run no git commands.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every git / gh invocation before running.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=(await new Config().forCommand().catch(()=>({}))).flatpak??{},N=n.appId??C.appId??readPackageJson(S).name;if(!N)throw Error(`[gjsify flatpak sync-flathub] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let F=n.flathubRepo??C.flathubRepo??`flathub/${N}`,I=n.version??await resolveLatestTag$1(S,n.verbose);if(!I)throw Error(`[gjsify flatpak sync-flathub] no version resolved — pass --version vX.Y.Z or create a git tag locally.`);let H=n.commit??await resolveCommitForTag(S,I,n.verbose),W=n.branch??`update-to-${normaliseBranchSegment(I)}`;if(ve.log(`[gjsify flatpak sync-flathub] appId=${N}`),ve.log(`[gjsify flatpak sync-flathub] flathubRepo=${F}`),ve.log(`[gjsify flatpak sync-flathub] version=${I}`),ve.log(`[gjsify flatpak sync-flathub] commit=${H}`),ve.log(`[gjsify flatpak sync-flathub] branch=${W}`),n.dryRun){ve.log(`[gjsify flatpak sync-flathub] --dry-run set; not cloning / writing / pushing.`);return}let q=flathubCacheRoot(),Y=js(q,F.replace(`/`,`__`));mkdirSync(q,{recursive:!0}),await ensureClone(Y,F,n.verbose);let X=js(Y,`${N}.json`);if(!existsSync(X))throw Error(`[gjsify flatpak sync-flathub] Flathub manifest not found at ${X} — wrong appId / wrong flathub-repo?`);let Z=readFileSync(X,`utf-8`),te=editManifest(Z,{tag:I,commit:H,sourceIndex:n.sourceIndex});if(te===Z){ve.log(`[gjsify flatpak sync-flathub] manifest already at ${I} — nothing to do.`);return}if(writeFileSync(X,te,`utf-8`),ve.log(`[gjsify flatpak sync-flathub] manifest patched at ${X}`),await gitInRepo(Y,[`checkout`,`-B`,W],n.verbose),await gitInRepo(Y,[`add`,`.`],n.verbose),await gitInRepo(Y,[`commit`,`-m`,`Update to ${I}`],n.verbose),n.pr===!1){ve.log(`[gjsify flatpak sync-flathub] --no-pr set; branch ${W} committed locally in ${Y}.`);return}await gitInRepo(Y,[`push`,`-u`,`origin`,W,`--force-with-lease`],n.verbose),await ghCreate(Y,F,W,I,`Auto-generated by \`gjsify flatpak sync-flathub\`.\n\n- Version: \`${I}\`\n- Commit: \`${H}\`\n`,n.verbose)}},__name$1(resolveLatestTag$1,`resolveLatestTag`),__name$1(detectIndent$1,`detectIndent`)});async function loadFlathubSource(n,S){let C;if(n.against){if(!existsSync(n.against))throw Error(`[gjsify flatpak diff] --against path ${n.against} does not exist`);C=readFileSync(n.against,`utf-8`)}else C=await fetchFlathubManifest(n.flathubRepo,n.appId,n.verbose);let N;try{N=JSON.parse(C)}catch(n){throw Error(`[gjsify flatpak diff] failed to parse Flathub manifest as JSON: ${n.message}`)}let F=(N.modules??[])[0]?.sources??[];if(F.length===0)return null;let I=S??F.findIndex(n=>n?.type===`git`);return I<0||I>=F.length?null:F[I]??null}async function fetchFlathubManifest(n,S,C){for(let N of[`master`,`main`]){let F=`https://raw.githubusercontent.com/${n}/${N}/${S}.json`;C&&ve.log(`[gjsify flatpak diff] fetch ${F}`);try{let n=await fetch(F);if(n.ok)return await n.text();C&&ve.log(`[gjsify flatpak diff] ${N} → HTTP ${n.status}`)}catch(n){C&&ve.log(`[gjsify flatpak diff] ${N} fetch error: ${n.message}`)}}throw Error(`[gjsify flatpak diff] could not fetch flathub manifest from ${n} on master or main`)}async function resolveLatestTag(n,S){try{let{stdout:C}=await pL(`git`,[`describe`,`--tags`,`--abbrev=0`],{cwd:n}),N=C.trim();return S&&ve.log(`[gjsify flatpak diff] local latest tag → ${N}`),N||null}catch{return null}}var pL,mL,hL=__esmMin(()=>{ye(),Vl(),Dh(),Ac(),nP(),RI(),pL=promisify(execFile),mL={command:`diff`,description:`Compare the per-app Flathub tracking-repo manifest against the local git state and report version / commit drift.`,builder:n=>n.version(!1).option(`version`,{description:"Local version to compare against. Default: `git describe --tags --abbrev=0` in cwd.",type:`string`}).option(`app-id`,{description:"Reverse-DNS app id. Default: `gjsify.flatpak.appId`.",type:`string`}).option(`flathub-repo`,{description:"Flathub tracking-repo (owner/name). Default: `gjsify.flatpak.flathubRepo` or `flathub/<appId>`.",type:`string`}).option(`against`,{description:`Read the Flathub manifest from a local file instead of fetching it. Useful in CI or offline.`,type:`string`}).option(`detail`,{description:`Also print the full Flathub manifest source entry alongside the resolved local version.`,type:`boolean`,default:!1}).option(`source-index`,{description:`Index into modules[0].sources[] to inspect (when the manifest has multiple sources).`,type:`number`}).option(`verbose`,{description:`Echo fetch URL + resolved values.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=(await new Config().forCommand().catch(()=>({}))).flatpak??{},N=n.appId??C.appId??readPackageJson(S).name;if(!N)throw Error(`[gjsify flatpak diff] no app id available — pass --app-id or set gjsify.flatpak.appId.`);let F=n.flathubRepo??C.flathubRepo??`flathub/${N}`,I=n.version??await resolveLatestTag(S,n.verbose),H=await loadFlathubSource({appId:N,flathubRepo:F,against:n.against,verbose:n.verbose},n.sourceIndex),W=H?.tag,q=H?.commit;if(ve.log(`[gjsify flatpak diff] appId=${N}`),ve.log(`[gjsify flatpak diff] flathubRepo=${F}`),ve.log(`[gjsify flatpak diff] flathub: tag=${W??`(missing)`} commit=${q??`(missing)`}`),ve.log(`[gjsify flatpak diff] local: tag=${I??`(none)`}`),n.detail&&H&&(ve.log(`[gjsify flatpak diff] flathub manifest source:`),ve.log(JSON.stringify(H,null,2))),!I){ve.warn("[gjsify flatpak diff] no local git tag found — cut a release (`git tag vX.Y.Z`) or pass --version vX.Y.Z to compare against an explicit value.");return}if(!W)return ve.warn("[gjsify flatpak diff] flathub manifest has no `tag` field on the inspected source."),process.exit(1);if(W===I){ve.log(`✅ in sync (${I})`);return}ve.log(`❌ drift detected — flathub=${W} vs local=${I}`),ve.log(` run \`gjsify flatpak sync-flathub --version ${I}\` to update the Flathub manifest.`),process.exit(1)}}});function resolveCliEntry(){return Os(Os(Ps(fileURLToPath(import.meta.url)),`..`,`..`),`index.js`)}async function runNode(n,S){let C=await spawnToCompletion(`node`,n,{completion:`return`,cwd:S});if(C.code!==0)throw Error(`sub-command exited with ${describeExit(C)}: node ${n.join(` `)}`)}var gL,_L,vL=__esmMin(()=>{ye(),Dh(),_P(),Ac(),gn(),Hs(),gL=promisify(execFile),_L={command:`release <version>`,description:"Cut a release end-to-end: regenerate Flathub assets, run linters, create + push the git tag, then open the Flathub PR. Each step delegates to the equivalent `gjsify flatpak <sub>` command.",builder:n=>n.version(!1).positional(`version`,{description:"Release tag, e.g. `v0.6.6`.",type:`string`,demandOption:!0}).option(`skip-init`,{description:"Skip the `flatpak init --force` regen step.",type:`boolean`,default:!1}).option(`skip-check`,{description:"Skip the `flatpak check` linter step.",type:`boolean`,default:!1}).option(`skip-tag`,{description:"Skip the `git tag` + `git push --tags` step (use when the tag was already created out-of-band).",type:`boolean`,default:!1}).option(`push-tag`,{description:`Push the created tag after creating it. Default: true.`,type:`boolean`,default:!0}).option(`flathub-repo`,{description:`Flathub tracking-repo override forwarded to sync-flathub.`,type:`string`}).option(`dry-run`,{description:`Print each step that would run without executing any of them.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo every sub-command invocation.`,type:`boolean`,default:!1}),handler:async n=>{let S=typeof n.version==`string`?n.version.trim():``;if(!S)throw Error(`[gjsify flatpak release] missing <version> positional`);let C=resolveCliEntry(),N=process.cwd(),F=[];n.skipInit||F.push({name:`init`,args:[C,`flatpak`,`init`,`--force`]}),n.skipCheck||F.push({name:`check`,args:[C,`flatpak`,`check`]});let I=[C,`flatpak`,`sync-flathub`,`--version`,S];if(n.flathubRepo&&I.push(`--flathub-repo`,n.flathubRepo),n.verbose&&I.push(`--verbose`),ve.log(`[gjsify flatpak release] starting release of ${S}`),n.dryRun){ve.log(`[gjsify flatpak release] --dry-run set; printing plan only:`);for(let n of F)ve.log(` · ${n.name}: node ${n.args.join(` `)}`);n.skipTag||ve.log(` · tag: git tag ${S}${n.pushTag===!1?``:` && git push origin `+S}`),ve.log(` · sync: node ${I.join(` `)}`);return}for(let S of F)n.verbose&&ve.log(`[gjsify flatpak release] step ${S.name}: node ${S.args.join(` `)}`),await runNode(S.args,N),ve.log(`[gjsify flatpak release] ${S.name} ✔`);if(!n.skipTag){n.verbose&&ve.log(`[gjsify flatpak release] git tag ${S}`);try{await gL(`git`,[`tag`,S],{cwd:N}),ve.log(`[gjsify flatpak release] tag ${S} created`)}catch(n){throw Error(`[gjsify flatpak release] git tag failed (${n.message}). If the tag already exists, re-run with --skip-tag.`)}n.pushTag!==!1&&(n.verbose&&ve.log(`[gjsify flatpak release] git push origin ${S}`),await gL(`git`,[`push`,`origin`,S],{cwd:N}),ve.log(`[gjsify flatpak release] tag pushed`))}n.verbose&&ve.log(`[gjsify flatpak release] sync: node ${I.join(` `)}`),await runNode(I,N),ve.log(`[gjsify flatpak release] ✅ release ${S} complete`)}}}),yL,bL=__esmMin(()=>{QI(),eL(),nL(),aL(),sL(),lL(),fL(),hL(),vL(),yL={command:`flatpak <subcommand>`,description:`Flatpak toolchain: init/build/deps/sources/ci/check/sync-flathub/diff/release subcommands for shipping GJS apps and CLIs as Flatpaks.`,builder:n=>n.command(ZI.command,ZI.description,ZI.builder,ZI.handler).command($I.command,$I.description,$I.builder,$I.handler).command(tL.command,tL.description,tL.builder,tL.handler).command(iL.command,iL.description,iL.builder,iL.handler).command(oL.command,oL.description,oL.builder,oL.handler).command(cL.command,cL.description,cL.builder,cL.handler).command(dL.command,dL.description,dL.builder,dL.handler).command(mL.command,mL.description,mL.builder,mL.handler).command(_L.command,_L.description,_L.builder,_L.handler).demandCommand(1).strict()}});function concatBytes(n){let S=0;for(let C of n)S+=C.byteLength;let C=new Uint8Array(S),N=0;for(let S of n)C.set(S,N),N+=S.byteLength;return C}function encodeUtf8(n){return new TextEncoder().encode(n)}var xL=__esmMin(()=>{});function createArArchive(n){let S=[encodeUtf8(SL)];for(let C of n)S.push(buildMemberHeader(C)),S.push(C.data),C.data.byteLength%2==1&&S.push(encodeUtf8(`
|
|
1060
1060
|
`));return concatBytes(S)}function buildMemberHeader(n){let S=pad(n.name,16)+pad(String(n.mtime??0),12)+pad(`0`,6)+pad(`0`,6)+pad((n.mode??33188).toString(8),8)+pad(String(n.data.byteLength),10)+`\`
|
|
1061
|
-
`;if(S.length!==
|
|
1062
|
-
`,
|
|
1061
|
+
`;if(S.length!==CL)throw Error(`gjsify ship: internal error — ar header is ${S.length} bytes, expected ${CL}.`);return encodeUtf8(S)}function pad(n,S){if(n.length>S)throw Error(`gjsify ship: ar header field "${n}" does not fit in ${S} bytes.`);return n.padEnd(S,` `)}var SL,CL,wL=__esmMin(()=>{xL(),SL=`!<arch>
|
|
1062
|
+
`,CL=60});function warnAboutGjsFloor(n,S){return!OL[n]||compareVersions(S,`1.82.3`)<=0||compareVersions(S,`1.88.1`)===0?[]:[`gjsify ship: \`Depends: gjs (>= ${S})\` is not satisfiable on Debian stable — ${DL}. The package installs on forky/sid and on distributions with a newer GJS. Set \`gjsify.ship.minGjsVersion\` if this bundle genuinely runs on an older GJS; do NOT lower it to make apt happy, because the result is an install that succeeds and an app that does not start.`]}function warnAboutNodeFloor(n,S){return!AL[n]||compareVersions(S,`22`)<=0?[]:[`gjsify ship: \`Depends: nodejs (>= ${S})\` is not satisfiable on any current DEB stable/LTS — ${kL}. The package installs on forky/sid and on distributions with a newer Node. Set \`gjsify.ship.minNodeVersion\` if this bundle genuinely runs on an older Node; do NOT lower it to make apt happy, because the result is an install that succeeds and an app that dies on the first syntax or API the older interpreter does not have.`]}function compareVersions(n,S){let C=n.split(`.`).map(Number),N=S.split(`.`).map(Number);for(let n=0;n<Math.max(C.length,N.length);n++){let S=(C[n]??0)-(N[n]??0);if(S!==0)return S}return 0}function deriveDepends(n,S){let C=S.interpreter===`node`?[`${TL[n]} >= ${S.minNodeVersion??`24`}`]:[`gjs >= ${S.minGjsVersion??`1.86`}`],N=[],F=new Set;for(let n of S.bundledTypelibs??[]){let S=/([A-Za-z0-9]+)-([\d.]+)\.typelib$/.exec(n);S&&(F.add(`${S[1]}-${S[2]}`),F.add(S[1]))}for(let I of[...new Set(S.namespaces)].sort()){if(ML.test(I)||F.has(I))continue;let H=lookupTypelib(I,S.typelibPackages);if(H===void 0){N.push(I);continue}C.push(H[n])}if(N.length>0)throw Error(`gjsify ship: the bundle imports ${N.map(n=>`gi://${n.split(`-`)[0]}`).join(`, `)}, and no ${n} package is known to ship ${N.length>1?`those typelibs`:`that typelib`}. An undeclared runtime dependency does not fail here — it fails on a user's machine after the download. Fill the gap in package.json:
|
|
1063
1063
|
"gjsify": { "ship": { "typelibPackages": { ${JSON.stringify(N[0])}: { "deb": "gir1.2-…", "rpm": "…" } } } }
|
|
1064
|
-
and please contribute the mapping back to \`utils/ship/depends.ts\` so the next project does not have to. (\`gjsify.ship.depends.<format>\` is for dependencies that are not typelibs at all — it appends, and deliberately does not silence this.)`);return S.hasIcons&&C.push(`hicolor-icon-theme`),S.hasSchemas&&C.push(
|
|
1064
|
+
and please contribute the mapping back to \`utils/ship/depends.ts\` so the next project does not have to. (\`gjsify.ship.depends.<format>\` is for dependencies that are not typelibs at all — it appends, and deliberately does not silence this.)`);return S.hasIcons&&C.push(`hicolor-icon-theme`),S.hasSchemas&&C.push(EL[n]),C.push(...S.extra),[...new Set(C)]}function lookupTypelib(n,S={}){let C={...jL,...S},N=C[n];if(N!==void 0)return N;if(n.includes(`-`))return;let F=Object.keys(C).filter(S=>S.startsWith(`${n}-`));if(F.length===1)return C[F[0]]}function parseDepend(n){let S=/^(\S+)\s*(>=|<=|=|>|<)\s*(\S+)$/.exec(n);return S?{name:S[1],relation:S[2],version:S[3]}:{name:n.trim()}}function formatDebDepend(n){let S=parseDepend(n);if(S.relation===void 0)return S.name;let C=S.relation===`>`?`>>`:S.relation===`<`?`<<`:S.relation;return`${S.name} (${C} ${S.version})`}var TL,EL,DL,OL,kL,AL,jL,ML,NL=__esmMin(()=>{TL={deb:`nodejs`,rpm:`nodejs(engine)`},EL={deb:`libglib2.0-bin`,rpm:`glib2`},DL=`trixie ships 1.82.3 and forky 1.88.1; 1.84 and 1.86 were skipped`,OL={deb:!0,rpm:!1},kL=`trixie ships 20, forky 24; Ubuntu 24.04 LTS ships 18 and 26.04 LTS 22`,AL={deb:!0,rpm:!1},jL={"GLib-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"GObject-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"Gio-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"GioUnix-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"GModule-2.0":{deb:`gir1.2-glib-2.0`,rpm:`glib2`},"Gtk-4.0":{deb:`gir1.2-gtk-4.0`,rpm:`gtk4`},"Gdk-4.0":{deb:`gir1.2-gtk-4.0`,rpm:`gtk4`},"Gsk-4.0":{deb:`gir1.2-gtk-4.0`,rpm:`gtk4`},"Adw-1":{deb:`gir1.2-adw-1`,rpm:`libadwaita`},"GdkPixbuf-2.0":{deb:`gir1.2-gdkpixbuf-2.0`,rpm:`gdk-pixbuf2`},"Pango-1.0":{deb:`gir1.2-pango-1.0`,rpm:`pango`},"PangoCairo-1.0":{deb:`gir1.2-pango-1.0`,rpm:`pango`},"Graphene-1.0":{deb:`gir1.2-graphene-1.0`,rpm:`graphene`},"cairo-1.0":{deb:`gir1.2-freedesktop`,rpm:`gobject-introspection`},"GtkSource-5":{deb:`gir1.2-gtksource-5`,rpm:`gtksourceview5`},"WebKit-6.0":{deb:`gir1.2-webkit-6.0`,rpm:`webkitgtk6.0`},"Soup-3.0":{deb:`gir1.2-soup-3.0`,rpm:`libsoup3`},"Json-1.0":{deb:`gir1.2-json-1.0`,rpm:`json-glib`},"Gst-1.0":{deb:`gir1.2-gstreamer-1.0`,rpm:`gstreamer1`},"Secret-1":{deb:`gir1.2-secret-1`,rpm:`libsecret`},"Notify-0.7":{deb:`gir1.2-notify-0.7`,rpm:`libnotify`},"Vte-3.91":{deb:`gir1.2-vte-3.91`,rpm:`vte291-gtk4`},"Manette-0.2":{deb:`gir1.2-manette-0.2`,rpm:`libmanette`},"Gda-6.0":{deb:`gir1.2-gda-6.0`,rpm:`libgda`}},ML=/^Gjsify[A-Z]/});async function gzipDeterministic(n){let S=await gzip(n);if(S.byteLength<10||S[0]!==31||S[1]!==139)throw Error(`gjsify ship: internal error — gzip did not produce a gzip stream.`);return S[4]=0,S[5]=0,S[6]=0,S[7]=0,S[9]=3,S}var PL=__esmMin(()=>{WP()});function isUnder(n,S){return n.startsWith(`${S}/`)}var FL,IL=__esmMin(()=>{FL={applications:`share/applications`,icons:`share/icons/hicolor`,schemas:`share/glib-2.0/schemas`,mime:`share/mime/packages`,metainfo:`share/metainfo`,locale:`share/locale`,fonts:`share/fonts`}});function cacheRefreshCommands(n,S){let C=[];return n.hasDesktopEntry&&C.push({probe:`update-desktop-database`,run:`update-desktop-database -q ${S}/${FL.applications}`}),n.hasIcons&&C.push({probe:`gtk-update-icon-cache`,run:`gtk-update-icon-cache -q -t -f ${S}/${FL.icons}`}),n.hasMimeTypes&&C.push({probe:`update-mime-database`,run:`update-mime-database ${S}/share/mime`}),n.hasSchemas&&C.push({probe:`glib-compile-schemas`,run:`glib-compile-schemas ${S}/${FL.schemas}`}),C.map(({probe:n,run:S})=>`if command -v ${n} >/dev/null 2>&1; then ${S} || true; fi`)}function renderDebScripts(n,S){let C=cacheRefreshCommands(n,S);if(C.length===0)return{};let N=C.map(n=>` ${n}`).join(`
|
|
1065
1065
|
`);return{postinst:[`#!/bin/sh`,`set -e`,`if [ "$1" = "configure" ]; then`,N,`fi`,``].join(`
|
|
1066
1066
|
`),postrm:[`#!/bin/sh`,`set -e`,`if [ "$1" = "remove" ]; then`,N,`fi`,``].join(`
|
|
1067
1067
|
`)}}function renderRpmScriptlets(n,S){let C=cacheRefreshCommands(n,S);if(C.length===0)return{};let N=`${C.join(`
|
|
1068
|
-
`)}\n`;return{post:N,postun:N}}var
|
|
1069
|
-
$`,64,`ascii`),ae.writeUInt32LE(
|
|
1070
|
-
`)}\n\t</array>`}function renderInfoPlist(n,S){let C=assertPlistText(n.name,`CFBundleName`,`gjsify.ship.name`),N=assertPlistText(n.binaryName,`CFBundleExecutable`,`gjsify.ship.binaryName`),F=assertPlistText(n.appId,`CFBundleIdentifier`,`gjsify.ship.appId`);return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<plist version="1.0">`,`<dict>`,...S===void 0?[]:[stringEntry(`ATSApplicationFontsPath`,S)],stringEntry(`CFBundleDevelopmentRegion`,`en`),stringEntry(`CFBundleDisplayName`,C),stringEntry(`CFBundleExecutable`,N),stringEntry(`CFBundleIdentifier`,F),stringEntry(`CFBundleInfoDictionaryVersion`,`6.0`),stringEntry(`CFBundleName`,C),stringEntry(`CFBundlePackageType`,
|
|
1071
|
-
`)}function renderPkgInfo(){return`${
|
|
1068
|
+
`)}\n`;return{post:N,postun:N}}var LL=__esmMin(()=>{IL()});function movImm32(n,S,C){let N={eax:184,ecx:185,edx:186,r8d:184,r9d:185,r14d:190}[S];(S===`r8d`||S===`r9d`||S===`r14d`)&&n.push(65),n.push(N);let F=Buffer.alloc(4);F.writeInt32LE(C|0),n.push(...F)}function movStackDword(n,S,C){n.push(199,132,36);let N=Buffer.alloc(4);N.writeInt32LE(S),n.push(...N);let F=Buffer.alloc(4);F.writeInt32LE(C|0),n.push(...F)}function movStackFromReg(n,S,C){let N={rax:132,rbx:156,rsi:180,rdi:188}[S];n.push(72,137,N,36);let F=Buffer.alloc(4);F.writeInt32LE(C),n.push(...F)}function movRaxFromStack(n,S){n.push(72,139,132,36);let C=Buffer.alloc(4);C.writeInt32LE(S),n.push(...C)}function leaStack(n,S,C){let N={rax:132,rcx:140,rdx:148,rdi:188,r9:140}[S];n.push(S===`r9`?76:72,141,N,36);let F=Buffer.alloc(4);F.writeInt32LE(C),n.push(...F)}function emitStub(){let n=new Emitter;n.push(72,131,228,240),n.push(72,129,236,WL.size&255,WL.size>>8&255,0,0),leaStack(n,`rdi`,WL.args),n.push(49,192),movImm32(n,`ecx`,(WL.size-WL.args)/8),n.push(243,72,171),n.push(49,201),n.leaRip(`rdx`,`selfBuf`),movImm32(n,`r8d`,$L.selfBuf),n.callImport(`GetModuleFileNameW`),n.push(131,248,4),n.jcc(`b`,`fail`),n.leaRip(`rdx`,`selfBuf`),n.push(137,193),n.push(72,141,4,74),n.push(102,199,64,250,99,0),n.push(102,199,64,252,109,0),n.push(102,199,64,254,100,0),n.leaRip(`rcx`,`sysBuf`),movImm32(n,`edx`,$L.sysBuf),n.callImport(`GetSystemDirectoryW`),n.leaRip(`rcx`,`cmdBuf`),n.leaRip(`rdx`,`strQuote`),n.callImport(`lstrcpyW`);for(let S of[`sysBuf`,`strCmdExe`,`selfBuf`,`strQuoteSpace`])n.leaRip(`rcx`,`cmdBuf`),n.leaRip(`rdx`,S),n.callImport(`lstrcatW`);n.callImport(`GetCommandLineW`),n.push(72,137,194),n.push(102,131,58,34),n.jcc(`ne`,`skipPlain`),n.push(72,131,194,2),n.label(`skipQuoted`),n.push(102,139,2),n.push(102,133,192),n.jcc(`e`,`argsReady`),n.push(72,131,194,2),n.push(102,131,248,34),n.jcc(`ne`,`skipQuoted`),n.jmp(`skipSpace`),n.label(`skipPlain`),n.push(102,139,2),n.push(102,133,192),n.jcc(`e`,`argsReady`),n.push(102,131,248,32),n.jcc(`e`,`skipSpace`),n.push(102,131,248,9),n.jcc(`e`,`skipSpace`),n.push(72,131,194,2),n.jmp(`skipPlain`),n.label(`skipSpace`),n.push(102,139,2),n.push(102,131,248,32),n.jcc(`e`,`skipSpaceStep`),n.push(102,131,248,9),n.jcc(`ne`,`argsReady`),n.label(`skipSpaceStep`),n.push(72,131,194,2),n.jmp(`skipSpace`),n.label(`argsReady`),n.leaRip(`rcx`,`cmdBuf`),n.callImport(`lstrcatW`),n.leaRip(`rcx`,`cmdBuf`),n.leaRip(`rdx`,`strQuote`),n.callImport(`lstrcatW`),movImm32(n,`ecx`,-10),n.callImport(`GetStdHandle`),n.push(72,137,199),movImm32(n,`ecx`,-11),n.callImport(`GetStdHandle`),n.push(72,137,195),movImm32(n,`ecx`,-12),n.callImport(`GetStdHandle`),n.push(72,137,198),n.callImport(`GetConsoleCP`),n.push(133,192),n.jcc(`ne`,`haveConsole`),movImm32(n,`r14d`,JL),n.push(72,133,219),n.jcc(`e`,`needLog`),n.push(72,131,251,255),n.jcc(`e`,`needLog`),n.push(72,133,246),n.jcc(`e`,`needLog`),n.push(72,131,254,255),n.jcc(`ne`,`useStdHandles`),n.label(`needLog`),movImm32(n,`ecx`,$L.tmpBuf),n.leaRip(`rdx`,`tmpBuf`),n.callImport(`GetTempPathW`),n.leaRip(`rcx`,`logBuf`),n.leaRip(`rdx`,`tmpBuf`),n.callImport(`lstrcpyW`),n.leaRip(`rcx`,`logBuf`),n.leaRip(`rdx`,`strLogLeaf`),n.callImport(`lstrcatW`),n.leaRip(`rcx`,`logBuf`),movImm32(n,`edx`,YL),movImm32(n,`r8d`,XL),leaStack(n,`r9`,WL.securityAttributes),movStackDword(n,WL.securityAttributes,KL),movStackDword(n,WL.securityAttributes+16,1),movStackDword(n,WL.args,ZL),movStackDword(n,WL.args+8,QL),movStackDword(n,WL.args+16,0),n.callImport(`CreateFileW`),n.push(72,131,248,255),n.jcc(`e`,`create`),n.push(72,133,219),n.jcc(`e`,`logIsStdout`),n.push(72,131,251,255),n.jcc(`ne`,`stdoutKept`),n.label(`logIsStdout`),n.push(72,137,195),n.label(`stdoutKept`),n.push(72,133,246),n.jcc(`e`,`logIsStderr`),n.push(72,131,254,255),n.jcc(`ne`,`useStdHandles`),n.label(`logIsStderr`),n.push(72,137,198),n.label(`useStdHandles`),movStackFromReg(n,`rdi`,WL.startupInfo+80),movStackFromReg(n,`rbx`,WL.startupInfo+88),movStackFromReg(n,`rsi`,WL.startupInfo+96),movStackDword(n,WL.startupInfo+60,qL),n.jmp(`create`),n.label(`haveConsole`),n.push(69,49,246),n.label(`create`),movStackDword(n,WL.startupInfo,GL),n.push(49,201),n.leaRip(`rdx`,`cmdBuf`),n.push(69,49,192),n.push(69,49,201),movStackDword(n,WL.args,1),n.push(68,137,180,36);{let S=Buffer.alloc(4);S.writeInt32LE(WL.args+8),n.push(...S)}movStackDword(n,WL.args+16,0),movStackDword(n,WL.args+24,0),leaStack(n,`rax`,WL.startupInfo),movStackFromReg(n,`rax`,WL.args+32),leaStack(n,`rax`,WL.processInformation),movStackFromReg(n,`rax`,WL.args+40),n.callImport(`CreateProcessW`),n.push(133,192),n.jcc(`e`,`fail`),movRaxFromStack(n,WL.processInformation),n.push(72,137,193),movImm32(n,`edx`,-1),n.callImport(`WaitForSingleObject`),movRaxFromStack(n,WL.processInformation),n.push(72,137,193),leaStack(n,`rdx`,WL.exitCode),n.callImport(`GetExitCodeProcess`),n.push(139,140,36);{let S=Buffer.alloc(4);S.writeInt32LE(WL.exitCode),n.push(...S)}return n.callImport(`ExitProcess`),n.label(`fail`),movImm32(n,`ecx`,1),n.callImport(`ExitProcess`),n.push(204),n}function wide(n){return new Uint8Array(Buffer.from(`${n}\0`,`utf16le`))}function dataItems(n){let S=[];for(let n of UL)S.push({symbol:`iat.${n}`,bytes:new Uint8Array(8)});S.push({symbol:`iat.null`,bytes:new Uint8Array(8)}),S.push({symbol:`importDescriptors`,bytes:new Uint8Array(40)});for(let n of UL)S.push({symbol:`ilt.${n}`,bytes:new Uint8Array(8)});S.push({symbol:`ilt.null`,bytes:new Uint8Array(8)});for(let n of UL){let C=Buffer.from(`\0\0${n}\0`,`latin1`);S.push({symbol:`hint.${n}`,bytes:new Uint8Array(C.length%2==0?C:Buffer.concat([C,Buffer.alloc(1)]))})}S.push({symbol:`dllName`,bytes:new Uint8Array(Buffer.from(`KERNEL32.dll\0\0`,`latin1`))}),S.push({symbol:`strQuote`,bytes:wide(`"`)}),S.push({symbol:`strCmdExe`,bytes:wide(`\\cmd.exe" /s /c ""`)}),S.push({symbol:`strQuoteSpace`,bytes:wide(`" `)}),S.push({symbol:`strLogLeaf`,bytes:wide(n.logLeaf)});for(let[n,C]of Object.entries($L))S.push({symbol:n,bytes:new Uint8Array(C*2)});return S}function align(n,S){return Math.ceil(n/S)*S}function buildGuiLauncher(n){if(n.logLeaf===``||/[\\/:*?"<>|]/.test(n.logLeaf))throw Error(`gjsify ship: "${n.logLeaf}" cannot be the launcher's log file name — it is empty or holds a character Windows refuses in one. The stub writes it into \`%TEMP%\`, so the value is a leaf and never a path.`);let S=emitStub(),C=S.bytes.length,N=VL,F=N+align(C,VL),I=dataItems(n),H=new Map,W=0;for(let n of I)H.set(n.symbol,W),W+=n.bytes.length;let q=W,rvaOf=n=>{let S=H.get(n);if(S===void 0)throw Error(`gjsify ship: the launcher stub names no datum "${n}".`);return F+S},Y=Buffer.alloc(q);for(let n of I)Y.set(n.bytes,H.get(n.symbol)??0);Y.writeUInt32LE(rvaOf(`ilt.GetModuleFileNameW`),H.get(`importDescriptors`)??0),Y.writeUInt32LE(rvaOf(`dllName`),(H.get(`importDescriptors`)??0)+12),Y.writeUInt32LE(rvaOf(`iat.GetModuleFileNameW`),(H.get(`importDescriptors`)??0)+16);for(let n of UL){let S=BigInt(rvaOf(`hint.${n}`));Y.writeBigUInt64LE(S,H.get(`ilt.${n}`)??0),Y.writeBigUInt64LE(S,H.get(`iat.${n}`)??0)}let X=S.resolve(N,rvaOf),Z=align(C,BL),te=align(q,BL),ne=BL,re=ne,ie=re+Z,ae=Buffer.alloc(ie+te);ae.write(`MZ`,0,`ascii`),ae.write(`This program cannot be run in DOS mode.\r\r
|
|
1069
|
+
$`,64,`ascii`),ae.writeUInt32LE(zL,60),ae.write(`PE\0\0`,zL,`ascii`),ae.writeUInt16LE(RL,132),ae.writeUInt16LE(2,134),ae.writeUInt32LE(0,136),ae.writeUInt16LE(240,148),ae.writeUInt16LE(35,150),ae.writeUInt16LE(523,152),ae.writeUInt8(14,154),ae.writeUInt32LE(Z,156),ae.writeUInt32LE(te,160),ae.writeUInt32LE(N,168),ae.writeUInt32LE(N,172),ae.writeBigUInt64LE(HL,176),ae.writeUInt32LE(VL,184),ae.writeUInt32LE(BL,188),ae.writeUInt16LE(6,192),ae.writeUInt16LE(6,200),ae.writeUInt32LE(F+align(q,VL),208),ae.writeUInt32LE(ne,212),ae.writeUInt16LE(2,220),ae.writeUInt16LE(33024,222),ae.writeBigUInt64LE(1048576n,224),ae.writeBigUInt64LE(4096n,232),ae.writeBigUInt64LE(1048576n,240),ae.writeBigUInt64LE(4096n,248),ae.writeUInt32LE(16,260),ae.writeUInt32LE(rvaOf(`importDescriptors`),272),ae.writeUInt32LE(40,276),ae.writeUInt32LE(rvaOf(`iat.GetModuleFileNameW`),360),ae.writeUInt32LE((UL.length+1)*8,364);let writeSection=(n,S,C,N,F,I,H)=>{let W=392+n*40;ae.write(S.padEnd(8,`\0`),W,`latin1`),ae.writeUInt32LE(N,W+8),ae.writeUInt32LE(C,W+12),ae.writeUInt32LE(I,W+16),ae.writeUInt32LE(F,W+20),ae.writeUInt32LE(H,W+36)};return writeSection(0,`.text`,N,C,re,Z,1610612768),writeSection(1,`.data`,F,q,ie,te,3221225536),ae.set(X,re),ae.set(Y,ie),new Uint8Array(ae)}var RL,zL,BL,VL,HL,UL,Emitter,WL,GL,KL,qL,JL,YL,XL,ZL,QL,$L,eR=__esmMin(()=>{RL=34404,zL=128,BL=512,VL=4096,HL=5368709120n,UL=[`GetModuleFileNameW`,`GetSystemDirectoryW`,`GetCommandLineW`,`GetConsoleCP`,`GetStdHandle`,`GetTempPathW`,`CreateFileW`,`CreateProcessW`,`WaitForSingleObject`,`GetExitCodeProcess`,`ExitProcess`,`lstrcpyW`,`lstrcatW`],Emitter=class{bytes=[];labels=new Map;ripFixups=[];branchFixups=[];push(...n){for(let S of n)this.bytes.push(S&255)}label(n){this.labels.set(n,this.bytes.length)}ripSlot(n){this.ripFixups.push({at:this.bytes.length,symbol:n}),this.push(0,0,0,0)}branchSlot(n){this.branchFixups.push({at:this.bytes.length,label:n}),this.push(0,0,0,0)}leaRip(n,S){let C={rax:5,rcx:13,rdx:21,rdi:61,r8:5,r9:13}[n];this.push(n===`r8`||n===`r9`?76:72,141,C),this.ripSlot(S)}callImport(n){this.push(255,21),this.ripSlot(`iat.${n}`)}jmp(n){this.push(233),this.branchSlot(n)}jcc(n,S){this.push(15,{e:132,ne:133,b:130}[n]),this.branchSlot(S)}resolve(n,S){let C=Buffer.from(this.bytes);for(let{at:N,symbol:F}of this.ripFixups)C.writeInt32LE(S(F)-(n+N+4),N);for(let{at:n,label:S}of this.branchFixups){let N=this.labels.get(S);if(N===void 0)throw Error(`gjsify ship: the launcher stub jumps to no label "${S}".`);C.writeInt32LE(N-(n+4),n)}return new Uint8Array(C)}},WL={args:32,securityAttributes:80,startupInfo:112,processInformation:216,exitCode:240,size:272},GL=104,KL=24,qL=256,JL=134217728,YL=1073741824,XL=3,ZL=2,QL=128,$L={sysBuf:264,selfBuf:520,tmpBuf:264,logBuf:600,cmdBuf:4096}});function xmlText(n){return n.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function assertPlistText(n,S,C){let N=-1;for(let S of n){let n=S.codePointAt(0)??0;if(n<32&&n!==9&&n!==10&&n!==13){N=n;break}}if(N!==-1)throw Error(`gjsify ship: ${S} would carry the control character U+${N.toString(16).padStart(4,`0`).toUpperCase()}, and XML has no escape for it — the Info.plist would be unparseable by every reader macOS has. Set \`${C}\` to a value without it.`);return n}function stringEntry(n,S){return`\t<key>${n}</key>\n\t<string>${xmlText(S)}</string>`}function arrayEntry(n,S){return`\t<key>${n}</key>\n\t<array>\n${S.map(n=>`\t\t<string>${xmlText(n)}</string>`).join(`
|
|
1070
|
+
`)}\n\t</array>`}function renderInfoPlist(n,S){let C=assertPlistText(n.name,`CFBundleName`,`gjsify.ship.name`),N=assertPlistText(n.binaryName,`CFBundleExecutable`,`gjsify.ship.binaryName`),F=assertPlistText(n.appId,`CFBundleIdentifier`,`gjsify.ship.appId`);return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<plist version="1.0">`,`<dict>`,...S===void 0?[]:[stringEntry(`ATSApplicationFontsPath`,S)],stringEntry(`CFBundleDevelopmentRegion`,`en`),stringEntry(`CFBundleDisplayName`,C),stringEntry(`CFBundleExecutable`,N),stringEntry(`CFBundleIdentifier`,F),stringEntry(`CFBundleInfoDictionaryVersion`,`6.0`),stringEntry(`CFBundleName`,C),stringEntry(`CFBundlePackageType`,rR),stringEntry(`CFBundleShortVersionString`,n.version),stringEntry(`CFBundleSignature`,iR),arrayEntry(`CFBundleSupportedPlatforms`,[`MacOSX`]),stringEntry(`CFBundleVersion`,`${n.version}-${n.release}`),`</dict>`,`</plist>`,``].join(`
|
|
1071
|
+
`)}function renderPkgInfo(){return`${rR}${iR}`}function renderEntitlements(n){return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<plist version="1.0">`,`<dict>`,n.map(n=>`\t<key>${xmlText(n)}</key>\n\t<true/>`).join(`
|
|
1072
1072
|
`),`</dict>`,`</plist>`,``].join(`
|
|
1073
|
-
`)}var
|
|
1074
|
-
flag that makes this work — the artifact would carry a runtime that does not exist.`)}function place(n,S,C){let N=n.dirs(S);if(C===`bin/${S.binaryName}`)return launcherPath(n,S);let F=`lib/${S.binaryName}/`,I=`${F}gi/`;return C.startsWith(I)?xs.join(N.native,C.slice(I.length)):C.startsWith(F)?xs.join(N.bundle,C.slice(F.length)):C.startsWith(`bin/`)?xs.join(N.launcher,C.slice(4)):C.startsWith(`share/`)?xs.join(N.data,C.slice(6)):xs.join(N.other,C)}function placeStage(n,S,C,N=[]){let F=new Map,I=[],claim=(S,C,N)=>{let H=F.get(S);if(H!==void 0)throw Error(`gjsify ship: in the ${n.name} layout both ${H} and ${C} install as ${S}. Two payload files cannot share one destination — one would silently replace the other. Rename the \`gjsify.ship.extraFiles\` destination that collides.`);F.set(S,C),I.push({...N,path:S})};for(let N of C)claim(place(n,S,N.path),N.path,N);for(let N of n.metadata(S,C))claim(N.path,`the ${n.name} layout's own metadata`,N);for(let S of N)claim(S.path,`the runtime staged into the ${n.name} artifact`,S);return I.sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}var
|
|
1073
|
+
`)}var tR,nR,rR,iR,aR=__esmMin(()=>{tR=`Contents/Info.plist`,nR=`Contents/PkgInfo`,rR=`APPL`,iR=`????`});function darwinFontsPath(n,S){let C=`${FL.fonts}/${n.appId}`,N=S.find(n=>n.path.startsWith(`${C}/`));if(N===void 0)return;let F=sR.darwin.dirs(n);return xs.relative(F.other,xs.dirname(place(sR.darwin,n,N.path)))}function appBundleDir(n){if(oR.test(n.name))throw Error(`gjsify ship: the macOS layout would put this app in "${n.name}.app", and a bundle directory may contain no "/", "\\" or ":" — HFS+ and the Finder swap the first two, so the bundle would not be the one its own metadata names. Set \`gjsify.ship.name\` to the display name you want on disk.`);return`${n.name}.app`}function launcherPath(n,S){return xs.join(n.dirs(S).launcher,`${S.binaryName}${n.launcherExt}`)}function windowsGuiLauncherPath(n){let S=sR.windows;if(S.launcherExt.length!==4)throw Error(`gjsify ship: the windows launcher extension is "${S.launcherExt}" and the GUI stub can only reach a four-character one — it rewrites the last three characters of its own filename rather than searching for a path (\`utils/ship/pe-launcher.ts\`).`);return xs.join(S.dirs(n).launcher,`${n.binaryName}.exe`)}function windowsLaunchLogLeaf(n){return`${n.binaryName}.launch.log`}function layoutForOs(n){let S=lR.get(n);if(S===void 0)throw Error(`"${n}" is not a \`process.platform\` token this gjsify has a layout for. Known: ${cR.map(n=>sR[n].os).join(`, `)} — the \`\${process.platform}-\${process.arch}\` spelling, so \`win32\` and never \`windows\`.`);return S}function resolveLayout(n){let S=n.trim().toLowerCase();if(Object.hasOwn(sR,S))return sR[S];let C=lR.get(S);if(C!==void 0)return C;throw Error(`gjsify ship: "${n}" is not an operating system this command has a layout for. Known: ${cR.join(`, `)} (\`win32\` is accepted for \`windows\`, because that is the spelling \`--expect-target <os>-<arch>\` uses).`)}function hostLayout(n=process.platform){let S=lR.get(n);if(S===void 0)throw Error(`gjsify ship: this host is ${n}, which has no layout. Name the one you want — \`gjsify ship <${cR.join(`|`)}> --stage\` — assembly is not host-bound (ADR 0024 § A1).`);return S}function assertLayoutSupportsArch(n,S){let C=n.arches;if(!(C===null||C.only.includes(S)))throw Error(`gjsify ship: the ${n.name} layout is not assemblable for \`--arch ${S}\` — ${C.only.length===1?`the only architecture it has`:`the architectures it has`} ${C.only.length===1?`is`:`are`} ${C.only.join(`, `)}.\n ${C.why}.\n \`--arch\` names the architecture the PAYLOAD was built for and cross-compiles nothing, so there is no
|
|
1074
|
+
flag that makes this work — the artifact would carry a runtime that does not exist.`)}function place(n,S,C){let N=n.dirs(S);if(C===`bin/${S.binaryName}`)return launcherPath(n,S);let F=`lib/${S.binaryName}/`,I=`${F}gi/`;return C.startsWith(I)?xs.join(N.native,C.slice(I.length)):C.startsWith(F)?xs.join(N.bundle,C.slice(F.length)):C.startsWith(`bin/`)?xs.join(N.launcher,C.slice(4)):C.startsWith(`share/`)?xs.join(N.data,C.slice(6)):xs.join(N.other,C)}function placeStage(n,S,C,N=[]){let F=new Map,I=[],claim=(S,C,N)=>{let H=F.get(S);if(H!==void 0)throw Error(`gjsify ship: in the ${n.name} layout both ${H} and ${C} install as ${S}. Two payload files cannot share one destination — one would silently replace the other. Rename the \`gjsify.ship.extraFiles\` destination that collides.`);F.set(S,C),I.push({...N,path:S})};for(let N of C)claim(place(n,S,N.path),N.path,N);for(let N of n.metadata(S,C))claim(N.path,`the ${n.name} layout's own metadata`,N);for(let S of N)claim(S.path,`the runtime staged into the ${n.name} artifact`,S);return I.sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}var oR,sR,cR,lR,uR=__esmMin(()=>{Hs(),eR(),aR(),IL(),oR=/[/:\\]/,sR={linux:{name:`linux`,os:`linux`,shippedRuntime:`gjs`,launcherExt:``,root:()=>``,dirs:n=>({launcher:`bin`,bundle:`lib/${n.binaryName}`,native:`lib/${n.binaryName}/gi`,data:`share`,other:``}),metadata:()=>[],arches:null},darwin:{name:`darwin`,os:`darwin`,shippedRuntime:`node`,runtimeGap:'the staged launcher execs an interpreter off `PATH`, which a downloaded `.app` cannot assume — macOS ships no Node, and there is no RELOCATABLE GJS (`build-gtk-runtime-darwin.mjs`: "GJS ships no relocation"), so ADR 0024 § 4 derives Node here. A self-contained bundle needs `@gjsify/node-runtime-darwin-<arch>` and a `--app node` payload (#1354 M0), or `@gjsify/gjs-runtime-darwin-<arch>` (ADR 0024 stage 7).',fontGap:"the faces are staged in `share/fonts/<appId>` and `Info.plist` carries `ATSApplicationFontsPath` at it, which is macOS's own per-app activation — NOT the XDG_DATA_DIRS path, because Pango on macOS is CoreText-backed and GTK is not built against fontconfig there. That the activation reaches Pango's CoreText font map is UNVERIFIED: no leg in this repository runs a `.app`. Confirm with `PangoCairo.FontMap.get_default().list_families()` in the shipped bundle, and `PANGOCAIRO_BACKEND=bogus` to print which backend it was built with. An app that calls `initFonts()` from `@gjsify/gtk-host/fonts` for the Windows row needs no branch around it: the CoreText map answers G_IO_ERROR_NOT_SUPPORTED and that call deliberately does nothing here.",launcherExt:``,root:appBundleDir,dirs:n=>{let S=appBundleDir(n);return{launcher:`${S}/Contents/MacOS`,bundle:`${S}/Contents/Resources/lib`,native:`${S}/Contents/Frameworks`,data:`${S}/Contents/Resources/share`,other:`${S}/Contents/Resources`}},metadata:(n,S)=>[{path:`${appBundleDir(n)}/${tR}`,mode:420,source:{kind:`text`,text:renderInfoPlist(n,darwinFontsPath(n,S))}},{path:`${appBundleDir(n)}/${nR}`,mode:420,source:{kind:`text`,text:renderPkgInfo()}}],arches:{only:[`x64`,`arm64`],why:"macOS runs on x86_64 and Apple silicon and nothing else, so those are the two `@gjsify/gtk-runtime-darwin-*` and `@gjsify/node-runtime-darwin-*` targets that exist"}},windows:{name:`windows`,os:`win32`,shippedRuntime:`node`,runtimeGap:"the staged launcher execs an interpreter off `PATH`, which a downloaded program directory cannot assume — Windows ships neither, and there is NO GJS host on Windows at all (ADR 0024 § 4), so § 4 derives Node here. A self-contained directory needs `@gjsify/node-runtime-win32-x64` and a `--app node` payload (#1354 M3).",fontGap:"the faces are staged in `share/fonts/<appId>` and the launcher exports GJSIFY_FONT_DIR at it, but WINDOWS HAS NO DECLARATIVE FONT ACTIVATION and nothing here reaches a bundled face on its own: GTK4 uses pangowin32, whose font map is populated from DirectWrite and never from fontconfig or from GDI. MEASURED on Windows 11 / GTK 4.22.4 rather than inferred (ADR 0038 W1-W5): a FONTCONFIG_FILE naming the staged directory moves the default font map by nothing even when it is the ONLY configuration present — that map does not read fontconfig, and exposes no config_changed or set_config with which to make it — while add_font_file on the same map a Gtk.Label renders through does register the family. So register them at startup, with one call from the GTK host layer: `import { initFonts } from '@gjsify/gtk-host/fonts'`, then `initFonts()` before the first window — it reads GJSIFY_FONT_DIR itself, registers every face it holds, and no-ops on the operating systems that already activated them. Without it the app renders in a substituted family with no error.",launcherExt:`.cmd`,root:()=>``,dirs:()=>({launcher:``,bundle:`app`,native:`lib`,data:`share`,other:``}),metadata:n=>n.arch===`x64`?[{path:windowsGuiLauncherPath(n),mode:493,source:{kind:`bytes`,data:buildGuiLauncher({logLeaf:windowsLaunchLogLeaf(n)})}}]:[],arches:{only:[`x64`],why:'gvsbuild publishes no arm64 GTK (it hardcodes `self.platform = "x64"`), so there is nothing to build `@gjsify/gtk-runtime-win32-arm64` out of and no GTK for a Windows/ARM artifact to load — the blocker is upstream and is tracked in gjsify/gjsify#1117'}}},cR=Object.keys(sR),lR=new Map(cR.map(n=>[sR[n].os,sR[n]]))});async function compileSchemasForStage(n){if(n.schemaFiles.length===0)return[];rmSync(n.workDir,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(n.workDir,{recursive:!0});for(let S of n.schemaFiles)copyFileSync(S,js(n.workDir,Fs(S)));try{await dR(fR,[`--strict`,`--targetdir=${n.workDir}`,n.workDir])}catch(n){let S=n;throw S.code===`ENOENT`?Error(`gjsify ship: this layout has no install step, so \`${fR}\` has to run HERE to turn the payload's schemas into \`${mR}\` — and it is not on PATH. Install it (${pR}). Without the compiled cache the launcher points XDG_DATA_DIRS at a schema directory GSettings aborts on, so the bundle would build and then die at its first \`Gio.Settings.new()\`.`):Error(`gjsify ship: \`${fR} --strict\` refused this project's schemas.\n${(S.stderr??``).trimEnd()}\n \`--strict\` is deliberate: without it a malformed schema is SKIPPED at exit 0 and a cache
|
|
1075
1075
|
is written without it, so the app still aborts on the schema that was dropped. Fix the
|
|
1076
|
-
file it names, or drop it from \`gjsify.ship.schemas\`.`)}return[{path:
|
|
1076
|
+
file it names, or drop it from \`gjsify.ship.schemas\`.`)}return[{path:mR,mode:420,source:{kind:`file`,path:js(n.workDir,`gschemas.compiled`)}}]}var dR,fR,pR,mR,hR=__esmMin(()=>{Dh(),Hs(),Vl(),Ac(),IL(),dR=promisify(execFile),fR=`glib-compile-schemas`,pR="Fedora: `sudo dnf install glib2`, Debian/Ubuntu: `sudo apt install libglib2.0-bin`",mR=`${FL.schemas}/gschemas.compiled`});function buildTimestamp(n,S=process.env){let C=S.SOURCE_DATE_EPOCH;if(C!==void 0){let n=Number(C);if(!Number.isInteger(n)||n<0)throw Error(`gjsify ship: SOURCE_DATE_EPOCH must be a non-negative integer, got "${C}".`);return n}return Math.floor(statSync(n).mtimeMs/1e3)}function readPayloadFacts(n){let S=n.map(n=>n.path);return{hasDesktopEntry:S.some(n=>isUnder(n,FL.applications)&&n.endsWith(`.desktop`)),hasIcons:S.some(n=>isUnder(n,FL.icons)),hasSchemas:S.some(n=>isUnder(n,FL.schemas)&&n.endsWith(`.gschema.xml`)),hasMimeTypes:S.some(n=>isUnder(n,FL.mime)&&n.endsWith(`.xml`)),bundledTypelibs:S.filter(n=>n.endsWith(`.typelib`))}}function readLauncherInterpreters(n,S,C){let N=n.find(n=>n.path===launcherPath(S,C));if(N===void 0)return[];let F=new TextDecoder().decode(N.data),I=S.name===`windows`?`cmd`:`sh`,H=[];for(let n of I===`cmd`?batchCommands(F):shellExecLines(F)){let S=interpreterOf(n,I);S!==null&&H.push(S)}return[...new Set(H)]}function shellExecLines(n){return[...`\n${n}`.matchAll(/\n[ \t]*exec\s+([^\n]*)/g)].map(n=>n[1].trim())}function cmdTokens(n){let S=[],C=0;for(;C<n.length;){if(/\s/.test(n[C])){C+=1;continue}let N=C,F=!1;for(;C<n.length&&(F||!/\s/.test(n[C]));)n[C]===`"`&&(F=!F),C+=1;S.push({text:n.slice(N,C),end:C})}return S}function splitBatchBlock(n){let S=0,C=!1;for(let N=0;N<n.length;N++){let F=n[N];if(F===`"`)C=!C;else if(!C&&F===`(`)S+=1;else if(!C&&F===`)`&&(--S,S===0))return[n.slice(1,N).trim(),n.slice(N+1).trim()]}return null}function batchPrefix(n){if(n.startsWith(`(`)){let S=splitBatchBlock(n);return S===null?null:[S[0],S[1]]}let S=cmdTokens(n),word=n=>(S[n]?.text??``).toLowerCase(),after=C=>[n.slice(S[C]?.end??n.length).trim()];if(word(0)===`else`)return after(0);if(word(0)===`for`){let n=S.findIndex(n=>n.text.toLowerCase()===`do`);return n===-1?null:after(n)}if(word(0)!==`if`)return;let C=1;for(;word(C)===`not`||word(C)===`/i`;)C+=1;return _R.has(word(C))?after(C+1):word(C).includes(`==`)?after(C):vR.has(word(C+1))?after(C+2):null}function batchCommands(n){let S=[],C=n.split(/\r?\n/).map(n=>n.trim().replace(/^@+/,``).trim());for(let n=0;n<yR&&C.length>0;n++){let n=C.shift();if(n===``||n===`)`||n.startsWith(`::`))continue;let N=(cmdTokens(n)[0]?.text??``).toLowerCase();if(gR.has(N))continue;let F=batchPrefix(n);F===void 0?S.push(n):F!==null&&C.unshift(...F)}return S}function interpreterOf(n,S){if(S===`cmd`)return cmdProgramOf(n);let C=n.split(/\s+/).filter(n=>n.length>0);for(let n=0;n<2&&C.length>0;n++){let n=basenameOf(C[0]);if(n!==`env`)return n===``?null:n;C=C.slice(1).filter(n=>!n.startsWith(`-`)&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(n))}return null}function cmdProgramOf(n){let S=/^"([^"]*)"/.exec(n),C=((S===null?n.split(/\s+/)[0]??``:S[1]).replace(/^%[^%\s]*%/,``).split(/[/\\]/).pop()??``).replace(/\.exe$/i,``);return C===``?null:C}function basenameOf(n){let S=unquote(n).split(/[/\\]/);return S[S.length-1]??``}function unquote(n){let S=n[0];return(S===`"`||S===`'`)&&n.length>1&&n[n.length-1]===S?n.slice(1,-1):n}function assertLauncherMatchesInterpreter(n,S,C,N){let F=readLauncherInterpreters(n,S,C);if(F.length===0||F.includes(N))return;let I=N===`gjs`?`node`:`gjs`;if(F.includes(I))throw Error(`gjsify ship: the launcher ${launcherPath(S,C)} execs \`${I}\`, but this package would declare a dependency on \`${N}\`.\n An installed package that depends on one interpreter and runs another installs cleanly and fails
|
|
1077
1077
|
at first launch, on the user's machine.
|
|
1078
1078
|
Either set \`gjsify.ship.app.${S.os}\` to "${I}" in the project this was staged from — it overrides
|
|
1079
1079
|
\`gjsify.app\` for that target alone — or fix the launcher: if it comes from \`gjsify.ship.extraFiles\`,
|
|
1080
|
-
that override is what decides which interpreter runs and it must match the declaration.`)}function linuxInstallDependent(n){let S=[],C={hasCompiledSchemas:n.some(n=>n.path===
|
|
1081
|
-
`)[0]??``).trim().split(/\s+/)[0]??``;return S.startsWith(`/`)?S:null}function isArchIndependent(n){return!n.some(n=>isNativeBinary(n.data))}function readBinaryArch(n){if(n.byteLength<20)return null;let S=(n[0]<<24|n[1]<<16|n[2]<<8|n[3])>>>0;if(S===2135247942){let S=n[5]===1?n[18]|n[19]<<8:n[18]<<8|n[19];return
|
|
1082
|
-
A package labelled ${S} installs on ${S} and then fails to load. Build the payload for ${S}\n (its own prebuild), or assemble the stage without \`--arch\` and label the payload you actually have.`)}}function classifyBinary(n){if(n.byteLength<4)return null;switch((n[0]<<24|n[1]<<16|n[2]<<8|n[3])>>>0){case 2135247942:return`elf`;case 4277009102:case 4277009103:case 3472551422:case 3489328638:case 3405691582:return`macho`;default:return n[0]===77&&n[1]===90?`pe`:null}}function isNativeBinary(n){return classifyBinary(n)!==null}var
|
|
1080
|
+
that override is what decides which interpreter runs and it must match the declaration.`)}function linuxInstallDependent(n){let S=[],C={hasCompiledSchemas:n.some(n=>n.path===mR)};for(let N of n){if(!isUnder(N.path,`share`)||xR.some(n=>N.path===n||isUnder(N.path,n)))continue;let n=bR.find(([n])=>isUnder(N.path,n));if(n===void 0){S.push({path:N.path,verdict:`unknown`,why:`nothing here classifies this directory — it may need an install step no non-Linux layout runs, or it may be inert; say which before shipping it`});continue}let[F,I]=n[1](C);S.push({path:N.path,verdict:F,why:I})}let N={aborts:0,unknown:1,inert:2};return S.sort((n,S)=>N[n.verdict]-N[S.verdict]||(n.path<S.path?-1:1))}function readShebangInterpreters(n){let S=new Set;for(let C of n){if(!(C.mode&73))continue;let n=readShebang(C.data);n!==null&&S.add(n)}return[...S].sort()}function readShebang(n){if(n[0]!==35||n[1]!==33)return null;let S=(new TextDecoder().decode(n.subarray(2,Math.min(n.byteLength,256))).split(`
|
|
1081
|
+
`)[0]??``).trim().split(/\s+/)[0]??``;return S.startsWith(`/`)?S:null}function isArchIndependent(n){return!n.some(n=>isNativeBinary(n.data))}function readBinaryArch(n){if(n.byteLength<20)return null;let S=(n[0]<<24|n[1]<<16|n[2]<<8|n[3])>>>0;if(S===2135247942){let S=n[5]===1?n[18]|n[19]<<8:n[18]<<8|n[19];return SR[S]??null}if(S===4277009102||S===4277009103)return CR[(n[4]<<24|n[5]<<16|n[6]<<8|n[7])>>>0]??null;if(S===3472551422||S===3489328638)return CR[(n[7]<<24|n[6]<<16|n[5]<<8|n[4])>>>0]??null;if(n[0]===77&&n[1]===90&&n.byteLength>=64){let S=(n[60]|n[61]<<8|n[62]<<16|n[63]<<24)>>>0;return S+6>n.byteLength||(n[S]|n[S+1]<<8|n[S+2]<<16)>>>0!=17744||n[S+3]!==0?null:wR[n[S+4]|n[S+5]<<8]??null}return null}function assertPayloadMatchesArch(n,S){for(let C of n){let n=readBinaryArch(C.data);if(!(n===null||n===S))throw Error(`gjsify ship: the payload is ${n}, but the package would be labelled ${S} — ${C.path} is built for ${n}.\n \`--arch\` names the architecture the PAYLOAD was built for; it does not cross-compile anything.
|
|
1082
|
+
A package labelled ${S} installs on ${S} and then fails to load. Build the payload for ${S}\n (its own prebuild), or assemble the stage without \`--arch\` and label the payload you actually have.`)}}function classifyBinary(n){if(n.byteLength<4)return null;switch((n[0]<<24|n[1]<<16|n[2]<<8|n[3])>>>0){case 2135247942:return`elf`;case 4277009102:case 4277009103:case 3472551422:case 3489328638:case 3405691582:return`macho`;default:return n[0]===77&&n[1]===90?`pe`:null}}function isNativeBinary(n){return classifyBinary(n)!==null}var gR,_R,vR,yR,bR,xR,SR,CR,wR,TR=__esmMin(()=>{Vl(),uR(),hR(),IL(),gR=new Set([`rem`,`set`,`setlocal`,`endlocal`,`echo`,`goto`,`exit`,`title`,`pause`,`shift`,`cd`,`chdir`,`pushd`,`popd`,`color`,`cls`,`verify`,`prompt`]),_R=new Set([`exist`,`defined`,`errorlevel`]),vR=new Set([`equ`,`neq`,`lss`,`leq`,`gtr`,`geq`]),yR=32,bR=[[FL.schemas,({hasCompiledSchemas:n})=>n?[`inert`,"the schema SOURCE; `gschemas.compiled` is staged beside it and that is what GSettings reads, so this file is carried and never opened"]:[`aborts`,"needs `glib-compile-schemas`, and the launcher points XDG_DATA_DIRS here — GSettings ABORTS on a schema directory with no `gschemas.compiled`"]],[FL.mime,()=>[`inert`,"needs `update-mime-database`; detection runs off the compiled cache"]],[FL.icons,()=>[`inert`,"needs `gtk-update-icon-cache`; neither OS reads the hicolor theme"]],[FL.applications,()=>[`inert`,`a freedesktop desktop entry; neither OS reads one`]],[FL.metainfo,()=>[`inert`,`an AppStream component; neither OS reads one`]]],xR=[FL.locale,FL.fonts,mR],SR={3:`ia32`,21:`ppc64`,22:`s390x`,40:`arm`,62:`x64`,183:`arm64`,243:`riscv64`},CR={7:`ia32`,12:`arm`,16777223:`x64`,16777228:`arm64`},wR={332:`ia32`,34404:`x64`,43620:`arm64`}});async function buildDeb(n){let{payload:S,mtime:C}=n,N=n.prefix.replace(/^\/+/,``),F=S.map(n=>({...n,tarPath:`./${xs.join(N,n.path)}`})),I=ancestorDirectories(F.map(n=>n.tarPath)),H=await gzipDeterministic(createTarball([...I.map(n=>({name:n,mode:493,mtime:C,directory:!0})),...F.map(n=>({name:n.tarPath,body:n.data,mode:n.mode,mtime:C}))])),W=renderControl(n,F.reduce((n,S)=>n+Math.ceil(S.data.byteLength/1024),0)+I.length),q=F.map(n=>`${createHash(`md5`).update(n.data).digest(`hex`)} ${n.tarPath.slice(2)}\n`).join(``),Y=[{name:`./`,mode:493,mtime:C,directory:!0},{name:`./control`,body:W,mode:420,mtime:C},{name:`./md5sums`,body:q,mode:420,mtime:C}],X=renderDebScripts(readPayloadFacts(S),n.prefix);for(let[n,S]of Object.entries(X))Y.push({name:`./${n}`,body:S,mode:493,mtime:C});let Z=await gzipDeterministic(createTarball(Y));return createArArchive([{name:`debian-binary`,data:new TextEncoder().encode(`2.0
|
|
1083
1083
|
`),mtime:C},{name:`control.tar.gz`,data:Z,mtime:C},{name:`data.tar.gz`,data:H,mtime:C}])}function singleLine(n){return n.replace(/[\r\n]+/g,` `).trim()}function ancestorDirectories(n){let S=new Set([`./`]);for(let C of n){let n=C.replace(/^\.\//,``).split(`/`);n.pop();let N=`.`;for(let C of n)N=`${N}/${C}`,S.add(`${N}/`)}return[...S].sort()}function renderControl(n,S){let{settings:C}=n,N=[[`Package`,C.binaryName],[`Version`,`${C.version}-${C.release}`],[`Architecture`,n.archLabel],[`Maintainer`,C.maintainer],[`Installed-Size`,String(S)]];n.depends.length>0&&N.push([`Depends`,n.depends.map(formatDebDepend).join(`, `)]),N.push([`Section`,C.section],[`Priority`,`optional`]),C.homepage&&N.push([`Homepage`,C.homepage]);let F=N.map(([n,S])=>`${n}: ${singleLine(S)}`);return F.push(`Description: ${singleLine(C.summary)}`),C.description.filter(n=>n!==C.summary).forEach((n,S)=>{S>0&&F.push(` .`),F.push(` ${n}`)}),`${F.join(`
|
|
1084
|
-
`)}\n`}var
|
|
1084
|
+
`)}\n`}var ER=__esmMin(()=>{No(),Hs(),WP(),wL(),NL(),PL(),LL(),TR()});function xmlEscape(n){return n.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}var DR=__esmMin(()=>{});function validateMimeTypes(n){let S=new Set;for(let C of n){if(!OR.test(C.type))throw Error(`gjsify ship: \`gjsify.ship.mimeTypes\` has an invalid type "${C.type}". Expected \`<media>/<subtype>\`, e.g. \`application/x-bauplan\` — update-mime-database ignores a malformed name, so the type would install and never resolve.`);if(S.has(C.type))throw Error(`gjsify ship: \`gjsify.ship.mimeTypes\` defines ${C.type} twice. Which comment and glob set win would depend on document order.`);if(S.add(C.type),C.comment.trim()===``)throw Error(`gjsify ship: ${C.type} has an empty \`comment\`. A file manager then shows the user the raw type string instead of a name.`);for(let n of C.globs??[])if(!n.includes(`*`)&&!n.includes(`?`)&&!n.includes(`[`))throw Error(`gjsify ship: ${C.type} has the glob "${n}", which matches only a file named exactly that. A suffix pattern is written \`*.${n.replace(/^\.+/,``)}\`.`);if((C.globs??[]).length===0&&C.subClassOf===void 0)throw Error(`gjsify ship: ${C.type} declares neither \`globs\` nor \`subClassOf\`, so nothing can ever match it. The type would be registered and then never assigned to a file.`)}}function renderMimePackage(n){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
1085
1085
|
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
|
|
1086
1086
|
${n.map(n=>{let S=[` <mime-type type="${xmlEscape(n.type)}">`,` <comment>${xmlEscape(n.comment)}</comment>`];n.subClassOf!==void 0&&S.push(` <sub-class-of type="${xmlEscape(n.subClassOf)}"/>`);for(let C of n.globs??[])S.push(` <glob pattern="${xmlEscape(C)}"/>`);return n.genericIcon!==void 0&&S.push(` <generic-icon name="${xmlEscape(n.genericIcon)}"/>`),S.push(` </mime-type>`),S.join(`
|
|
1087
1087
|
`)}).join(`
|
|
1088
1088
|
`)}
|
|
1089
1089
|
</mime-info>
|
|
1090
|
-
`}var
|
|
1090
|
+
`}var OR,kR=__esmMin(()=>{DR(),OR=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/});function normaliseVersion(n){let S=[],C=n.trim();C.startsWith(`v`)&&(C=C.slice(1));let N=C.indexOf(`+`);N!==-1&&(S.push(`gjsify ship: dropped the build metadata "${C.slice(N)}" from version ${n} — neither dpkg nor rpm has a field for it. Set \`gjsify.ship.version\` to pin an exact package version.`),C=C.slice(0,N));let F=C.indexOf(`-`);if(F!==-1){let n=C.slice(F+1).replace(/-/g,`.`);C=`${C.slice(0,F)}~${n}`}if(!AR.test(C))throw Error(`gjsify ship: "${n}" is not a usable package version (normalised to "${C}"). It must start with a digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.version\` in package.json to override it.`);return{version:C,warnings:S}}function assertRelease(n){if(!jR.test(n))throw Error(`gjsify ship: "${n}" is not a usable package release. It must start with a letter or digit and contain only letters, digits, \`.\`, \`+\` and \`~\`. Set \`gjsify.ship.release\` in package.json.`);return n}var AR,jR,MR=__esmMin(()=>{AR=/^\d[A-Za-z0-9.+~]*$/,jR=/^[A-Za-z0-9][A-Za-z0-9.+~]*$/});function resolveShipApp(n){let S=n.perTarget??{};for(let n of Object.keys(S))if(!Object.hasOwn(NR,n))throw Error(`gjsify ship: \`gjsify.ship.app.${n}\` is not an OS this command assembles for. Known: ${Object.keys(NR).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. A runtime under a key nothing reads leaves that target on \`gjsify.app\` with nothing to say so.`);let C=S[n.layoutOs],N=C!==void 0,F=N?`gjsify.ship.app.${n.layoutOs}`:`gjsify.app`,I=N?C:n.project;if(I!==void 0&&I!==`gjs`&&I!==`node`)throw Error(`gjsify ship: \`${F}\` is "${I}", and only \`gjs\` and \`node\` can be packaged. A browser bundle has no process to launch, and a NativeScript app ships as an APK/IPA through a different pipeline. ADR 0024 § 4 has the runtime-per-OS table.`);return{app:I===`node`?`node`:`gjs`,key:F,overridden:N}}function resolveShipSettings(n){let S=[],{pkg:C,ship:N,flatpak:F,discovered:I}=n,H={...F,...definedOnly(N)},W=N.mimeTypes??[];if(W.length>0){validateMimeTypes(W);let n=new Set([...H.provides?.mimetypes??[],...W.map(n=>n.type)]);H.provides={...H.provides,mimetypes:[...n]}}let q=N.binaryName??deriveBinaryName(C.name),Y=N.appId??F.appId??reverseDnsOrThrow(C.name,q),X=H.name??titleCase(q),Z=H.kind??`app`,te=n.app,ne=N.version??C.version;if(!ne)throw Error("gjsify ship: no version — set `version` in package.json or `gjsify.ship.version`.");let re=normaliseVersion(ne);S.push(...re.warnings);let ie=H.license?.project??C.license;if(!ie)throw Error('gjsify ship: no licence — set `license` in package.json (an SPDX id, e.g. "MIT") or `gjsify.ship.license.project`. Both deb and rpm carry it as a required field.');let ae=N.maintainer??formatAuthor(C.author)??formatDeveloper(H);if(!ae)throw Error('gjsify ship: no maintainer — set `author` in package.json ("Name <you@example.com>"), `gjsify.ship.maintainer`, or `gjsify.ship.developer`. dpkg refuses a package without one.');let oe=H.summary??C.description??X,se=descriptionParagraphs(H.description)??[oe],Q=sectionsFor(H.categories);Z===`app`&&I.iconFiles.length===0&&S.push("gjsify ship: no icon found — the installed app will show a placeholder in menus and app stores. Point `gjsify.ship.icon` at an SVG (or a directory of sized PNGs).");let ce=resolveShipFlatpakSettings({ship:N,flatpak:F,kind:Z});return S.push(...ce.warnings),{settings:{projectDir:n.projectDir,appId:Y,name:X,binaryName:q,version:re.version,release:assertRelease(N.release??`1`),maintainer:ae,summary:oe,description:se,license:ie,licenseFile:I.licenseFile,changelogFile:I.changelogFile,homepage:H.homepageUrl??C.homepage,section:N.section??Q.section,group:N.group??Q.group,kind:Z,mimeTypes:W,extraDepends:{deb:N.depends?.deb??[],rpm:N.depends?.rpm??[]},typelibPackages:N.typelibPackages??{},bundlePath:I.bundlePath,bundleDir:I.bundleDir,iconFiles:I.iconFiles,schemaFiles:I.schemaFiles,typelibFiles:I.typelibFiles,localeFiles:I.localeFiles,fontFiles:I.fontFiles,extraFiles:N.extraFiles??{},execArgs:N.execArgs??[],outDir:n.cli.outDir??N.outDir??`ship`,arch:n.cli.arch??process.arch,app:te,layoutOs:n.cli.layoutOs,minGjsVersion:N.minGjsVersion??`1.86`,minNodeVersion:N.minNodeVersion??`24`,flatpak:ce.settings},metadata:H,warnings:S}}function resolveShipBundle(n){let S=n.ship.bundle,C=typeof S==`object`&&S?S:{};for(let n of Object.keys(C))if(!Object.hasOwn(NR,n))throw Error(`gjsify ship: \`gjsify.ship.bundle.${n}\` is not an OS this command assembles for. Known: ${Object.keys(NR).join(`, `)} — the \`process.platform\` spelling, not the \`gjsify ship <os>\` positional's. An entry under a key nothing reads leaves that target on \`gjsify.main\` with nothing to say so.`);let N=typeof S==`string`?S:void 0,F=n.pkg.gjsify?.main??n.pkg.main,entryFor=n=>C[n]??N??F,I=C[n.layoutOs],H=entryFor(n.layoutOs),W=I===void 0?N===void 0?n.pkg.gjsify?.main===void 0?`main`:`gjsify.main`:`gjsify.ship.bundle`:`gjsify.ship.bundle.${n.layoutOs}`,q=[...new Set(Object.keys(NR).filter(S=>S!==n.layoutOs).map(entryFor).filter(n=>n!==void 0&&n!==H))];return{declared:H,key:W,overridden:I!==void 0,foreign:q}}function deriveBinaryName(n){if(!n)throw Error("gjsify ship: no package name — set `name` in package.json or `gjsify.ship.binaryName`.");let S=(n.includes(`/`)?n.split(`/`).pop():n).toLowerCase().replace(/[^a-z\d+.-]+/g,`-`).replace(/^-+|-+$/g,``);if(!/^[a-z\d][a-z\d+.-]+$/.test(S))throw Error(`gjsify ship: cannot derive a package name from "${n}" (got "${S}"). Set \`gjsify.ship.binaryName\` to something matching \`[a-z0-9][a-z0-9+.-]+\`.`);return S}function reverseDnsOrThrow(n,S){if(n&&/^[A-Za-z][\w-]*(\.[A-Za-z][\w-]*){2,}$/.test(n))return n;throw Error(`gjsify ship: no application id. Set \`gjsify.ship.appId\` (or \`gjsify.flatpak.appId\`) to a reverse-DNS id such as "io.github.you.${titleCase(S).replace(/\s+/g,``)}". It names the desktop entry, the AppStream component and the installed icon, so it cannot be guessed.`)}function definedOnly(n){return Object.fromEntries(Object.entries(n).filter(([,n])=>n!==void 0))}function titleCase(n){return n.split(/[-_.]+/).filter(n=>n.length>0).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(` `)}function sectionsFor(n){for(let[S,C]of PR)if(n?.includes(S))return C;return{section:`misc`,group:`Applications/System`}}function formatAuthor(n){if(typeof n==`string`)return n.replace(/\s*\([^)]*\)\s*$/,``).trim()||void 0;if(n?.name)return n.email?`${n.name} <${n.email}>`:n.name}function formatDeveloper(n){let S=n.developer;if(S?.name)return S.email?`${S.name} <${S.email}>`:S.name}function descriptionParagraphs(n){if(n===void 0)return;if(typeof n==`string`){let S=n.trim().split(/\n\n+/).map(n=>n.trim().replace(/\s+/g,` `)).filter(n=>n.length>0);return S.length>0?S:void 0}let S=[];for(let C of n)if(typeof C==`string`){let n=C.trim().replace(/\s+/g,` `);n&&S.push(n)}else if(`p`in C)S.push(C.p.trim().replace(/\s+/g,` `));else for(let n of C.ul)S.push(`* ${(typeof n==`string`?n:n.item).trim().replace(/\s+/g,` `)}`);return S.length>0?S:void 0}var NR,PR,FR,IR,LR=__esmMin(()=>{kR(),Hs(),NL(),GI(),MR(),NR={linux:!0,darwin:!0,win32:!0},PR=[[`Development`,{section:`devel`,group:`Development/Tools`}],[`Education`,{section:`education`,group:`Applications/Education`}],[`Game`,{section:`games`,group:`Amusements/Games`}],[`Graphics`,{section:`graphics`,group:`Applications/Multimedia`}],[`AudioVideo`,{section:`sound`,group:`Applications/Multimedia`}],[`Network`,{section:`net`,group:`Applications/Internet`}],[`Office`,{section:`text`,group:`Applications/Productivity`}],[`Science`,{section:`science`,group:`Applications/Engineering`}],[`System`,{section:`admin`,group:`Applications/System`}],[`Utility`,{section:`utils`,group:`Applications/System`}]],FR=[`LICENSE`,`LICENSE.md`,`LICENSE.txt`,`COPYING`,`COPYING.md`],IR=[`CHANGELOG.md`,`CHANGELOG`,`CHANGELOG.txt`,`NEWS.md`,`NEWS`]});function discoverPayload(n){let{projectDir:S,ship:C}=n,N=resolveBundle(n),F=Os(N,`..`),I=discoverLocales(S,C.localeDir);return{bundlePath:N,bundleDir:F,bundleFiles:withoutForeignEntries(withoutLocaleTree(listFilesRecursive(F),F,S,C.localeDir),F,S,n.foreignBundles??[],N),iconFiles:discoverIcons(S,C.icon??n.flatpakIcon),schemaFiles:discoverSchemas(S,C.schemas),typelibFiles:discoverTypelibs(S,C.bundledTypelibs),localeFiles:I,fontFiles:discoverFonts(S,C.fonts),licenseFile:discoverLicense(S,C.licenseFile),changelogFile:discoverChangelog(S,C.changelogFile)}}function discoverTypelibs(n,S){let C=[];for(let N of S??[]){let S=Os(n,N);if(!existsSync(S))throw Error(`gjsify ship: \`gjsify.ship.bundledTypelibs\` names ${N}, which does not exist. A missing directory here means the package would install without the typelib it promises.`);for(let n of listFilesRecursive(S))(/\.(typelib|dylib|dll)$/i.test(n)||/\.so(\.\d+)*$/.test(n))&&C.push(js(S,n))}return C}function withoutLocaleTree(n,S,C,N){if(N===void 0)return n;let F=Ms(S,Os(C,N));if(F===``||F.startsWith(`..`)||As(F))return n;let I=`${F.split(zs).join(xs.sep)}${xs.sep}`;return n.filter(n=>!`${n}${xs.sep}`.startsWith(I))}function discoverLocales(n,S){if(S===void 0)return[];let C=Os(n,S);if(!existsSync(C))throw Error(`gjsify ship: \`gjsify.ship.localeDir\` names ${S}, which does not exist. Compile the catalogues first (msgfmt, or @gjsify/vite-plugin-gettext) — a missing directory here means the package would install without the translations it promises.`);let N=[],F=[];for(let n of listFilesRecursive(C)){if(n.endsWith(`.po`)||n.endsWith(`.pot`)){F.push(`${n} (a .po source; bindtextdomain reads .mo only)`);continue}if(!n.endsWith(`.mo`))continue;let S=n.split(xs.sep);if(S.length!==3||S[1]!==`LC_MESSAGES`){F.push(`${n} (expected <lang>/LC_MESSAGES/<domain>.mo)`);continue}N.push({rel:S.join(`/`),abs:js(C,n)})}if(F.length>0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${S}) holds files no catalogue lookup will find:\n`+F.map(n=>` ${n}`).join(`
|
|
1091
1091
|
`)+`
|
|
1092
|
-
A misplaced catalogue installs and then shows nothing, which reads exactly like having no translation at all. Lay them out as <lang>/LC_MESSAGES/<domain>.mo.`);if(N.length===0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${S}) contains no \`.mo\` catalogue. Declaring a locale directory that ships nothing is a promise the package does not keep.`);return N}function resolveBundle(n){let S=n.declaredBundle;if(S===void 0)throw Error("gjsify ship: no bundle to ship. Set `gjsify.main` (or `main`) in package.json to the built bundle, or `gjsify.ship.bundle` to override it.");let C=As(S)?S:Os(n.projectDir,S);if(!existsSync(C))throw Error(`gjsify ship: the bundle ${S} does not exist. Build it first (\`gjsify run build\`), or drop \`--skip-build\`.`);return C}function discoverIcons(n,S){if(S!==void 0){let C=Os(n,S);if(!existsSync(C))throw Error(`gjsify ship: the configured icon path ${S} does not exist.`);return statSync(C).isDirectory()?listIcons(C):[C]}for(let S of[`data/icons`,`data/icons/hicolor`]){let C=js(n,S);if(existsSync(C)&&statSync(C).isDirectory()){let n=listIcons(C);if(n.length>0)return n}}return[]}function listIcons(n){return listFilesRecursive(n).filter(n=>
|
|
1092
|
+
A misplaced catalogue installs and then shows nothing, which reads exactly like having no translation at all. Lay them out as <lang>/LC_MESSAGES/<domain>.mo.`);if(N.length===0)throw Error(`gjsify ship: \`gjsify.ship.localeDir\` (${S}) contains no \`.mo\` catalogue. Declaring a locale directory that ships nothing is a promise the package does not keep.`);return N}function withoutForeignEntries(n,S,C,N,F){if(N.length===0)return n;let I=new Set;for(let n of N){let N=As(n)?n:Os(C,n);if(N===F)continue;let H=Ms(S,N);H===``||H.startsWith(`..`)||As(H)||I.add(H.split(zs).join(xs.sep))}return n.filter(n=>!I.has(n))}function resolveBundle(n){let S=n.declaredBundle;if(S===void 0)throw Error("gjsify ship: no bundle to ship. Set `gjsify.main` (or `main`) in package.json to the built bundle, or `gjsify.ship.bundle` to override it.");let C=As(S)?S:Os(n.projectDir,S);if(!existsSync(C))throw Error(`gjsify ship: the bundle ${S} does not exist. Build it first (\`gjsify run build\`), or drop \`--skip-build\`.`);return C}function discoverIcons(n,S){if(S!==void 0){let C=Os(n,S);if(!existsSync(C))throw Error(`gjsify ship: the configured icon path ${S} does not exist.`);return statSync(C).isDirectory()?listIcons(C):[C]}for(let S of[`data/icons`,`data/icons/hicolor`]){let C=js(n,S);if(existsSync(C)&&statSync(C).isDirectory()){let n=listIcons(C);if(n.length>0)return n}}return[]}function listIcons(n){return listFilesRecursive(n).filter(n=>RR.some(S=>n.toLowerCase().endsWith(S))).map(S=>js(n,S.split(`/`).join(zs))).sort()}function discoverFonts(n,S){let C=S??`data/fonts`,N=S===void 0?js(n,`data`,`fonts`):Os(n,S);if(!existsSync(N)){if(S===void 0)return[];throw Error(`gjsify ship: the configured font path ${S} does not exist.`)}if(!statSync(N).isDirectory()){if(assertNotWebFont(N,C),!zR.some(n=>N.toLowerCase().endsWith(n)))throw Error(`gjsify ship: \`gjsify.ship.fonts\` names ${S}, which is not a font face fontconfig will open (${zR.join(`, `)}). A file it cannot read installs and is never found, and Pango substitutes a fallback family rather than reporting anything.`);return[N]}let F=[];for(let n of listFilesRecursive(N))assertNotWebFont(n,C),zR.some(S=>n.toLowerCase().endsWith(S))&&F.push(js(N,n.split(`/`).join(zs)));if(F.length===0&&S!==void 0)throw Error(`gjsify ship: \`gjsify.ship.fonts\` (${S}) holds no font face (${zR.join(`, `)}). Declaring fonts that ship nothing is a promise the package does not keep — and its symptom is a substituted family, not an error.`);return F.sort()}function assertNotWebFont(n,S){let C=n.toLowerCase(),N=BR.find(n=>C.endsWith(n));if(N!==void 0)throw Error(`gjsify ship: \`gjsify.ship.fonts\` (${S}) carries ${n}, and \`${N}\` is a web-font wrapper whose support is a FreeType BUILD option — brotli for woff2, zlib for woff. Whether it opens is therefore a property of the FreeType the SHIPPED artifact loads (inside \`@gjsify/gtk-runtime-<target>\` for a \`.app\` or a Windows program directory), not of the machine that packaged it. Ship the desktop face instead (${zR.join(`, `)}); a font that fails to open is not an error, it is Pango quietly substituting a different typeface.`)}function discoverSchemas(n,S){let C=S===void 0?[js(n,`data`)]:[Os(n,S)];for(let n of C){if(!existsSync(n)){if(S!==void 0)throw Error(`gjsify ship: the configured schema path ${S} does not exist.`);continue}if(!statSync(n).isDirectory())return[n];let C=listFilesRecursive(n).filter(n=>n.endsWith(`.gschema.xml`)).map(S=>js(n,S.split(`/`).join(zs))).sort();if(C.length>0)return C}return[]}function discoverLicense(n,S){if(S!==void 0){let C=Os(n,S);if(!existsSync(C))throw Error(`gjsify ship: the configured licence file ${S} does not exist.`);return C}for(let S of licenseSearchDirs(n))for(let n of FR){let C=js(S,n);if(existsSync(C))return C}}function discoverChangelog(n,S){if(S!==void 0){let C=Os(n,S);if(!existsSync(C))throw Error(`gjsify ship: the configured changelog file ${S} does not exist.`);return C}for(let S of licenseSearchDirs(n))for(let n of IR){let C=js(S,n);if(existsSync(C))return C}}function licenseSearchDirs(n){let S=[];for(let C=n;;){if(S.push(C),isProjectRoot(C))return S;let N=Ps(C);if(N===C)return[n];C=N}}function isProjectRoot(n){if(existsSync(js(n,`.git`)))return!0;let S=js(n,`package.json`);if(!existsSync(S))return!1;try{return JSON.parse(readFileSync(S,`utf-8`)).workspaces!==void 0}catch{return!1}}function listFilesRecursive(n){let S=[],walk=C=>{for(let N of readdirSync(C,{withFileTypes:!0}).sort((n,S)=>n.name<S.name?-1:1)){let F=js(C,N.name);if(N.isDirectory())walk(F);else if(N.isSymbolicLink())throw Error(`gjsify ship: ${F} is a symlink. The payload has to be self-contained — replace it with the file it points at, or exclude it from the bundle directory.`);else N.isFile()&&S.push(xs.join(...Ms(n,F).split(zs)))}};return walk(n),S.sort()}var RR,zR,BR,VR=__esmMin(()=>{Vl(),Hs(),LR(),RR=[`.svg`,`.png`],zR=[`.ttf`,`.otf`,`.ttc`,`.otc`],BR=[`.woff`,`.woff2`,`.eot`]});function isNodeRuntimeTarget(n){return HR.includes(n)}function nodeRuntimePackageName(n){return`@gjsify/node-runtime-${n}`}function nodeRuntimeBinaryName(n){return n.startsWith(`win32-`)?`node.exe`:`node`}function resolveNodeRuntime(n,S={}){let C=S.env??process.env,N=nodeRuntimeBinaryName(n),F=C.GJSIFY_NODE_RUNTIME;if(F){let n=complete(`GJSIFY_NODE_RUNTIME`,F,N);if(n)return n}let I=nodeRuntimePackageName(n),H=resolveInstalledPackage(I,{cwd:S.cwd,bundleUrl:import.meta.url});return H===null?null:complete(I,js(Ps(H),`bin`),N)}function complete(n,S,C){let N=js(S,C),F=js(S,`LICENSE`);return!existsSync(N)||!existsSync(F)?null:{source:n,binDir:S,nodePath:N,licensePath:F}}var HR,UR=__esmMin(()=>{Vl(),Hs(),YM(),HR=[`darwin-arm64`,`darwin-x64`,`win32-x64`]});function rfc822(n){let S=new Date(n*1e3),pad=n=>String(n).padStart(2,`0`);return`${WR[S.getUTCDay()]}, ${pad(S.getUTCDate())} ${GR[S.getUTCMonth()]} ${S.getUTCFullYear()} ${pad(S.getUTCHours())}:${pad(S.getUTCMinutes())}:${pad(S.getUTCSeconds())} +0000`}function changelogEntriesFor(n,S){let C=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),N=RegExp(`^##+[ \\t]+\\[?${C}\\]?[^\\n]*$`,`m`).exec(S);if(N===null)return[];let F=S.slice(N.index+N[0].length),I=/^##[ \t]+\[?\d/m.exec(F),H=I===null?F:F.slice(0,I.index),W=[];for(let n of H.split(`
|
|
1093
|
+
`)){let S=/^[*-][ \t]+(.*\S)\s*$/.exec(n);S!==null&&W.push(S[1].replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\*\*([^*]+)\*\*/g,`$1`).replace(/\s+/g,` `).trim())}return W}function wrapEntry(n){let S=[],C=` *`;for(let N of n.split(/\s+/))N!==``&&(C.length+1+N.length>KR&&C!==` *`&&C!==` `&&(S.push(C),C=` `),C+=` ${N}`);return S.push(C),S}function renderDebianChangelog(n,S,C){let N=S===void 0?[]:changelogEntriesFor(n.version,S),F=n.homepage?`Release ${n.version}. See ${n.homepage} for the upstream changes.`:`Release ${n.version}.`,I=(N.length>0?N:[F]).flatMap(wrapEntry);return[`${n.binaryName} (${n.version}-${n.release}) unstable; urgency=medium`,``,...I,``,` -- ${n.maintainer} ${rfc822(C)}`,``].join(`
|
|
1094
|
+
`)}var WR,GR,KR,qR=__esmMin(()=>{WR=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],GR=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],KR=80});function planStage(n,S){let C=[],N=`lib/${n.binaryName}`;C.push({path:`bin/${n.binaryName}`,mode:493,source:{kind:`text`,text:S.launcher}});for(let F of S.bundleFiles)C.push({path:xs.join(N,F),mode:isExecutableAsset(F)?493:420,source:{kind:`file`,path:xs.join(n.bundleDir,F)}});if(C.push({path:`${FL.metainfo}/${n.appId}.metainfo.xml`,mode:420,source:{kind:`text`,text:S.metainfo}}),n.kind===`app`){if(S.desktopEntry===void 0)throw Error('gjsify ship: internal error — a desktop entry is required for `kind: "app"`.');C.push({path:`${FL.applications}/${n.appId}.desktop`,mode:420,source:{kind:`text`,text:S.desktopEntry}});for(let S of planIcons(n))C.push(S)}for(let S of n.schemaFiles){let N=Fs(S);if(!N.startsWith(n.appId))throw Error(`gjsify ship: the GSettings schema ${N} must be named \`${n.appId}[.…].gschema.xml\`. Every installed schema shares one system directory, so the app id is what keeps it unique.`);C.push({path:`${FL.schemas}/${N}`,mode:420,source:{kind:`file`,path:S}})}for(let S of n.typelibFiles)C.push({path:xs.join(N,`gi`,Fs(S)),mode:493,source:{kind:`file`,path:S}});n.mimeTypes.length>0&&C.push({path:`${FL.mime}/${n.appId}.xml`,mode:420,source:{kind:`text`,text:renderMimePackage(n.mimeTypes)}});for(let S of n.localeFiles)C.push({path:xs.join(FL.locale,S.rel),mode:420,source:{kind:`file`,path:S.abs}});for(let S of planFonts(n))C.push(S);for(let[S,N]of Object.entries(n.extraFiles))C.push({path:assertInsidePrefix(S),mode:420,source:{kind:`file`,path:N}});return normalise(C)}function planFonts(n){let S=[],C=new Map;for(let N of n.fontFiles){let F=`${FL.fonts}/${n.appId}/${Fs(N)}`,I=C.get(F);if(I!==void 0)throw Error(`gjsify ship: ${N} and ${I} both install as ${F}. Two faces cannot share one filename — one would silently not ship, and a missing face is a substituted typeface rather than an error. Rename one, or point \`gjsify.ship.fonts\` at a directory holding only the faces you mean to ship.`);C.set(F,N),S.push({path:F,mode:420,source:{kind:`file`,path:N}})}return S}async function planOverlay(n,S,C){if(C.licenseText===void 0)throw Error(`gjsify ship: no licence file found, so the ${S.id} package would ship no ${S.licenseDest(n.binaryName)}. Debian Policy § 12.5 requires it and lintian errors without it, and neither dpkg nor rpm will tell you it is missing. Add a LICENSE file to ${n.projectDir} or to the root of its repository, or point \`gjsify.ship.licenseFile\` at the one this package ships under.`);let N=S.licenseKind===`debian-copyright`?renderDebianCopyright(n,C.licenseText):C.licenseText,F=[{path:S.licenseDest(n.binaryName),mode:420,source:{kind:`text`,text:N}}];if(S.changelogDest!==void 0){let N=renderDebianChangelog(n,C.changelogText,C.mtime);F.push({path:S.changelogDest(n.binaryName),mode:420,source:{kind:`bytes`,data:await gzipDeterministic(new TextEncoder().encode(N))}})}return F}function assertOverlayIsLicensed(n,S,C){if(!(C.length>0))throw Error(`gjsify ship: this stage carries no ${n} licence overlay, so the package would ship no licence file for ${S} — Debian Policy § 12.5 requires one and lintian errors without it. The fix is on the assembling host, not this one: give that project a LICENSE (or set \`gjsify.ship.licenseFile\`) and re-run the \`--stage\` phase.`)}function renderDebianCopyright(n,S){let C=S.trimEnd().split(`
|
|
1093
1095
|
`).map(n=>n.trim()===``?` .`:` ${n}`).join(`
|
|
1094
1096
|
`);return[`Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/`,`Upstream-Name: ${n.name}`,...n.homepage?[`Source: ${n.homepage}`]:[],``,`Files: *`,`Copyright: ${n.maintainer}`,`License: ${n.license}`,C,``].join(`
|
|
1095
|
-
`)}function planIcons(n){let S=[],C=new Map;for(let N of n.iconFiles){let F=Is(N),I=iconSizeDir(N),H=`${PL.icons}/${I}/apps/${n.appId}${F}`,W=C.get(H);if(W!==void 0)throw Error(`gjsify ship: ${N} and ${W} both install as ${H}. Icon size is read from the path (\`.../128x128/...\`) or the filename (\`icon-128.png\`); give them distinguishable sizes or point \`gjsify.ship.icon\` at a single file.`);C.set(H,N),S.push({path:H,mode:420,source:{kind:`file`,path:N}})}return S}function iconSizeDir(n){if(Is(n).toLowerCase()===`.svg`)return`scalable`;let S=/(?:^|[\\/])(\d{1,4})x\1(?:[\\/]|$)/.exec(n);if(S)return`${S[1]}x${S[1]}`;let C=Fs(n,Is(n)).split(/[-_.]/);for(let n=C.length-1;n>=0;n--){let S=C[n];if(S!==void 0&&/^\d{1,4}$/.test(S))return`${S}x${S}`}throw Error(`gjsify ship: cannot tell what size ${n} is. Put it in a \`<size>x<size>/\` directory, end its name with the size (\`icon-128.png\`), or ship an SVG.`)}function assertInsidePrefix(n){let S=xs.normalize(n);if(xs.isAbsolute(S)||S===`..`||S.startsWith(`../`))throw Error(`gjsify ship: \`gjsify.ship.extraFiles\` destination "${n}" escapes the install prefix. Destinations are relative to the prefix, e.g. \`share/applications/extra.desktop\`.`);return S}function isExecutableAsset(n){return/\.(so|node|dylib)(\.\d+)*$/.test(n)}function normalise(n){let S=new Map;for(let C of n)S.set(C.path,C);return[...S.values()].sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}var HR=__esmMin(()=>{OR(),FL(),Hs()});function isGtkRuntimeTarget(n){return UR.includes(n)}function gtkRuntimePackageName(n){return`@gjsify/gtk-runtime-${n}`}function resolveGtkRuntime(n,S={}){let C=S.env??process.env,N=n.startsWith(`win32-`)?`bin`:`lib`,F=[],I=C.GJSIFY_GTK_RUNTIME;I&&F.push({source:`GJSIFY_GTK_RUNTIME`,dir:I});let H=resolveNodeGiRoot(S);H!==null&&(F.push({source:`${GR}/prebuilds/${n}`,dir:js(H,`prebuilds`,n,`gtk`)}),F.push({source:`${GR} sibling`,dir:js(H,`..`,`gtk-runtime-${n}`,`gtk`)}));let W=gtkRuntimePackageName(n),q=resolveStagedPackage(W,S);q!==null&&F.push({source:W,dir:js(Ps(q),`gtk`)});for(let n of F){let S=js(n.dir,N),C=js(n.dir,`girepository-1.0`);if(!(!existsSync(S)||!existsSync(C)))return{source:n.source,dir:n.dir,libDir:S,typelibDir:C}}return null}function resolveNodeGiAddon(n,S={}){let C=resolveNodeGiRoot(S);if(C===null)return null;let N=js(C,`prebuilds`,n,WR);return existsSync(N)?{source:GR,addonPath:N}:null}function resolveNodeGiRoot(n){let S=resolveStagedPackage(GR,n);return S===null?null:Ps(S)}function resolveStagedPackage(n,S){let C={bundleUrl:import.meta.url};return S.cwd!==void 0&&(C.cwd=S.cwd),S.resolve!==void 0&&(C.resolve=S.resolve),resolveInstalledPackage(n,C)}function resolveNodeGiPackage(n={}){let S=resolveNodeGiRoot(n);if(S===null)return null;let C=[`package.json`];for(let n of readdirSync(S,{withFileTypes:!0}).sort((n,S)=>n.name<S.name?-1:1))n.isFile()&&n.name.endsWith(`.js`)&&C.push(n.name);let N=js(S,`overrides`);if(existsSync(N))for(let n of listFilesRecursive(N))C.push(xs.join(`overrides`,n));return C.length>1?{source:GR,root:S,files:C.sort()}:null}function appRuntimePaths(n,S,C){let N=n.dirs(S),F=xs.join(N.native,`node-gi`),I=xs.join(F,`prebuilds`,C);return{nodeGiRoot:F,nodeGiPackageDir:xs.join(N.bundle,`node_modules`,GR),prebuildDir:I,gtkDir:xs.join(I,`gtk`),addonPath:xs.join(I,WR),interpreterPath:xs.join(N.launcher,nodeRuntimeBinaryName(C)),interpreterLicensePath:xs.join(N.data,`licenses`,`node`,`LICENSE`)}}function stageAppRuntime(n){let S=appRuntimePaths(n.layout,n.identity,n.target),C=[],N={},F=[],I=[];n.interpreter===null?I.push(`no bundled interpreter — install \`@gjsify/node-runtime-${n.target}\` (or point \`GJSIFY_NODE_RUNTIME\` at a \`bin/\` directory holding \`node\` and its \`LICENSE\`)`):(C.push({path:S.interpreterPath,mode:493,source:{kind:`file`,path:n.interpreter.nodePath}}),C.push({path:S.interpreterLicensePath,mode:420,source:{kind:`file`,path:n.interpreter.licensePath}}),N.interpreter=S.interpreterPath,F.push(`interpreter from ${n.interpreter.source}`));let H=resolveGtkRuntime(n.target,discoveryOptions(n));if(H!==null){for(let n of listFilesRecursive(H.dir)){let N=js(H.dir,n.split(`/`).join(zs));C.push({path:xs.join(S.gtkDir,n),mode:stagedMode(n,N),source:{kind:`file`,path:N}})}N.gtkRuntimeDir=S.gtkDir,F.push(`GTK closure from ${H.source}`)}else{let S=n.target.startsWith(`win32-`)?`bin`:`lib`;I.push(`no GTK closure — install \`${gtkRuntimePackageName(n.target)}\` (or point \`GJSIFY_GTK_RUNTIME\` at a bundle directory holding \`${S}/\` and \`girepository-1.0/\`)`)}let W=resolveNodeGiPackage(discoveryOptions(n));if(W!==null){for(let n of W.files)C.push({path:xs.join(S.nodeGiPackageDir,n),mode:420,source:{kind:`file`,path:js(W.root,n.split(`/`).join(zs))}});F.push(`node-gi runtime (${W.files.length} file(s)) from ${W.source}`)}else I.push(`no node-gi JavaScript — install \`${GR}\`; a \`--app node\` bundle keeps \`@gjsify/node-gi/*\` external, so the staged bundle would \`require\` a package the artifact does not carry`);let q=resolveNodeGiAddon(n.target,discoveryOptions(n));return q===null?I.push(`no node-gi addon — install \`${GR}\`, whose \`prebuilds/${n.target}/${WR}\` is the binary built against that closure`):(C.push({path:S.addonPath,mode:493,source:{kind:`file`,path:q.addonPath}}),N.nodeGiAddon=S.addonPath,F.push(`node-gi addon from ${q.source}`)),{files:C,launcher:N,found:F,missing:I}}function discoveryOptions(n){let S={};return n.cwd!==void 0&&(S.cwd=n.cwd),n.env!==void 0&&(S.env=n.env),n.resolve!==void 0&&(S.resolve=n.resolve),S}function stagedMode(n,S){if(isExecutableAsset(n)||n.startsWith(`libexec/`)||n.startsWith(`bin/`))return 493;try{if(statSync(S).mode&73)return 493}catch{}return 420}var UR,WR,GR,KR=__esmMin(()=>{Vl(),Hs(),zR(),VR(),HR(),YM(),UR=[`darwin-arm64`,`darwin-x64`,`win32-x64`],WR=`node_gi.node`,GR=`@gjsify/node-gi`});function dmgVolumeName(n){let S=n.name;if(S.trim()===``)throw Error("gjsify ship: the macOS image has no name to call its volume — `gjsify.ship.name` (or the package name it is derived from) is empty. `hdiutil` would accept that and mount the image as `untitled`, which is the name every nameless disk image on the machine has.");if(JR.test(S))throw Error(`gjsify ship: the macOS image would mount a volume called "${S}", and HFS+ cannot hold it: the Finder shows a stored ":" as a "/" and a stored "/" as a ":", so the volume would not be the one this project named. Set \`gjsify.ship.name\` to the display name you want.`);return S}function hdiutilCreateArgs(n){return[`create`,`-format`,`UDZO`,`-fs`,`HFS+J`,`-volname`,n.volumeName,`-srcfolder`,n.sourceDir,`-ov`,`-quiet`,n.target]}async function buildDmgImage(n){let S=hdiutilCreateArgs(n);n.verbose&&ve.log(`[gjsify ship] ${qR} ${S.join(` `)}`);let C=await spawnToCompletion(qR,S,{completion:`return`,cwd:n.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${qR} is not on PATH. It ships with macOS and cannot be installed anywhere else, so this is either a broken macOS installation or a host that is not macOS at all. A \`.dmg\` is packed on darwin (ADR 0024 § A1); from anywhere else the route is \`gjsify ship darwin --stage\` here and \`gjsify ship --from-stage <dir> --target macos-app-dmg\` there.`)});if(C.code!==0)throw Error(`gjsify ship: ${qR} failed with ${describeExit(C)}.`)}function dmgVolumeDir(n){return js(n,`dmg`,`volume`)}var qR,JR,YR=__esmMin(()=>{ye(),Hs(),_P(),qR=`hdiutil`,JR=/[/:]/});function renderShipFlatpakManifest(n){let{settings:S,stageDir:C,overlayDir:N}=n,F=S.flatpak,I={id:S.appId,runtime:F.runtime,"runtime-version":F.runtimeVersion,sdk:F.sdk,branch:F.branch,command:S.binaryName,"finish-args":F.finishArgs};return F.sdkExtensions.length>0&&(I[`sdk-extensions`]=F.sdkExtensions),F.appendPath.length>0&&(I[`build-options`]={"append-path":F.appendPath.join(`:`)}),F.cleanup.length>0&&(I.cleanup=F.cleanup),I.modules=[{name:S.binaryName,buildsystem:`simple`,"build-commands":[`mkdir -p /app`,`cp -a stage/. /app/`,`cp -a overlay/. /app/`],sources:[{type:`dir`,path:C,dest:`stage`,skip:[n.stageManifestFile]},{type:`dir`,path:N,dest:`overlay`}]}],I}async function buildFlatpakBundle(n){let{settings:S,workDir:C,archLabel:N}=n,F=js(C,`${S.appId}.json`),I=js(C,`build`),H=js(C,`repo`),W=js(C,`state`);mkdirSync(C,{recursive:!0}),rmSync(H,{recursive:!0,force:!0,maxRetries:5}),writeFileSync(F,`${JSON.stringify(renderShipFlatpakManifest(n),null,2)}\n`),await run$1(`flatpak-builder`,[`--force-clean`,`--disable-rofiles-fuse`,`--delete-build-dirs`,`--state-dir=${W}`,`--arch=${N}`,`--repo=${H}`,I,F],n,"flatpak-builder not found. Install it (Fedora: `sudo dnf install flatpak-builder`)."),await run$1(`flatpak`,[`build-bundle`,`--arch=${N}`,H,n.target,S.appId,S.flatpak.branch],n,`flatpak not found. Install it via your distro: see https://flathub.org/setup.`)}async function run$1(n,S,C,N){C.verbose&&ve.log(`[gjsify ship] ${n} ${S.join(` `)}`);let F=await spawnToCompletion(n,S,{completion:`return`,cwd:C.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${N}`)});if(F.code!==0)throw Error(`gjsify ship: ${n} failed with ${describeExit(F)}.`)}var XR=__esmMin(()=>{ye(),Vl(),Hs(),_P(),__name$1(run$1,`run`)});function localeOf(n){return n.split(`/`)[0]??``}function fold(n,S,C,N,F){let I=js(F,`source${C}`);return writeFileSync(I,S),readFileSync(mergeCatalogues({mode:n,template:I,extension:C,catalogues:N,workDir:F}),`utf-8`)}function localizeMetadata(n,S){if(S.length===0)return n;let C=mkdtempSync(js(tmpdir(),`gjsify-ship-l10n-`));try{let N=[...S].sort((n,S)=>n.rel<S.rel?-1:+(n.rel>S.rel)),F=new Map;for(let[n,S]of N.entries()){let N=js(C,`${n}.po`);execFileSync(`msgunfmt`,[S.abs,`--output-file`,N],{stdio:`pipe`});let I=localeOf(S.rel);F.set(I,[...F.get(I)??[],N])}let I=[...F].map(([n,S])=>({locale:n,po:S.length===1?S[0]:msgcat(S,js(C,`${n}.merged.po`))}));return{metainfo:fold(`--xml`,n.metainfo,`.metainfo.xml`,I,C),desktopEntry:n.desktopEntry===void 0?void 0:fold(`--desktop`,n.desktopEntry,`.desktop`,I,C)}}catch(n){throw Error(describeFailure(n,S.length))}finally{rmSync(C,{recursive:!0,force:!0})}}function msgcat(n,S){return execFileSync(`msgcat`,[`--use-first`,`--output-file`,S,...n],{stdio:`pipe`}),S}function describeFailure(n,S){let C=n;return C?.code===`ENOENT`?`gjsify ship: \`msgfmt\`/\`msgunfmt\`/\`msgcat\` are not on PATH, but the package stages ${S} gettext catalogue(s). Install them (package: gettext) — shipping the metadata untranslated would install an English app menu entry for a translated app, which nothing downstream can detect.`:`gjsify ship: could not fold the gettext catalogues into the freedesktop metadata.${C?.stderr===void 0?``:`\n${String(C.stderr).trim()}`}`}var ZR=__esmMin(()=>{Dh(),Vl(),Dm(),Hs(),AI()});function lookupArch(n,S,C){let N=n[S];if(!N)throw Error(`gjsify ship: no ${C} architecture is known for \`process.arch\` "${S}". Known: ${Object.keys(n).join(`, `)}.`);return N}function debArch(n,S){return S?`all`:lookupArch(QR,n,`Debian`)}function rpmArch(n,S){return S?`noarch`:lookupArch($R,n,`RPM`)}function flatpakArch(n,S){return lookupArch(ez,n,`Flatpak`)}function macosArch(n,S){return lookupArch(tz,n,`macOS`)}function windowsArch(n,S){return lookupArch(nz,n,`Windows`)}function windowsNameIsUnusable(n){return rz.test(n)||iz.test(n)||/[. ]$/.test(n)?!0:[...n].some(n=>(n.codePointAt(0)??0)<32)}function windowsProgramDirName(n){let S=n.name;if(S.trim()===``)throw Error("gjsify ship: the windows layout has no name to call the program directory — `gjsify.ship.name` (or the package name it is derived from) is empty. The artifact IS a directory and its zip expands into one, so an empty name would unpack `app\\`, `share\\` and the launcher loose into whatever folder the user was in.");if(windowsNameIsUnusable(S))throw Error(`gjsify ship: the windows layout would put this app in a directory called "${S}", and Windows cannot hold it: it reserves < > : " / \\ | ? * and the control characters, reserves CON, PRN, AUX, NUL, COM1-9 and LPT1-9 as device names at every path, and silently strips a trailing dot or space.
|
|
1097
|
+
`)}function planIcons(n){let S=[],C=new Map;for(let N of n.iconFiles){let F=Is(N),I=iconSizeDir(N),H=`${FL.icons}/${I}/apps/${n.appId}${F}`,W=C.get(H);if(W!==void 0)throw Error(`gjsify ship: ${N} and ${W} both install as ${H}. Icon size is read from the path (\`.../128x128/...\`) or the filename (\`icon-128.png\`); give them distinguishable sizes or point \`gjsify.ship.icon\` at a single file.`);C.set(H,N),S.push({path:H,mode:420,source:{kind:`file`,path:N}})}return S}function iconSizeDir(n){if(Is(n).toLowerCase()===`.svg`)return`scalable`;let S=/(?:^|[\\/])(\d{1,4})x\1(?:[\\/]|$)/.exec(n);if(S)return`${S[1]}x${S[1]}`;let C=Fs(n,Is(n)).split(/[-_.]/);for(let n=C.length-1;n>=0;n--){let S=C[n];if(S!==void 0&&/^\d{1,4}$/.test(S))return`${S}x${S}`}throw Error(`gjsify ship: cannot tell what size ${n} is. Put it in a \`<size>x<size>/\` directory, end its name with the size (\`icon-128.png\`), or ship an SVG.`)}function assertInsidePrefix(n){let S=xs.normalize(n);if(xs.isAbsolute(S)||S===`..`||S.startsWith(`../`))throw Error(`gjsify ship: \`gjsify.ship.extraFiles\` destination "${n}" escapes the install prefix. Destinations are relative to the prefix, e.g. \`share/applications/extra.desktop\`.`);return S}function isExecutableAsset(n){return/\.(so|node|dylib)(\.\d+)*$/.test(n)}function normalise(n){let S=new Map;for(let C of n)S.set(C.path,C);return[...S.values()].sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}var JR=__esmMin(()=>{qR(),PL(),kR(),IL(),Hs()});function isGtkRuntimeTarget(n){return YR.includes(n)}function gtkRuntimePackageName(n){return`@gjsify/gtk-runtime-${n}`}function resolveGtkRuntime(n,S={}){let C=S.env??process.env,N=n.startsWith(`win32-`)?`bin`:`lib`,F=[],I=C.GJSIFY_GTK_RUNTIME;I&&F.push({source:`GJSIFY_GTK_RUNTIME`,dir:I});let H=resolveNodeGiRoot(S);H!==null&&(F.push({source:`${ZR}/prebuilds/${n}`,dir:js(H,`prebuilds`,n,`gtk`)}),F.push({source:`${ZR} sibling`,dir:js(H,`..`,`gtk-runtime-${n}`,`gtk`)}));let W=gtkRuntimePackageName(n),q=resolveStagedPackage(W,S);q!==null&&F.push({source:W,dir:js(Ps(q),`gtk`)});for(let n of F){let S=js(n.dir,N),C=js(n.dir,`girepository-1.0`);if(!(!existsSync(S)||!existsSync(C)))return{source:n.source,dir:n.dir,libDir:S,typelibDir:C}}return null}function resolveNodeGiAddon(n,S={}){let C=resolveNodeGiRoot(S);if(C===null)return null;let N=js(C,`prebuilds`,n,XR);return existsSync(N)?{source:ZR,addonPath:N}:null}function resolveNodeGiRoot(n){let S=resolveStagedPackage(ZR,n);return S===null?null:Ps(S)}function resolveStagedPackage(n,S){let C={bundleUrl:import.meta.url};return S.cwd!==void 0&&(C.cwd=S.cwd),S.resolve!==void 0&&(C.resolve=S.resolve),resolveInstalledPackage(n,C)}function resolveNodeGiPackage(n={}){let S=resolveNodeGiRoot(n);if(S===null)return null;let C=[`package.json`];for(let n of readdirSync(S,{withFileTypes:!0}).sort((n,S)=>n.name<S.name?-1:1))n.isFile()&&n.name.endsWith(`.js`)&&C.push(n.name);let N=js(S,`overrides`);if(existsSync(N))for(let n of listFilesRecursive(N))C.push(xs.join(`overrides`,n));return C.length>1?{source:ZR,root:S,files:C.sort()}:null}function appRuntimePaths(n,S,C){let N=n.dirs(S),F=xs.join(N.native,`node-gi`),I=xs.join(F,`prebuilds`,C);return{nodeGiRoot:F,nodeGiPackageDir:xs.join(N.bundle,`node_modules`,ZR),prebuildDir:I,gtkDir:xs.join(I,`gtk`),addonPath:xs.join(I,XR),interpreterPath:xs.join(N.launcher,nodeRuntimeBinaryName(C)),interpreterLicensePath:xs.join(N.data,`licenses`,`node`,`LICENSE`)}}function stageAppRuntime(n){let S=appRuntimePaths(n.layout,n.identity,n.target),C=[],N={},F=[],I=[];n.interpreter===null?I.push(`no bundled interpreter — install \`@gjsify/node-runtime-${n.target}\` (or point \`GJSIFY_NODE_RUNTIME\` at a \`bin/\` directory holding \`node\` and its \`LICENSE\`)`):(C.push({path:S.interpreterPath,mode:493,source:{kind:`file`,path:n.interpreter.nodePath}}),C.push({path:S.interpreterLicensePath,mode:420,source:{kind:`file`,path:n.interpreter.licensePath}}),N.interpreter=S.interpreterPath,F.push(`interpreter from ${n.interpreter.source}`));let H=resolveGtkRuntime(n.target,discoveryOptions(n));if(H!==null){for(let n of listFilesRecursive(H.dir)){let N=js(H.dir,n.split(`/`).join(zs));C.push({path:xs.join(S.gtkDir,n),mode:stagedMode(n,N),source:{kind:`file`,path:N}})}N.gtkRuntimeDir=S.gtkDir,F.push(`GTK closure from ${H.source}`)}else{let S=n.target.startsWith(`win32-`)?`bin`:`lib`;I.push(`no GTK closure — install \`${gtkRuntimePackageName(n.target)}\` (or point \`GJSIFY_GTK_RUNTIME\` at a bundle directory holding \`${S}/\` and \`girepository-1.0/\`)`)}let W=resolveNodeGiPackage(discoveryOptions(n));if(W!==null){for(let n of W.files)C.push({path:xs.join(S.nodeGiPackageDir,n),mode:420,source:{kind:`file`,path:js(W.root,n.split(`/`).join(zs))}});F.push(`node-gi runtime (${W.files.length} file(s)) from ${W.source}`)}else I.push(`no node-gi JavaScript — install \`${ZR}\`; a \`--app node\` bundle keeps \`@gjsify/node-gi/*\` external, so the staged bundle would \`require\` a package the artifact does not carry`);let q=resolveNodeGiAddon(n.target,discoveryOptions(n));return q===null?I.push(`no node-gi addon — install \`${ZR}\`, whose \`prebuilds/${n.target}/${XR}\` is the binary built against that closure`):(C.push({path:S.addonPath,mode:493,source:{kind:`file`,path:q.addonPath}}),N.nodeGiAddon=S.addonPath,F.push(`node-gi addon from ${q.source}`)),{files:C,launcher:N,found:F,missing:I}}function discoveryOptions(n){let S={};return n.cwd!==void 0&&(S.cwd=n.cwd),n.env!==void 0&&(S.env=n.env),n.resolve!==void 0&&(S.resolve=n.resolve),S}function stagedMode(n,S){if(isExecutableAsset(n)||n.startsWith(`libexec/`)||n.startsWith(`bin/`))return 493;try{if(statSync(S).mode&73)return 493}catch{}return 420}var YR,XR,ZR,QR=__esmMin(()=>{Vl(),Hs(),VR(),UR(),JR(),YM(),YR=[`darwin-arm64`,`darwin-x64`,`win32-x64`],XR=`node_gi.node`,ZR=`@gjsify/node-gi`});function dmgVolumeName(n){let S=n.name;if(S.trim()===``)throw Error("gjsify ship: the macOS image has no name to call its volume — `gjsify.ship.name` (or the package name it is derived from) is empty. `hdiutil` would accept that and mount the image as `untitled`, which is the name every nameless disk image on the machine has.");if(ez.test(S))throw Error(`gjsify ship: the macOS image would mount a volume called "${S}", and HFS+ cannot hold it: the Finder shows a stored ":" as a "/" and a stored "/" as a ":", so the volume would not be the one this project named. Set \`gjsify.ship.name\` to the display name you want.`);return S}function hdiutilCreateArgs(n){return[`create`,`-format`,`UDZO`,`-fs`,`HFS+J`,`-volname`,n.volumeName,`-srcfolder`,n.sourceDir,`-ov`,`-quiet`,n.target]}async function buildDmgImage(n){let S=hdiutilCreateArgs(n);n.verbose&&ve.log(`[gjsify ship] ${$R} ${S.join(` `)}`);let C=await spawnToCompletion($R,S,{completion:`return`,cwd:n.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${$R} is not on PATH. It ships with macOS and cannot be installed anywhere else, so this is either a broken macOS installation or a host that is not macOS at all. A \`.dmg\` is packed on darwin (ADR 0024 § A1); from anywhere else the route is \`gjsify ship darwin --stage\` here and \`gjsify ship --from-stage <dir> --target macos-app-dmg\` there.`)});if(C.code!==0)throw Error(`gjsify ship: ${$R} failed with ${describeExit(C)}.`)}function dmgVolumeDir(n){return js(n,`dmg`,`volume`)}var $R,ez,tz=__esmMin(()=>{ye(),Hs(),_P(),$R=`hdiutil`,ez=/[/:]/});function renderShipFlatpakManifest(n){let{settings:S,stageDir:C,overlayDir:N}=n,F=S.flatpak,I={id:S.appId,runtime:F.runtime,"runtime-version":F.runtimeVersion,sdk:F.sdk,branch:F.branch,command:S.binaryName,"finish-args":F.finishArgs};return F.sdkExtensions.length>0&&(I[`sdk-extensions`]=F.sdkExtensions),F.appendPath.length>0&&(I[`build-options`]={"append-path":F.appendPath.join(`:`)}),F.cleanup.length>0&&(I.cleanup=F.cleanup),I.modules=[{name:S.binaryName,buildsystem:`simple`,"build-commands":[`mkdir -p /app`,`cp -a stage/. /app/`,`cp -a overlay/. /app/`],sources:[{type:`dir`,path:C,dest:`stage`,skip:[n.stageManifestFile]},{type:`dir`,path:N,dest:`overlay`}]}],I}async function buildFlatpakBundle(n){let{settings:S,workDir:C,archLabel:N}=n,F=js(C,`${S.appId}.json`),I=js(C,`build`),H=js(C,`repo`),W=js(C,`state`);mkdirSync(C,{recursive:!0}),rmSync(H,{recursive:!0,force:!0,maxRetries:5}),writeFileSync(F,`${JSON.stringify(renderShipFlatpakManifest(n),null,2)}\n`),await run$1(`flatpak-builder`,[`--force-clean`,`--disable-rofiles-fuse`,`--delete-build-dirs`,`--state-dir=${W}`,`--arch=${N}`,`--repo=${H}`,I,F],n,"flatpak-builder not found. Install it (Fedora: `sudo dnf install flatpak-builder`)."),await run$1(`flatpak`,[`build-bundle`,`--arch=${N}`,H,n.target,S.appId,S.flatpak.branch],n,`flatpak not found. Install it via your distro: see https://flathub.org/setup.`)}async function run$1(n,S,C,N){C.verbose&&ve.log(`[gjsify ship] ${n} ${S.join(` `)}`);let F=await spawnToCompletion(n,S,{completion:`return`,cwd:C.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${N}`)});if(F.code!==0)throw Error(`gjsify ship: ${n} failed with ${describeExit(F)}.`)}var nz=__esmMin(()=>{ye(),Vl(),Hs(),_P(),__name$1(run$1,`run`)});function localeOf(n){return n.split(`/`)[0]??``}function fold(n,S,C,N,F){let I=js(F,`source${C}`);return writeFileSync(I,S),readFileSync(mergeCatalogues({mode:n,template:I,extension:C,catalogues:N,workDir:F}),`utf-8`)}function localizeMetadata(n,S){if(S.length===0)return n;let C=mkdtempSync(js(tmpdir(),`gjsify-ship-l10n-`));try{let N=[...S].sort((n,S)=>n.rel<S.rel?-1:+(n.rel>S.rel)),F=new Map;for(let[n,S]of N.entries()){let N=js(C,`${n}.po`);execFileSync(`msgunfmt`,[S.abs,`--output-file`,N],{stdio:`pipe`});let I=localeOf(S.rel);F.set(I,[...F.get(I)??[],N])}let I=[...F].map(([n,S])=>({locale:n,po:S.length===1?S[0]:msgcat(S,js(C,`${n}.merged.po`))}));return{metainfo:fold(`--xml`,n.metainfo,`.metainfo.xml`,I,C),desktopEntry:n.desktopEntry===void 0?void 0:fold(`--desktop`,n.desktopEntry,`.desktop`,I,C)}}catch(n){throw Error(describeFailure(n,S.length))}finally{rmSync(C,{recursive:!0,force:!0})}}function msgcat(n,S){return execFileSync(`msgcat`,[`--use-first`,`--output-file`,S,...n],{stdio:`pipe`}),S}function describeFailure(n,S){let C=n;return C?.code===`ENOENT`?`gjsify ship: \`msgfmt\`/\`msgunfmt\`/\`msgcat\` are not on PATH, but the package stages ${S} gettext catalogue(s). Install them (package: gettext) — shipping the metadata untranslated would install an English app menu entry for a translated app, which nothing downstream can detect.`:`gjsify ship: could not fold the gettext catalogues into the freedesktop metadata.${C?.stderr===void 0?``:`\n${String(C.stderr).trim()}`}`}var rz=__esmMin(()=>{Dh(),Vl(),Dm(),Hs(),jI()});function lookupArch(n,S,C){let N=n[S];if(!N)throw Error(`gjsify ship: no ${C} architecture is known for \`process.arch\` "${S}". Known: ${Object.keys(n).join(`, `)}.`);return N}function debArch(n,S){return S?`all`:lookupArch(iz,n,`Debian`)}function rpmArch(n,S){return S?`noarch`:lookupArch(az,n,`RPM`)}function flatpakArch(n,S){return lookupArch(oz,n,`Flatpak`)}function macosArch(n,S){return lookupArch(sz,n,`macOS`)}function windowsArch(n,S){return lookupArch(cz,n,`Windows`)}function windowsNameIsUnusable(n){return lz.test(n)||uz.test(n)||/[. ]$/.test(n)?!0:[...n].some(n=>(n.codePointAt(0)??0)<32)}function windowsProgramDirName(n){let S=n.name;if(S.trim()===``)throw Error("gjsify ship: the windows layout has no name to call the program directory — `gjsify.ship.name` (or the package name it is derived from) is empty. The artifact IS a directory and its zip expands into one, so an empty name would unpack `app\\`, `share\\` and the launcher loose into whatever folder the user was in.");if(windowsNameIsUnusable(S))throw Error(`gjsify ship: the windows layout would put this app in a directory called "${S}", and Windows cannot hold it: it reserves < > : " / \\ | ? * and the control characters, reserves CON, PRN, AUX, NUL, COM1-9 and LPT1-9 as device names at every path, and silently strips a trailing dot or space.
|
|
1096
1098
|
The artifact would assemble here and be unextractable — or extract under a different name than
|
|
1097
|
-
the launcher resolves against. Set \`gjsify.ship.name\` to the display name you want on disk.`);return S}function requiredToolsOn(n,S){return Array.isArray(n)?n:n[S]??[]}function defaultFormatIds(n){return
|
|
1099
|
+
the launcher resolves against. Set \`gjsify.ship.name\` to the display name you want on disk.`);return S}function requiredToolsOn(n,S){return Array.isArray(n)?n:n[S]??[]}function defaultFormatIds(n){return hz.filter(S=>mz[S].layoutOs===n&&mz[S].host.finishOn===`any`)}function formatIdsFor(n){return hz.filter(S=>mz[S].layoutOs===n)}function assertHostCanFinish(n,S=process.platform){let{finishOn:C}=n.host;if(!(C===`any`||C.includes(S)))throw Error(`gjsify ship: a ${n.id} artifact is packed on ${C.join(` or `)} and this host is ${S} (ADR 0024 § A1: a container is produced where its format's tool lives). Assembly is not host-bound, so the way across is the two-phase split: run \`gjsify ship --stage\` here, move \`ship/stage/\` to a ${C.join(`/`)} runner, and finish with \`gjsify ship --from-stage <dir> --target ${n.id}\`.`)}function assertToolsInstalled(n,S=isOnPath,C=process.platform){let N=requiredToolsOn(n.host.requiredTools,C),F=N.filter(n=>!S(n));if(F.length===0)return;let I=n.host.installHint;throw Error(`gjsify ship: packing a ${n.id} on ${C} needs ${N.join(` and `)}, and ${F.join(`, `)} ${F.length>1?`are`:`is`} not on PATH. ${I===void 0?`Install it`:`Install it (${I})`}, or drop this target — the other formats need no tools at all. \`gjsify ship --stage\` also works without ${F.join(`/`)}: the payload is assembled by this CLI and only the container needs them.`)}function parseFormatNames(n,S){let C=n.flatMap(n=>n.split(`,`)).map(n=>n.trim()).filter(n=>n.length>0),N=C.filter(n=>!Object.hasOwn(mz,n));if(N.length>0)throw Error(`gjsify ship: unknown target${N.length>1?`s`:``} ${N.join(`, `)} in ${S}. Known targets: ${hz.join(`, `)}.`);let F=[...new Set(C)].sort();if(F.length===0)throw Error(`gjsify ship: ${S} named no format. Known targets: ${hz.join(`, `)}.`);return F}function resolveFormats(n,S){let C=parseFormatNames(n,`--target`),N=C.filter(n=>mz[n].layoutOs!==S.os);if(N.length>0){let n=formatIdsFor(S.os),C=[...new Set(N.map(n=>mz[n].layoutOs))];throw Error(`gjsify ship: ${N.join(`, `)} ${N.length>1?`wrap`:`wraps`} the ${C.join(`/`)} layout and this run assembles the ${S.name} one. `+(n.length===0?`No format wraps the ${S.name} layout — \`gjsify ship ${S.name} --stage\` assembles it and stops.`:`Formats for this layout: ${n.join(`, `)}.`)+` To build ${N.join(`, `)}, name the layout each wraps: ${C.map(n=>`\`gjsify ship ${gz[n]??n} --target ${N.filter(S=>mz[S].layoutOs===n).join(`,`)}\``).join(`, `)}.`)}return C.map(n=>mz[n])}function configuredFormats(n,S){let C=parseFormatNames(n,"`gjsify.ship.targets`");return{formats:C.filter(n=>mz[n].layoutOs===S.os).map(n=>mz[n]),dropped:C.filter(n=>mz[n].layoutOs!==S.os)}}function canCarryTicket(n){switch(n){case`macos-app`:case`macos-app-dmg`:return!0;case`macos-app-zip`:case`deb`:case`rpm`:case`flatpak`:case`windows-dir`:case`windows-dir-zip`:case`msi`:return!1;default:throw Error(`gjsify ship: no ticket answer for format "${String(n)}".`)}}var iz,az,oz,sz,cz,lz,uz,dz,fz,pz,SHARE_LICENSE_DEST,WRITTEN_HERE,mz,hz,gz,_z=__esmMin(()=>{dN(),tz(),uR(),hR(),iz={x64:`amd64`,arm64:`arm64`,ia32:`i386`,arm:`armhf`,riscv64:`riscv64`,ppc64:`ppc64el`,s390x:`s390x`},az={x64:`x86_64`,arm64:`aarch64`,ia32:`i686`,arm:`armv7hl`,riscv64:`riscv64`,ppc64:`ppc64le`,s390x:`s390x`},oz={x64:`x86_64`,arm64:`aarch64`,ia32:`i386`,arm:`arm`},sz={x64:`x86_64`,arm64:`arm64`},cz={x64:`x64`},lz=/[<>:"/\\|?*]/,uz=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i,dz=`a distro package declares its interpreter as a dependency instead of carrying one, and every distribution ships both`,fz='a `.app` a stranger downloads has to CARRY its interpreter, and there is no relocatable GJS to put in one — `packages/node-gi/scripts/build-gtk-runtime-darwin.mjs` records "GJS ships no relocation", which is why ADR 0024 § 4 derives Node on macOS and stage 7 is what would change it',pz="there is no GJS host on Windows at all (ADR 0024 § 4) — not a system one to depend on and not a relocatable one to carry — so a `--app gjs` payload cannot be shipped this way. That is why § 4 derives Node here, and why `@gjsify/node-runtime-win32-x64` exists",SHARE_LICENSE_DEST=n=>`share/licenses/${n}/LICENSE`,WRITTEN_HERE=n=>({finishOn:`any`,requiredTools:[],oracle:{readWith:n,readOn:[`linux`],selfReading:!1}}),mz={deb:{id:`deb`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`ar`,`tar`,`dpkg-deb`,`lintian`]),depends:`deb`,interpreters:[`gjs`,`node`],interpreterGap:dz,licenseDest:n=>`share/doc/${n}/copyright`,licenseKind:`debian-copyright`,changelogDest:n=>`share/doc/${n}/changelog.Debian.gz`,archName:debArch,fileName:(n,S)=>`${n.binaryName}_${n.version}-${n.release}_${S}.deb`,artifactKind:`file`},rpm:{id:`rpm`,layoutOs:`linux`,prefix:`/usr`,host:WRITTEN_HERE([`rpm`,`rpm2cpio`,`cpio`]),depends:`rpm`,interpreters:[`gjs`,`node`],interpreterGap:dz,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:rpmArch,fileName:(n,S)=>`${n.binaryName}-${n.version}-${n.release}.${S}.rpm`,artifactKind:`file`},flatpak:{id:`flatpak`,layoutOs:`linux`,prefix:`/app`,host:{finishOn:[`linux`],requiredTools:[`flatpak-builder`,`flatpak`],installHint:"Fedora: `sudo dnf install flatpak flatpak-builder`, Debian/Ubuntu: `sudo apt install flatpak flatpak-builder`",oracle:{readWith:[`flatpak`,`ostree`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`gjs`],interpreterGap:"a Flatpak runs against `org.gnome.Platform`, which ships `gjs` and no `node`. Node exists only as `org.freedesktop.Sdk.Extension.node2x`, and that extension puts node on the BUILD path, not in the runtime — so the artifact would install and then fail at `exec node`",licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:flatpakArch,fileName:(n,S)=>`${n.appId}-${n.version}-${n.release}.${S}.flatpak`,artifactKind:`file`},"macos-app":{id:`macos-app`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[fR],installHint:pR,oracle:{readWith:[`python3`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:fz,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:n=>`${n.name}.app`,artifactKind:`directory`},"macos-app-zip":{id:`macos-app-zip`,layoutOs:`darwin`,prefix:``,host:{finishOn:`any`,requiredTools:[fR],installHint:pR,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:fz,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(n,S)=>`${n.binaryName}-${n.version}-${n.release}.${S}.zip`,artifactKind:`file`},"macos-app-dmg":{id:`macos-app-dmg`,layoutOs:`darwin`,prefix:``,host:{finishOn:[`darwin`],requiredTools:[$R],installHint:"`hdiutil` is part of macOS and cannot be installed elsewhere — on a Mac it is /usr/bin/hdiutil, so an absent one means a broken installation rather than a missing package",oracle:{readWith:[`7z`,`dmg2img`,`fsck.hfsplus`],readOn:[`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:fz,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:macosArch,fileName:(n,S)=>`${n.binaryName}-${n.version}-${n.release}.${S}.dmg`,artifactKind:`file`},"windows-dir":{id:`windows-dir`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[fR],installHint:pR,oracle:{readWith:[`cmd`,`python3`],readOn:[`linux`,`win32`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:pz,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:n=>windowsProgramDirName(n),artifactKind:`directory`},"windows-dir-zip":{id:`windows-dir-zip`,layoutOs:`win32`,prefix:``,host:{finishOn:`any`,requiredTools:[fR],installHint:pR,oracle:{readWith:[`zipinfo`],readOn:[`linux`,`darwin`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:pz,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(n,S)=>`${n.binaryName}-${n.version}-${n.release}.${S}.zip`,artifactKind:`file`},msi:{id:`msi`,layoutOs:`win32`,prefix:``,host:{finishOn:[`linux`,`win32`],requiredTools:{linux:[fR,`wixl`],win32:[fR,`candle.exe`,`light.exe`]},installHint:`${pR}; the MSI compiler is Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 (https://github.com/wixtoolset/wix3/releases) with its \`bin\` directory on PATH`,oracle:{readWith:[`msiexec`,`msiinfo`],readOn:[`win32`,`linux`],selfReading:!1}},depends:null,interpreters:[`node`],interpreterGap:pz,licenseDest:SHARE_LICENSE_DEST,licenseKind:`plain`,archName:windowsArch,fileName:(n,S)=>`${n.binaryName}-${n.version}-${n.release}.${S}.msi`,artifactKind:`file`}},hz=Object.keys(mz),gz=Object.fromEntries(cR.map(n=>[sR[n].os,n]))});function uuid5(n,S){let C=n.replace(/-/g,``),N=new Uint8Array(16);for(let n=0;n<16;n+=1)N[n]=Number.parseInt(C.slice(n*2,n*2+2),16);let F=createHash(`sha1`).update(N).update(new TextEncoder().encode(S)).digest(),I=Uint8Array.from(F.subarray(0,16));I[6]=(I[6]??0)&15|80,I[8]=(I[8]??0)&63|128;let H=[...I].map(n=>n.toString(16).padStart(2,`0`)).join(``);return[H.slice(0,8),H.slice(8,12),H.slice(12,16),H.slice(16,20),H.slice(20)].join(`-`)}function msiUpgradeCode(n){return uuid5(vz,`upgrade\n${n.appId}`).toUpperCase()}function msiProductCode(n,S){let C=`product\n${n.appId}\n${n.version}\n${n.release}\n${S}`;return uuid5(vz,C).toUpperCase()}function msiComponentGuid(n,S){return uuid5(vz,`component\n${n.appId}\n${S}`).toUpperCase()}function msiProductVersion(n){let S=/^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(n);if(S===null)throw Error(`gjsify ship: "${n}" is not a version an \`.msi\` can carry. Windows Installer's \`ProductVersion\` is \`major.minor.build\` and nothing else — no prerelease suffix, no build metadata.
|
|
1098
1100
|
Dropping the suffix is not an option this command will take silently: \`1.2.0~rc.1\` and \`1.2.0\` would
|
|
1099
1101
|
become the same version, \`MajorUpgrade\` could not tell them apart, and installing one over the other
|
|
1100
1102
|
would leave both on the machine. Set \`gjsify.ship.version\` to a plain \`x.y.z\`, or drop \`msi\` from the targets.`);let[C,N,F]=[Number(S[1]),Number(S[2]),Number(S[3]??`0`)];if(C>255||N>255||F>65535)throw Error(`gjsify ship: version "${n}" is outside what Windows Installer compares — \`major\` and \`minor\` are at most 255 and \`build\` at most 65535. A field over the limit is not rejected by the installer, it is
|
|
1101
|
-
TRUNCATED, so the artifact would carry a version that is not the one it was built from. Set \`gjsify.ship.version\`.`);return`${C}.${N}.${F}`}function msiIdentifier(n,S){let C=createHash(`sha1`).update(new TextEncoder().encode(S)).digest(`hex`).slice(0,12),N=S.replace(/[^A-Za-z0-9_.]/g,`_`),F=72-n.length-2-C.length;return`${n}_${N.length>F?N.slice(N.length-F):N}_${C}`}function assertNameIsAddressable(n,S){if(n===`.`||n===`..`||n.length===0||
|
|
1103
|
+
TRUNCATED, so the artifact would carry a version that is not the one it was built from. Set \`gjsify.ship.version\`.`);return`${C}.${N}.${F}`}function msiIdentifier(n,S){let C=createHash(`sha1`).update(new TextEncoder().encode(S)).digest(`hex`).slice(0,12),N=S.replace(/[^A-Za-z0-9_.]/g,`_`),F=72-n.length-2-C.length;return`${n}_${N.length>F?N.slice(N.length-F):N}_${C}`}function assertNameIsAddressable(n,S){if(n===`.`||n===`..`||n.length===0||yz.test(n))throw Error(`gjsify ship: the payload holds "${S}", and Windows Installer cannot address the path segment "${n}". A \`FileName\` or \`DefaultDir\` cell reserves < > : " / \\ | ? * and ; (its own list separator), and
|
|
1102
1104
|
\`.\` and \`..\` are not names. The \`.msi\` would build and install the file somewhere else, or not at all.`);if(n.length>255)throw Error(`gjsify ship: the payload holds "${S}", whose segment "${n.slice(0,40)}…" is ${n.length} characters. Windows Installer's \`FileName\` column is 255.`)}function directoryTree(n){let S={path:``,name:``,children:new Map,files:[]};for(let C of[...n].sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))){let n=C.path.split(`/`),N=n.pop();if(N===void 0)throw Error(`gjsify ship: the payload holds an empty path.`);let F=S;for(let S of n){assertNameIsAddressable(S,C.path);let n=F.children.get(S)??{path:F.path===``?S:`${F.path}/${S}`,name:S,children:new Map,files:[]};F.children.set(S,n),F=n}assertNameIsAddressable(N,C.path),F.files.push(C)}return S}function renderWxs(n){let{settings:S,programDirName:C,archLabel:N}=n,F=msiProductVersion(S.version),I=S.maintainer.replace(/\s*<[^>]*>\s*$/,``).trim()||S.maintainer,H=windowsGuiLauncherPath(S),W=new Map,claim=(n,S)=>{let C=W.get(n);if(C!==void 0)throw Error(`gjsify ship: the MSI identifier "${n}" would be shared by ${C} and ${S}. Two rows cannot carry one id — one would silently replace the other.`);return W.set(n,S),n},q=[],Y=[],X=!1,emitDir=(n,C)=>{for(let N of n.files){let n=claim(msiIdentifier(`c`,N.path),N.path),F=claim(msiIdentifier(`f`,N.path),N.path);Y.push(n);let I=msiComponentGuid(S,N.path),W=xmlEscape(xs.basename(N.path));q.push(`${C}<Component Id="${n}" Guid="${I}">`),N.path===H?(X=!0,q.push(`${C} <File Id="${F}" Name="${W}" Source="${xmlEscape(N.source)}" KeyPath="yes">`),q.push(`${C} <Shortcut Id="${claim(`s_startmenu`,`the Start-Menu shortcut`)}" Directory="ProgramMenuFolder" Name="${xmlEscape(S.name)}" WorkingDirectory="INSTALLDIR" Description="${xmlEscape(S.summary)}" Advertise="yes" />`),q.push(`${C} </File>`)):q.push(`${C} <File Id="${F}" Name="${W}" Source="${xmlEscape(N.source)}" KeyPath="yes" />`),q.push(`${C}</Component>`)}for(let S of[...n.children.values()].sort((n,S)=>n.name<S.name?-1:1)){let n=claim(msiIdentifier(`d`,S.path),`the directory ${S.path}`);q.push(`${C}<Directory Id="${n}" Name="${xmlEscape(S.name)}">`),emitDir(S,`${C} `),q.push(`${C}</Directory>`)}};if(emitDir(directoryTree(n.files),` `),Y.length===0)throw Error("gjsify ship: the windows payload is empty, so there is nothing for an `.msi` to install.");if(!X)throw Error(`gjsify ship: the windows payload carries no "${H}" at the root of the program directory, so the installer would have nothing to point a Start-Menu shortcut at — an application a user installs and
|
|
1103
1105
|
cannot start. \`windows-dir\` puts the launcher there; a payload without one is a stage assembled for another layout.`);let Z=S.homepage===void 0?[]:[` <Property Id="ARPURLINFOABOUT" Value="${xmlEscape(S.homepage)}" />`];return[`<?xml version="1.0" encoding="utf-8"?>`,"<!-- Generated by `gjsify ship` (ADR 0024 stage 5). Do not edit; edit utils/ship/msi.ts. -->",`<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">`,` <Product Id="${msiProductCode(S,N)}" Name="${xmlEscape(S.name)}" Language="1033" Version="${F}" Manufacturer="${xmlEscape(I)}" UpgradeCode="${msiUpgradeCode(S)}">`,` <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" Manufacturer="${xmlEscape(I)}" Description="${xmlEscape(S.summary)}" />`,` <MajorUpgrade DowngradeErrorMessage="A newer version of ${xmlEscape(S.name)} is already installed." />`,` <Media Id="1" Cabinet="app.cab" EmbedCab="yes" />`,...Z,` <Directory Id="TARGETDIR" Name="SourceDir">`,` <Directory Id="ProgramFiles64Folder">`,` <Directory Id="INSTALLDIR" Name="${xmlEscape(C)}">`,...q,` </Directory>`,` </Directory>`,` <Directory Id="ProgramMenuFolder" />`,` </Directory>`,` <Feature Id="Main" Title="${xmlEscape(S.name)}" Level="1">`,...Y.map(n=>` <ComponentRef Id="${n}" />`),` </Feature>`,` </Product>`,`</Wix>`,``].join(`
|
|
1104
|
-
`)}function msiBackendFor(n){if(n===`linux`)return`wixl`;if(n===`win32`)return`wix3`;throw Error(`gjsify ship: no MSI compiler is wired for ${n}. \`wixl\` (msitools) is used on linux and WiX v3 on win32; assembly is not host-bound, so \`gjsify ship windows --stage\` here and \`gjsify ship --from-stage <dir> --target msi\` there is the way across.`)}async function buildMsi(n){let S=msiBackendFor(n.host??process.platform);mkdirSync(n.workDir,{recursive:!0});let C=js(n.workDir,`${n.settings.binaryName}.wxs`);if(writeFileSync(C,renderWxs(n)),S===`wixl`)return await run(`wixl`,[`-a`,n.archLabel,`-o`,n.target,C],n),C;let N=js(n.workDir,`obj`);return rmSync(N,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(N,{recursive:!0}),await run(`candle.exe`,[`-nologo`,`-arch`,n.archLabel,`-out`,`${N}\\`,C],n),await run(`light.exe`,[`-nologo`,`-out`,n.target,js(N,`${n.settings.binaryName}.wixobj`)],n),C}async function run(n,S,C){C.verbose&&ve.log(`[gjsify ship] ${n} ${S.join(` `)}`);let N=await spawnToCompletion(n,[...S],{completion:`return`,cwd:C.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${n} not found. It is the MSI compiler for this host — Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 with its \`bin\` directory on PATH.`)});if(N.code!==0)throw Error(`gjsify ship: ${n} failed with ${describeExit(N)}.`)}var fz,pz,mz,hz=__esmMin(()=>{ye(),No(),Vl(),Hs(),_P(),lR(),ER(),fz=`7b3a1f6e-0c4d-4a2b-9e51-3d8c6f2a0b14`,pz=/[<>:"/\\|?*;]/,mz=`root`});function getCrcTable(){if(Sz!==null)return Sz;let n=new Uint32Array(256);for(let S=0;S<256;S++){let C=S;for(let n=0;n<8;n++)C=C&1?3988292384^C>>>1:C>>>1;n[S]=C>>>0}return Sz=n,n}function crc32(n){let S=getCrcTable(),C=4294967295;for(let N=0;N<n.length;N++)C=S[(C^n[N])&255]^C>>>8;return(C^4294967295)>>>0}function dosDateTime(n){let S=new Date(Math.max(n,315532800)*1e3);return{date:(S.getUTCFullYear()-1980&127)<<9|S.getUTCMonth()+1<<5|S.getUTCDate(),time:S.getUTCHours()<<11|S.getUTCMinutes()<<5|Math.floor(S.getUTCSeconds()/2)}}function buildZip(n,S){let C=[...n].sort((n,S)=>n.path<S.path?-1:+(n.path>S.path)),{date:N,time:F}=dosDateTime(S),I=new TextEncoder;if(C.length>65535)throw Error(`gjsify ship: this archive would hold ${C.length} entries and a non-ZIP64 central directory records the count in 16 bits, so it would silently wrap. Nothing here writes ZIP64 yet; the payload has to shrink, or this writer has to grow the ZIP64 records.`);let H=new Writer,W=new Writer,q=0;for(let n of C){let S=I.encode(n.path),C=crc32(n.data),Y=n.data.byteLength,X=H.offset;if(X>4294967295||Y>4294967295)throw Error(`gjsify ship: ${n.path} would push this archive past 4 GiB, which a non-ZIP64 header records in 32 bits and therefore truncates. Nothing here writes ZIP64 yet.`);H.u32(gz),H.u16(xz),H.u16(2048),H.u16(yz),H.u16(F),H.u16(N),H.u32(C),H.u32(Y),H.u32(Y),H.u16(S.byteLength),H.u16(0),H.bytes(S),H.bytes(n.data),W.u32(_z),W.u16(bz),W.u16(xz),W.u16(2048),W.u16(yz),W.u16(F),W.u16(N),W.u32(C),W.u32(Y),W.u32(Y),W.u16(S.byteLength),W.u16(0),W.u16(0),W.u16(0),W.u16(0),W.u32(((32768|n.mode&4095)>>>0)*65536),W.u32(X),W.bytes(S),q+=1}let Y=W.finish(),X=new Writer;X.bytes(H.finish());let Z=X.offset;return X.bytes(Y),X.u32(vz),X.u16(0),X.u16(0),X.u16(q),X.u16(q),X.u32(Y.byteLength),X.u32(Z),X.u16(0),X.finish()}function zipEntriesFromPayload(n,S=``){let C=S===``?``:`${S}/`;return n.map(n=>({path:`${C}${n.path}`,mode:n.mode,data:n.data}))}var gz,_z,vz,yz,bz,xz,Sz,Writer,Cz=__esmMin(()=>{gz=67324752,_z=33639248,vz=101010256,yz=0,bz=788,xz=20,Sz=null,Writer=class{parts=[];length=0;get offset(){return this.length}u16(n){this.push(new Uint8Array([n&255,n>>>8&255]))}u32(n){this.push(new Uint8Array([n&255,n>>>8&255,n>>>16&255,n>>>24&255]))}bytes(n){this.push(n)}push(n){this.parts.push(n),this.length+=n.byteLength}finish(){let n=new Uint8Array(this.length),S=0;for(let C of this.parts)n.set(C,S),S+=C.byteLength;return n}}});function splitWorkspaceSpecifier(n,S){if(n.startsWith(`.`)||n.startsWith(`/`)||n.includes(`:`))return null;let C=n.split(`/`),N=n.startsWith(`@`)?[2]:[1];for(let n of N){let N=C.slice(0,n).join(`/`);if(!S.has(N))continue;let F=C.slice(n).join(`/`);return{name:N,subpath:F?`./${F}`:`.`}}return null}function literalSpecifier(n){if(n?.type===`Literal`)return typeof n.value==`string`?n.value:null;if(n?.type===`TemplateLiteral`&&n.expressions?.length===0){let S=n.quasis?.[0]?.value?.cooked;return typeof S==`string`?S:null}return null}function moduleSpecifiers$1(n){let S;try{S=parse$1(n,{ecmaVersion:`latest`,sourceType:`module`,allowHashBang:!0})}catch{return[]}let C=[],visit=n=>{if(!n||typeof n!=`object`)return;if(Array.isArray(n)){for(let S of n)visit(S);return}let S=n;if(S.type===`ImportDeclaration`||S.type===`ExportNamedDeclaration`||S.type===`ExportAllDeclaration`||S.type===`ImportExpression`){let n=literalSpecifier(S.source);n!==null&&C.push(n)}for(let[n,C]of Object.entries(S))n===`type`||n===`start`||n===`end`||n===`loc`||visit(C)};return visit(S),C}function resolveRelative(n,S){let C=Os(Ps(n),S);for(let n of[C,`${C}.js`,`${C}.mjs`,js(C,`index.js`)])try{if(statSync(n).isFile())return n}catch{}return null}function workspaceEntry(n,S){let C=n.manifest,pick=n=>{if(typeof n==`string`)return n;if(!n||typeof n!=`object`||Array.isArray(n))return null;let S=n;for(let n of[`node`,`import`,`default`,`gjs`])if(n in S){let C=pick(S[n]);if(C)return C}return null},N=null;if(typeof C.exports==`string`?N=S===`.`?C.exports:null:C.exports&&typeof C.exports==`object`&&(N=pick(C.exports[S])),!N&&S===`.`&&(N=typeof C.module==`string`?C.module:null,N??=typeof C.main==`string`?C.main:null),!N)return null;let F=Os(n.location,N);return existsSync(F)?F:null}function workspacePeers(n,S){return Object.keys(n.peerDependencies??{}).filter(n=>S.has(n))}function cliRuntimeClosure(n,S={}){let C=new Map(n.map(n=>[n.name,n])),N=new Set,F=S.entry,I=S.cliManifest;if(F===void 0||I===void 0){let n=cliPackageDir(),S=null;if(n)try{S=JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{}if(I??=S,F===void 0){let C=S?.bin,N=typeof C==`string`?C:C?.gjsify??S?.main;F=n&&N?Os(n,N):null}}for(let n of workspacePeers(I??{},C))N.add(n);if(!F||!existsSync(F))return N;let H=new Set,W=[F];for(;W.length>0;){let n=W.shift();if(H.has(n))continue;H.add(n);let S;try{S=readFileSync(n,`utf8`)}catch{continue}for(let F of moduleSpecifiers$1(S)){if(F.startsWith(`.`)){let S=resolveRelative(n,F);S&&W.push(S);continue}let S=splitWorkspaceSpecifier(F,C),I=S?C.get(S.name):void 0;if(!S||!I)continue;N.add(S.name);for(let n of workspacePeers(I.manifest,C))N.add(n);let H=workspaceEntry(I,S.subpath);H&&W.push(H)}}return N}var wz=__esmMin(()=>{Sy(),Vl(),Hs(),np(),__name$1(moduleSpecifiers$1,`moduleSpecifiers`)});function scanGiNamespaces(n){let S=new Set;for(let C of moduleSpecifiers$1(n)){let n=parseGiSpecifier(C);n!==null&&S.add(n)}return[...S].sort()}function parseGiSpecifier(n){if(!n.startsWith(`gi://`))return null;let[S,C]=n.slice(5).split(`?`,2);if(S===void 0||!/^[A-Za-z][A-Za-z0-9_]*$/.test(S))return null;if(C===void 0)return S;let N=/(?:^|&)version=([^&]+)/.exec(C)?.[1];return N===void 0?S:`${S}-${N}`}var Tz=__esmMin(()=>{wz()});function toPackSettings(n){return{binaryName:n.binaryName,appId:n.appId,name:n.name,version:n.version,release:n.release,maintainer:n.maintainer,summary:n.summary,description:n.description,license:n.license,...n.homepage===void 0?{}:{homepage:n.homepage},section:n.section,group:n.group,extraDepends:n.extraDepends,typelibPackages:n.typelibPackages,app:n.app,minGjsVersion:n.minGjsVersion,minNodeVersion:n.minNodeVersion,flatpak:n.flatpak}}function stageManifestPath(n){return js(n,Ez)}function formatTarget(n){return`${n.os}-${n.arch}`}function writeStageManifest(n){let S={};for(let C of n.formats)S[C.id]=(n.overlay.get(C.id)??[]).map(n=>{if(n.source.kind!==`text`)throw Error(`gjsify ship: internal error — the ${C.id} overlay entry ${n.path} is a file reference, and a stage manifest may only carry rendered text. Render it in \`planOverlay\` instead.`);return{path:n.path,mode:n.mode,text:n.source.text}});let C={schema:5,tool:{name:`@gjsify/cli`,version:cliVersion()},target:{os:n.settings.layoutOs,arch:n.settings.arch},formats:n.formats.map(n=>n.id),mtime:n.mtime,namespaces:[...n.namespaces],settings:toPackSettings(n.settings),staged:n.staged.map(S=>({path:S.path,mode:S.mode,bytes:statSync(js(n.stageDir,S.path.split(`/`).join(zs))).size})),overlay:S};return writeFileSync(stageManifestPath(n.stageDir),`${JSON.stringify(C,null,2)}\n`),C}function readStageManifest(n){let S=stageManifestPath(n);if(!existsSync(S))throw Error(`gjsify ship: ${n} has no ${Ez}, so it is not a stage this command can pack. A stage is produced by \`gjsify ship --stage\`, which writes that file at the stage root beside the payload. If you pointed --from-stage at a project's \`ship/\` directory, point it at \`ship/stage/\` instead.`);let C;try{C=JSON.parse(readFileSync(S,`utf-8`))}catch(n){throw Error(`gjsify ship: ${S} is not readable JSON (${n.message}). Re-run the \`--stage\` phase; a truncated manifest means the stage transfer was truncated too.`)}if(typeof C!=`object`||!C||Array.isArray(C))throw Error(`gjsify ship: ${S} is not a JSON object. Re-run the \`--stage\` phase.`);let N=C,F=N.schema;if(typeof F!=`number`||!Number.isInteger(F))throw Error(`gjsify ship: ${S} has no integer \`schema\` field, so it was not written by \`gjsify ship --stage\`. Re-run the \`--stage\` phase.`);if(F>5)throw Error(`gjsify ship: ${S} declares schema ${F} and this gjsify understands 5. The stage was assembled by a newer gjsify: upgrade this one (\`gjsify self-update\`), or re-run the \`--stage\` phase with this version. A manifest from the future is refused rather than partially read, because an unknown field could be the one that decides a file's mode.`);if(F<5)throw Error(`gjsify ship: ${S} declares schema ${F} and this gjsify understands 5. Re-run the \`--stage\` phase with this gjsify. A stage is a short-lived intermediate between two jobs of one run, not an archive, so no migration is kept for it.`);let at=n=>`${S} → ${n}`,I=record(N.tool,at(`tool`)),H=record(N.target,at(`target`)),W={schema:F,tool:{name:expectString(I.name,at(`tool.name`)),version:expectString(I.version,at(`tool.version`))},target:{os:expectLayoutOs(expectString(H.os,at(`target.os`)),at(`target.os`)),arch:expectString(H.arch,at(`target.arch`))},formats:expectArray(N.formats,at(`formats`)).map((n,S)=>{let C=expectString(n,at(`formats[${S}]`));if(!lz.includes(C))throw Error(`gjsify ship: ${at(`formats[${S}]`)} is "${C}", which this gjsify does not know. Known formats: ${lz.join(`, `)}.`);return C}),mtime:expectInteger(N.mtime,at(`mtime`)),namespaces:expectArray(N.namespaces,at(`namespaces`)).map((n,S)=>expectString(n,at(`namespaces[${S}]`))),settings:readPackSettings(record(N.settings,at(`settings`)),at(`settings`)),staged:expectArray(N.staged,at(`staged`)).map((n,S)=>{let C=record(n,at(`staged[${S}]`));return{path:expectString(C.path,at(`staged[${S}].path`)),mode:expectInteger(C.mode,at(`staged[${S}].mode`)),bytes:expectInteger(C.bytes,at(`staged[${S}].bytes`))}}),overlay:{}};if(W.staged.length===0)throw Error(`gjsify ship: ${at(`staged`)} is empty, so this stage describes no payload. A stage always carries at least the launcher its plan named. Re-run the \`--stage\` phase; a stage that lost its plan cannot be packed into anything but an empty package.`);let q=record(N.overlay,at(`overlay`));for(let n of W.formats)W.overlay[n]=expectArray(q[n],at(`overlay.${n}`)).map((S,C)=>{let N=record(S,at(`overlay.${n}[${C}]`));return{path:expectString(N.path,at(`overlay.${n}[${C}].path`)),mode:expectInteger(N.mode,at(`overlay.${n}[${C}].mode`)),text:expectString(N.text,at(`overlay.${n}[${C}].text`))}});return W}function expectLayoutOs(n,S){try{return layoutForOs(n).os}catch{let C=sR.map(n=>oR[n].os).join(`, `);throw Error(`gjsify ship: ${S} is "${n}", which is not a layout this gjsify can pack. It carries the \`process.platform\` spelling and only that — ${C}, so \`win32\` and never \`windows\`. A stage holds exactly one OS's layout and every path in it has that OS's shape, so there is nothing to pack here. Re-run the \`--stage\` phase.`)}}function overlayFiles(n,S){return(n.overlay[S]??[]).map(n=>({path:n.path,mode:n.mode,source:{kind:`text`,text:n.text}}))}function assertExpectedTarget(n,S){if(S===void 0)return;let C=formatTarget(n.target);if(S!==C)throw Error(`gjsify ship: --expect-target ${S} but this stage was assembled for ${C}. The stage records the target its \`--arch\` resolved to at stage time, so this is a stage from another matrix leg: download the artifact belonging to ${S}, or drop --expect-target if packing this one is what you meant.`)}function assertFormatsStaged(n,S){let C=S.filter(S=>!n.formats.includes(S.id)).map(n=>n.id);if(C.length!==0)throw Error(`gjsify ship: this stage was assembled for ${n.formats.length===0?`no format at all`:n.formats.join(`, `)}, and --target names ${C.join(`, `)}. Phase one renders each format's overlay — rpm wants the licence at \`share/licenses/<pkg>/LICENSE\`, deb wants a machine-readable copyright at \`share/doc/<pkg>/copyright\` — so a format the stage never saw would pack without it, and Debian Policy § 12.5 makes that a broken package. Re-run \`gjsify ship --stage --target ${[...n.formats,...C].join(`,`)}\` on the assembling host.`)}function resolveStageMtime(n,S=process.env){let C=S.SOURCE_DATE_EPOCH;return C===void 0||Number(C)===n.mtime?{mtime:n.mtime,warnings:[]}:{mtime:n.mtime,warnings:[`SOURCE_DATE_EPOCH is ${C} here and this stage was stamped ${n.mtime}. The stage's stamp wins, because changing it would make this artifact differ from the same stage packed on the assembling host. Set the same value in both jobs, or set it in neither.`]}}function warnOnToolSkew(n){let S=cliVersion();return n.tool.version===S?[]:[`this stage was assembled by ${n.tool.name} ${n.tool.version} and is being packed by ${S}. Both phases run the same packer, so a version difference can change the artifact's bytes. Pin both jobs to one gjsify version.`]}function readPackSettings(n,S){let field=n=>`${S}.${n}`,C=record(n.extraDepends,field(`extraDepends`)),N=record(n.typelibPackages,field(`typelibPackages`));return{binaryName:expectString(n.binaryName,field(`binaryName`)),appId:expectString(n.appId,field(`appId`)),name:expectString(n.name,field(`name`)),version:expectString(n.version,field(`version`)),release:expectString(n.release,field(`release`)),maintainer:expectString(n.maintainer,field(`maintainer`)),summary:expectString(n.summary,field(`summary`)),description:expectArray(n.description,field(`description`)).map((n,S)=>expectString(n,field(`description[${S}]`))),license:expectString(n.license,field(`license`)),...n.homepage===void 0?{}:{homepage:expectString(n.homepage,field(`homepage`))},section:expectString(n.section,field(`section`)),group:expectString(n.group,field(`group`)),extraDepends:{deb:expectArray(C.deb??[],field(`extraDepends.deb`)).map((n,S)=>expectString(n,field(`extraDepends.deb[${S}]`))),rpm:expectArray(C.rpm??[],field(`extraDepends.rpm`)).map((n,S)=>expectString(n,field(`extraDepends.rpm[${S}]`)))},typelibPackages:Object.fromEntries(Object.entries(N).map(([n,S])=>{let C=record(S,field(`typelibPackages.${n}`));return[n,{deb:expectString(C.deb,field(`typelibPackages.${n}.deb`)),rpm:expectString(C.rpm,field(`typelibPackages.${n}.rpm`))}]})),app:expectApp(n.app,field(`app`)),minGjsVersion:expectString(n.minGjsVersion,field(`minGjsVersion`)),minNodeVersion:expectString(n.minNodeVersion,field(`minNodeVersion`)),flatpak:readFlatpakSettings(record(n.flatpak,field(`flatpak`)),field(`flatpak`))}}function readFlatpakSettings(n,S){let field=n=>`${S}.${n}`,strings=(n,S)=>expectArray(n,field(S)).map((n,C)=>expectString(n,field(`${S}[${C}]`)));return{runtime:expectString(n.runtime,field(`runtime`)),runtimeVersion:expectString(n.runtimeVersion,field(`runtimeVersion`)),sdk:expectString(n.sdk,field(`sdk`)),branch:expectString(n.branch,field(`branch`)),sdkExtensions:strings(n.sdkExtensions,`sdkExtensions`),appendPath:strings(n.appendPath,`appendPath`),finishArgs:strings(n.finishArgs,`finishArgs`),cleanup:strings(n.cleanup,`cleanup`)}}function record(n,S){if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: ${S} must be an object. Re-run the \`--stage\` phase.`);return n}function expectArray(n,S){if(!Array.isArray(n))throw Error(`gjsify ship: ${S} must be an array. Re-run the \`--stage\` phase.`);return n}function expectApp(n,S){if(n===`gjs`||n===`node`)return n;throw Error(`gjsify ship: ${S} must be "gjs" or "node", got ${JSON.stringify(n)}.`)}function expectString(n,S){if(typeof n!=`string`)throw Error(`gjsify ship: ${S} must be a string. Re-run the \`--stage\` phase.`);return n}function expectInteger(n,S){if(typeof n!=`number`||!Number.isInteger(n)||n<0)throw Error(`gjsify ship: ${S} must be a non-negative integer. Re-run the \`--stage\` phase. (Modes are decimal here — JSON has no octal literal, so 0o755 is written 493.)`);return n}var Ez,Dz=__esmMin(()=>{Vl(),Hs(),np(),dz(),lR(),Ez=`.gjsify-ship-stage.json`});function writeStage(n,S){for(let n of S)if(n.path===`.gjsify-ship-stage.json`)throw Error(`gjsify ship: a payload file may not be called \`${Ez}\` — that name belongs to the stage manifest, which sits at the stage root beside the payload and carries what the packing host needs (ADR 0024 § A2). Rename the \`gjsify.ship.extraFiles\` destination.`);rmSync(n,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(n,{recursive:!0});for(let C of S){let S=js(n,C.path.split(`/`).join(zs));mkdirSync(Ps(S),{recursive:!0});let N;switch(C.source.kind){case`text`:N=new TextEncoder().encode(C.source.text);break;case`file`:N=new Uint8Array(readFileSync(C.source.path));break;case`bytes`:N=C.source.data;break;default:{let n=C.source;throw Error(`gjsify ship: no writer for the "${JSON.stringify(n)}" source kind.`)}}writeFileSync(S,N),chmodSync(S,C.mode)}}function readStage(n,S){let C=new Map(S.map(n=>[n.path,n])),N=new Map;for(let S of n)for(let n of listFilesRecursive(S)){if(n===`.gjsify-ship-stage.json`)continue;let F=C.get(n);if(F===void 0)throw Error(`gjsify ship: ${js(S,n.split(`/`).join(zs))} is in the stage and not in its manifest, so nothing knows what mode to give it. Every payload file takes its mode from the plan, never from the filesystem, so a file that arrived some other way would be packed 0644 — unrunnable if it is a program. Remove it, or add it through \`gjsify.ship.extraFiles\` and re-run the \`--stage\` phase.`);let I=new Uint8Array(readFileSync(js(S,n.split(`/`).join(zs))));if(F.bytes!==void 0&&F.bytes!==I.byteLength)throw Error(`gjsify ship: ${n} is ${I.byteLength} bytes in the stage and ${F.bytes} in its manifest. The stage arrived truncated or was edited after it was assembled. Re-upload it, or re-run the \`--stage\` phase.`);N.set(n,{path:n,mode:F.mode,data:I})}let F=S.filter(n=>!N.has(n.path)).map(n=>n.path);if(F.length>0)throw Error(`gjsify ship: the stage manifest lists ${F.length} file(s) the stage does not contain: ${F.slice(0,5).join(`, `)}${F.length>5?`, …`:``}. A payload has to be complete before it is packed — both formats would pack the rest without complaint and install a package that cannot start. Re-run the \`--stage\` phase, and check that whatever moved the stage between hosts copied every file (an artifact upload that drops empty files or dotfiles is the usual cause).`);return[...N.values()].sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}function writePayload(n,S,C){let N=C===``?``:`${C}/`;rmSync(n,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(n,{recursive:!0});for(let F of S){if(!F.path.startsWith(N))throw Error(`gjsify ship: ${F.path} is outside ${C||`the artifact`}, which this artifact IS — so there is nowhere inside it for the file to go. A payload file that escaped the bundle would ship beside it, unsigned and unfound.`);let S=js(n,F.path.slice(N.length).split(`/`).join(zs));mkdirSync(Ps(S),{recursive:!0}),writeFileSync(S,F.data),chmodSync(S,F.mode)}}function directorySize(n){let S=0;for(let C of listFilesRecursive(n))S+=statSync(js(n,C.split(`/`).join(zs))).size;return S}var Oz=__esmMin(()=>{Vl(),Hs(),zR(),Dz()});function resolveSignPlan(n){let S=kz[n.layoutOs];if(S===void 0){if(n.flag!==void 0)throw Error(`gjsify ship: --sign has nothing to sign in the ${n.layoutOs} layout. A .deb and an .rpm carry no per-file signature — the artifact is signed as a whole by the repository that serves it (\`debsigs\`, \`rpmsign\`), with that repository's key and not with a build-time identity. Drop --sign, or assemble the darwin or windows layout.`);return{kind:`unsupported`}}let C=n.config?.[n.layoutOs]?.identity,[N,F]=n.flag===void 0?[C,`config`]:[n.flag,`flag`];return N===void 0||N===``?{kind:`skip`,message:`${N===``?`an empty identity was ${F===`flag`?`passed to --sign`:`set in \`${S.configKey}\``}`:`no identity was given`} — skipping ${S.tool}. An unsigned artifact is the default path and a legitimate deliverable (ADR 0024 § A13). Pass \`--sign <identity>\` or set \`${S.configKey}\` to sign; \`--sign -\` signs ad-hoc and needs no developer identity.`}:{kind:`sign`,identity:N,signer:S,source:F}}function assertHostCanSign(n){let S=process.platform;if(!n.signOn.includes(S))throw Error(`gjsify ship: signing the ${n.layoutOs} layout needs ${n.tool}, which runs on ${n.signOn.join(`, `)} and this host is ${S}. Assembly is not host-bound — \`gjsify ship <os> --stage\` here, then \`gjsify ship --from-stage <dir> --sign <identity>\` on a host that has both the tool and the identity (ADR 0024 § A1, § A14).`);if(!isOnPath(n.tool))throw Error(`gjsify ship: --sign was given and \`${n.tool}\` is not on PATH, so nothing can make the signature — ${n.installHint}. Dropping --sign produces an unsigned artifact, which is a legitimate output (ADR 0024 § A13); silently producing one while --sign was asked for is not.`)}function partitionSignedFileSet(n){let S=new Set(n.planned),C=new Set(n.arrived),N=[...C].filter(n=>!S.has(n)).sort(),F=n.sealPrefix;return{sealed:F===void 0?[]:N.filter(n=>n.startsWith(F)),unexpected:F===void 0?N:N.filter(n=>!n.startsWith(F)),removed:[...S].filter(n=>!C.has(n)).sort()}}async function signPayload(n){let{payload:S,signer:C,workDir:N}=n;writePayload(N,S,``);let F=n.identity===`-`,I;C.entitlements.length>0&&(mkdirSync(Ps(n.entitlementsPath),{recursive:!0}),writeFileSync(n.entitlementsPath,renderEntitlements(C.entitlements)),I=n.entitlementsPath);let run=async(S,H)=>{let W=C.args({identity:n.identity,file:S,adhoc:F,...I?{entitlements:I}:{}});n.verbose&&n.log(`${C.tool} ${W.join(` `)}`);let q=await spawnToCompletion(C.tool,W,{completion:`return`,cwd:N,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${C.tool}\` is not on PATH — ${C.installHint}.`)});if(q.code!==0)throw Error(`gjsify ship: ${C.tool} failed on ${H} with ${describeExit(q)}. Nothing is packed from a payload whose signature failed: an artifact that is half signed installs and is refused at first launch, which is worse than not shipping.`)},H=S.filter(n=>classifyBinary(n.data)===C.signs);if(H.length===0&&!C.sealsBundle)return n.log(`nothing in this payload is a ${C.signs===`macho`?`Mach-O`:`PE`} image, so ${C.tool} signed 0 file(s). The artifact carries no signature.`),[...S];for(let n of H)await run(js(N,n.path.split(`/`).join(zs)),n.path);let W;if(C.sealsBundle){if(n.bundleRoot===``)throw Error(`gjsify ship: the ${C.layoutOs} signer seals a bundle and this layout has no root to seal. \`Layout.root\` is what names the artifact directory; a signer that sealed the whole stage would sign the payload of every other format beside it.`);W=C.sealAddPrefix(n.bundleRoot),await run(js(N,n.bundleRoot.split(`/`).join(zs)),`${n.bundleRoot} (bundle seal)`)}let q=partitionSignedFileSet({arrived:listFilesRecursive(N),planned:S.map(n=>n.path),...W===void 0?{}:{sealPrefix:W}});if(q.unexpected.length>0||q.removed.length>0)throw Error(`gjsify ship: ${C.tool} changed the payload's file set — ${q.unexpected.length} added (${q.unexpected.slice(0,3).join(`, `)||`—`}), ${q.removed.length} removed (${q.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly the seal's own directory${W===void 0?``:` (\`${W}\`)`}.`);let Y=q.sealed;n.log(`${C.tool} signed ${H.length} of ${S.length} payload file(s) as ${F?"ad-hoc (`-`)":`\`${n.identity}\``}${W===void 0?``:` and sealed ${n.bundleRoot} (${Y.length} seal file(s))`} — ${C.gap}.`);let read=n=>new Uint8Array(readFileSync(js(N,n.split(`/`).join(zs))));return[...S.map(n=>({path:n.path,mode:n.mode,data:read(n.path)})),...Y.map(n=>({path:n,mode:420,data:read(n)}))].sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}function resolveNotaryPlan(n){let S=Az[n.layoutOs];if(S===void 0){if(n.flag!==void 0)throw Error(`gjsify ship: --notarize has no meaning in the ${n.layoutOs} layout. Notarisation is Apple's pre-clearance of a signed artifact and nothing else asks for it — Windows SmartScreen accrues reputation per file hash instead (ADR 0024 § A5).`);return{kind:`unsupported`}}if(n.flag===void 0||n.flag===``)return{kind:`skip`,message:`no notarisation credential was given — skipping ${S.tool} notarytool. Pass \`--notarize <keychain-profile>\`, naming a profile a prior \`notarytool store-credentials\` put in this host's keychain.`};if(n.sign.kind!==`sign`)throw Error("gjsify ship: --notarize was given without an identity to sign with. Notarisation is a check ON a signature, so submitting an unsigned artifact has nothing to clear. Pass `--sign <identity>` as well, or drop --notarize.");return{kind:`notarize`,credential:n.flag,notary:S}}async function notarizeArtifact(n){let{notary:S,credential:C}=n.plan,N=process.platform;if(!S.notarizeOn.includes(N))throw Error(`gjsify ship: notarising the ${S.layoutOs} layout needs ${S.tool}, which runs on ${S.notarizeOn.join(`, `)} and this host is ${N}.`);let F=S.args(C,n.artifact);n.verbose&&n.log(`${S.tool} ${F.join(` `)}`);let I=await spawnToCompletion(S.tool,F,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(I.code!==0)throw Error(`gjsify ship: ${S.tool} notarytool failed with ${describeExit(I)}.`);n.log(`${S.tool} notarytool accepted ${n.artifact}.`)}async function stapleArtifact(n){let S=[`stapler`,`staple`,n.artifact];n.verbose&&n.log(`${n.notary.tool} ${S.join(` `)}`);let C=await spawnToCompletion(n.notary.tool,S,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${n.notary.tool}\` is not on PATH — ${n.notary.installHint}.`)});if(C.code!==0)throw Error(`gjsify ship: ${n.notary.tool} stapler failed with ${describeExit(C)}. The artifact is notarised and NOT stapled, which means every launch asks Gatekeeper to check online — and fails closed on a machine with no network. Re-run the finish phase; \`stapler\` requires internet access and the ticket may not have propagated yet.`);n.log(`${n.notary.tool} stapler attached the ticket to ${n.artifact}.`)}var kz,Az,jz=__esmMin(()=>{Vl(),Hs(),dN(),_P(),zR(),wR(),iR(),Oz(),kz={darwin:{layoutOs:`darwin`,tool:`codesign`,signOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",signs:`macho`,args:({identity:n,file:S,entitlements:C,adhoc:N})=>[`--force`,`--sign`,n,`--options`,`runtime`,...C===void 0?[]:[`--entitlements`,C],...N?[]:[`--timestamp`],S],entitlements:[`com.apple.security.cs.allow-jit`,`com.apple.security.cs.allow-unsigned-executable-memory`,`com.apple.security.cs.disable-executable-page-protection`,`com.apple.security.cs.allow-dyld-environment-variables`],sealsBundle:!0,sealAddPrefix:n=>`${n}/Contents/_CodeSignature/`,configKey:`gjsify.ship.sign.darwin.identity`,gap:"the images are signed and the bundle is sealed; UNVERIFIED end to end — no macOS host in this repository has run a `--sign` over a real `.app`, and ADR 0024 § A16 still leaves library validation unmeasured"},win32:{layoutOs:`win32`,tool:`signtool`,signOn:[`win32`],installHint:"install the Windows SDK (signtool.exe ships in its `bin/<version>/x64` directory)",signs:`pe`,args:({identity:n,file:S})=>[`sign`,`/n`,n,`/fd`,`sha256`,S],entitlements:[],sealsBundle:!1,sealAddPrefix:()=>``,configKey:`gjsify.ship.sign.win32.identity`,gap:`no timestamp countersignature is requested, so the signature expires with the certificate (UNVERIFIED: no run in this repository has ever invoked signtool)`}},Az={darwin:{layoutOs:`darwin`,tool:`xcrun`,notarizeOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",args:(n,S)=>[`notarytool`,`submit`,`--keychain-profile`,n,`--wait`,S]}}});function stagedFontDir(n,S){return`${n}/${xs.basename(PL.fonts)}/${S}`}function shellQuote(n){return`'${n.replace(/'/g,`'\\''`)}'`}function cmdQuote(n){let S=/["%!\r\n]/.exec(n);if(S!==null)throw Error(`gjsify ship: \`gjsify.ship.execArgs\` contains ${JSON.stringify(n)}, and cmd.exe has no way to pass ${JSON.stringify(S[0])} through a Windows launcher literally — \`%\` expands at parse time and \`"\` ends the quoted run. Move the value into the app (it can read it from its own config) or drop the character.`);return`"${n}"`}function renderLauncher(n,S,C,N={}){switch(C.name){case`linux`:return renderPrefixLauncher(n,S,C);case`darwin`:return renderAppBundleLauncher(n,S,C,N);case`windows`:return renderWindowsLauncher(n,S,C,N);default:{let n=C.name;throw Error(`gjsify ship: no launcher is wired for the "${String(n)}" layout.`)}}}function renderPrefixLauncher(n,S,C){let N=C.dirs(n),F=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`self=$(readlink -f "$0")`,`prefix=$(dirname "$(dirname "$self")")`,`XDG_DATA_DIRS="$prefix/${N.data}:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"`,`export XDG_DATA_DIRS`];if(n.typelibFiles.length>0){let n=`"$prefix"/${N.native}`;for(let S of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])F.push(`${S}=${n}\${${S}:+:$${S}}`,`export ${S}`)}return n.localeFiles.length>0&&F.push(`GJSIFY_LOCALE_DIR="$prefix"/${N.data}/locale`,`export GJSIFY_LOCALE_DIR`),n.fontFiles.length>0&&F.push(`GJSIFY_FONT_DIR="$prefix"/${stagedFontDir(N.data,n.appId)}`,`export GJSIFY_FONT_DIR`),F.push(`exec ${execLine(C,`"$prefix"/${N.bundle}/${S}`,n)} "$@"`,``),F.join(`
|
|
1106
|
+
`)}function msiBackendFor(n){if(n===`linux`)return`wixl`;if(n===`win32`)return`wix3`;throw Error(`gjsify ship: no MSI compiler is wired for ${n}. \`wixl\` (msitools) is used on linux and WiX v3 on win32; assembly is not host-bound, so \`gjsify ship windows --stage\` here and \`gjsify ship --from-stage <dir> --target msi\` there is the way across.`)}async function buildMsi(n){let S=msiBackendFor(n.host??process.platform);mkdirSync(n.workDir,{recursive:!0});let C=js(n.workDir,`${n.settings.binaryName}.wxs`);if(writeFileSync(C,renderWxs(n)),S===`wixl`)return await run(`wixl`,[`-a`,n.archLabel,`-o`,n.target,C],n),C;let N=js(n.workDir,`obj`);return rmSync(N,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(N,{recursive:!0}),await run(`candle.exe`,[`-nologo`,`-arch`,n.archLabel,`-out`,`${N}\\`,C],n),await run(`light.exe`,[`-nologo`,`-out`,n.target,js(N,`${n.settings.binaryName}.wixobj`)],n),C}async function run(n,S,C){C.verbose&&ve.log(`[gjsify ship] ${n} ${S.join(` `)}`);let N=await spawnToCompletion(n,[...S],{completion:`return`,cwd:C.workDir,stdio:`inherit`,notFound:()=>Error(`gjsify ship: ${n} not found. It is the MSI compiler for this host — Fedora: \`sudo dnf install msitools\`, Debian/Ubuntu: \`sudo apt install msitools\`, Windows: WiX Toolset v3.14 with its \`bin\` directory on PATH.`)});if(N.code!==0)throw Error(`gjsify ship: ${n} failed with ${describeExit(N)}.`)}var vz,yz,bz,xz=__esmMin(()=>{ye(),No(),Vl(),Hs(),_P(),uR(),DR(),vz=`7b3a1f6e-0c4d-4a2b-9e51-3d8c6f2a0b14`,yz=/[<>:"/\\|?*;]/,bz=`root`});function getCrcTable(){if(Oz!==null)return Oz;let n=new Uint32Array(256);for(let S=0;S<256;S++){let C=S;for(let n=0;n<8;n++)C=C&1?3988292384^C>>>1:C>>>1;n[S]=C>>>0}return Oz=n,n}function crc32(n){let S=getCrcTable(),C=4294967295;for(let N=0;N<n.length;N++)C=S[(C^n[N])&255]^C>>>8;return(C^4294967295)>>>0}function dosDateTime(n){let S=new Date(Math.max(n,315532800)*1e3);return{date:(S.getUTCFullYear()-1980&127)<<9|S.getUTCMonth()+1<<5|S.getUTCDate(),time:S.getUTCHours()<<11|S.getUTCMinutes()<<5|Math.floor(S.getUTCSeconds()/2)}}function buildZip(n,S){let C=[...n].sort((n,S)=>n.path<S.path?-1:+(n.path>S.path)),{date:N,time:F}=dosDateTime(S),I=new TextEncoder;if(C.length>65535)throw Error(`gjsify ship: this archive would hold ${C.length} entries and a non-ZIP64 central directory records the count in 16 bits, so it would silently wrap. Nothing here writes ZIP64 yet; the payload has to shrink, or this writer has to grow the ZIP64 records.`);let H=new Writer,W=new Writer,q=0;for(let n of C){let S=I.encode(n.path),C=crc32(n.data),Y=n.data.byteLength,X=H.offset;if(X>4294967295||Y>4294967295)throw Error(`gjsify ship: ${n.path} would push this archive past 4 GiB, which a non-ZIP64 header records in 32 bits and therefore truncates. Nothing here writes ZIP64 yet.`);H.u32(Sz),H.u16(Dz),H.u16(2048),H.u16(Tz),H.u16(F),H.u16(N),H.u32(C),H.u32(Y),H.u32(Y),H.u16(S.byteLength),H.u16(0),H.bytes(S),H.bytes(n.data),W.u32(Cz),W.u16(Ez),W.u16(Dz),W.u16(2048),W.u16(Tz),W.u16(F),W.u16(N),W.u32(C),W.u32(Y),W.u32(Y),W.u16(S.byteLength),W.u16(0),W.u16(0),W.u16(0),W.u16(0),W.u32(((32768|n.mode&4095)>>>0)*65536),W.u32(X),W.bytes(S),q+=1}let Y=W.finish(),X=new Writer;X.bytes(H.finish());let Z=X.offset;return X.bytes(Y),X.u32(wz),X.u16(0),X.u16(0),X.u16(q),X.u16(q),X.u32(Y.byteLength),X.u32(Z),X.u16(0),X.finish()}function zipEntriesFromPayload(n,S=``){let C=S===``?``:`${S}/`;return n.map(n=>({path:`${C}${n.path}`,mode:n.mode,data:n.data}))}var Sz,Cz,wz,Tz,Ez,Dz,Oz,Writer,kz=__esmMin(()=>{Sz=67324752,Cz=33639248,wz=101010256,Tz=0,Ez=788,Dz=20,Oz=null,Writer=class{parts=[];length=0;get offset(){return this.length}u16(n){this.push(new Uint8Array([n&255,n>>>8&255]))}u32(n){this.push(new Uint8Array([n&255,n>>>8&255,n>>>16&255,n>>>24&255]))}bytes(n){this.push(n)}push(n){this.parts.push(n),this.length+=n.byteLength}finish(){let n=new Uint8Array(this.length),S=0;for(let C of this.parts)n.set(C,S),S+=C.byteLength;return n}}});function splitWorkspaceSpecifier(n,S){if(n.startsWith(`.`)||n.startsWith(`/`)||n.includes(`:`))return null;let C=n.split(`/`),N=n.startsWith(`@`)?[2]:[1];for(let n of N){let N=C.slice(0,n).join(`/`);if(!S.has(N))continue;let F=C.slice(n).join(`/`);return{name:N,subpath:F?`./${F}`:`.`}}return null}function staticStringValue(n){if(n?.type===`Literal`)return typeof n.value==`string`?n.value:null;if(n?.type===`TemplateLiteral`&&n.expressions?.length===0){let S=n.quasis?.[0]?.value?.cooked;return typeof S==`string`?S:null}return null}function walkModuleAst(n,S){let C;try{C=parse$1(n,{ecmaVersion:`latest`,sourceType:`module`,allowHashBang:!0})}catch{return}let descend=n=>{if(!n||typeof n!=`object`)return;if(Array.isArray(n)){for(let S of n)descend(S);return}let C=n;S(C);for(let[n,S]of Object.entries(C))n===`type`||n===`start`||n===`end`||n===`loc`||descend(S)};descend(C)}function importedSpecifier(n){return n.type!==`ImportDeclaration`&&n.type!==`ExportNamedDeclaration`&&n.type!==`ExportAllDeclaration`&&n.type!==`ImportExpression`?null:staticStringValue(n.source)}function moduleSpecifiers$1(n){let S=[];return walkModuleAst(n,n=>{let C=importedSpecifier(n);C!==null&&S.push(C)}),S}function resolveRelative(n,S){let C=Os(Ps(n),S);for(let n of[C,`${C}.js`,`${C}.mjs`,js(C,`index.js`)])try{if(statSync(n).isFile())return n}catch{}return null}function workspaceEntry(n,S){let C=n.manifest,pick=n=>{if(typeof n==`string`)return n;if(!n||typeof n!=`object`||Array.isArray(n))return null;let S=n;for(let n of[`node`,`import`,`default`,`gjs`])if(n in S){let C=pick(S[n]);if(C)return C}return null},N=null;if(typeof C.exports==`string`?N=S===`.`?C.exports:null:C.exports&&typeof C.exports==`object`&&(N=pick(C.exports[S])),!N&&S===`.`&&(N=typeof C.module==`string`?C.module:null,N??=typeof C.main==`string`?C.main:null),!N)return null;let F=Os(n.location,N);return existsSync(F)?F:null}function workspacePeers(n,S){return Object.keys(n.peerDependencies??{}).filter(n=>S.has(n))}function cliRuntimeClosure(n,S={}){let C=new Map(n.map(n=>[n.name,n])),N=new Set,F=S.entry,I=S.cliManifest;if(F===void 0||I===void 0){let n=cliPackageDir(),S=null;if(n)try{S=JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{}if(I??=S,F===void 0){let C=S?.bin,N=typeof C==`string`?C:C?.gjsify??S?.main;F=n&&N?Os(n,N):null}}for(let n of workspacePeers(I??{},C))N.add(n);if(!F||!existsSync(F))return N;let H=new Set,W=[F];for(;W.length>0;){let n=W.shift();if(H.has(n))continue;H.add(n);let S;try{S=readFileSync(n,`utf8`)}catch{continue}for(let F of moduleSpecifiers$1(S)){if(F.startsWith(`.`)){let S=resolveRelative(n,F);S&&W.push(S);continue}let S=splitWorkspaceSpecifier(F,C),I=S?C.get(S.name):void 0;if(!S||!I)continue;N.add(S.name);for(let n of workspacePeers(I.manifest,C))N.add(n);let H=workspaceEntry(I,S.subpath);H&&W.push(H)}}return N}var Az=__esmMin(()=>{Sy(),Vl(),Hs(),np(),__name$1(moduleSpecifiers$1,`moduleSpecifiers`)});function entryEvidence(n){let S=new Set,C=new Set;return walkModuleAst(n,n=>{let N=importedSpecifier(n);N!==null&&(N.startsWith(`gi://`)||jz.has(N)?S.add(N):N.startsWith(`node:`)&&C.add(N))}),{gi:[...S].sort(),node:[...C].sort()}}function assertEntryRunsUnder(n){let S=entryEvidence(n.source),C=n.interpreter===`node`?S.gi:S.node;if(C.length===0)return;let N=n.interpreter===`node`?`gjs`:`node`,F=n.interpreter===`gjs`?`GJS's loader refuses it: ImportError, "Unsupported URI scheme for importing: node"`:C.some(n=>n.startsWith(`gi://`))?`node's ESM loader refuses it: ERR_UNSUPPORTED_ESM_URL_SCHEME, "Only URLs with a scheme in: file, data, and node are supported by the default ESM loader"`:`node's ESM loader refuses it: ERR_MODULE_NOT_FOUND — a GJS built-in is not a package`,I=C.slice(0,3).join(`, `),H=C.length>3?`, and ${C.length-3} more`:``;throw Error(`gjsify ship: this target execs \`${n.interpreter}\` (\`${n.appKey}\`), and the entry it would ship — ${n.entry} (\`${n.bundleKey}\`) — imports ${I}${H}.\n ${F}, before a line of application code runs.\n The artifact would be built, reported as built, and fail at launch on every machine.
|
|
1107
|
+
Either ship this target the \`--app ${n.interpreter}\` build of the app — \`gjsify.ship.bundle.${n.layoutOs}\` selects the entry per target, the way \`gjsify.ship.app.${n.layoutOs}\` selects the runtime —\n or set \`gjsify.ship.app.${n.layoutOs}\` to "${N}" if this bundle is the one that should ship.`)}var jz,Mz=__esmMin(()=>{Az(),jz=new Set([`system`,`gettext`])});function scanGiNamespaces(n){let S=new Set,C=new Set,N=new Set,F=[];walkModuleAst(n,n=>{let I=importedSpecifier(n);if(I!==null){let F=parseGiSpecifier(I);F!==null&&S.add(F),n.type===`ImportDeclaration`&&I===Nz&&collectNodeGiBindings(n,C,N);return}if(n.type===`VariableDeclarator`&&loadsNodeGiModule(n.init)){let S=n.id;S?.type===`Identifier`&&typeof S.name==`string`&&N.add(S.name);return}n.type===`CallExpression`&&F.push(n)});for(let n of F){let F=requireGiNamespace(n,C,N);F!==null&&S.add(F)}return[...S].sort()}function parseGiSpecifier(n){if(!n.startsWith(`gi://`))return null;let[S,C]=n.slice(5).split(`?`,2);if(S===void 0||!Pz.test(S))return null;if(C===void 0)return S;let N=/(?:^|&)version=([^&]+)/.exec(C)?.[1];return N===void 0?S:`${S}-${N}`}function collectNodeGiBindings(n,S,C){let N=n.specifiers??[];for(let n of N){let N=n.local;if(N?.type!==`Identifier`||typeof N.name!=`string`)continue;let F=n.imported;n.type===`ImportNamespaceSpecifier`?C.add(N.name):(n.type===`ImportDefaultSpecifier`||F?.type===`Identifier`&&F.name===`requireGi`)&&S.add(N.name)}}function loadsNodeGiModule(n){if(!n||typeof n!=`object`)return!1;let S=n;return S.type===`CallExpression`?staticStringValue((S.arguments??[])[0])===Nz:!1}function requireGiNamespace(n,S,C){let N=n.callee,F=!1;if(N?.type===`Identifier`)F=typeof N.name==`string`&&S.has(N.name);else if(N?.type===`MemberExpression`&&N.computed!==!0){let n=N.property;if(n?.type!==`Identifier`||n.name!==`requireGi`)return null;let S=N.object;F=loadsNodeGiModule(S)||S?.type===`Identifier`&&typeof S.name==`string`&&C.has(S.name)}if(!F)return null;let I=n.arguments??[],H=staticStringValue(I[0]);if(H===null||!Pz.test(H))return null;let W=staticStringValue(I[1]);return W===null?H:`${H}-${W}`}var Nz,Pz,Fz=__esmMin(()=>{Az(),Nz=`@gjsify/node-gi/gi`,Pz=/^[A-Za-z][A-Za-z\d_]*$/});function base64Encode(n){let S=``,C=32768;for(let N=0;N<n.length;N+=C)S+=String.fromCharCode(...n.subarray(N,N+C));return btoa(S)}function base64Decode(n){let S=atob(n),C=new Uint8Array(S.length);for(let n=0;n<S.length;n++)C[n]=S.charCodeAt(n);return C}var Iz=__esmMin(()=>{});function toPackSettings(n){return{binaryName:n.binaryName,appId:n.appId,name:n.name,version:n.version,release:n.release,maintainer:n.maintainer,summary:n.summary,description:n.description,license:n.license,...n.homepage===void 0?{}:{homepage:n.homepage},section:n.section,group:n.group,extraDepends:n.extraDepends,typelibPackages:n.typelibPackages,app:n.app,minGjsVersion:n.minGjsVersion,minNodeVersion:n.minNodeVersion,flatpak:n.flatpak}}function stageManifestPath(n){return js(n,Lz)}function formatTarget(n){return`${n.os}-${n.arch}`}function writeStageManifest(n){let S={};for(let C of n.formats)S[C.id]=(n.overlay.get(C.id)??[]).map(n=>{if(n.source.kind===`text`)return{path:n.path,mode:n.mode,text:n.source.text};if(n.source.kind===`bytes`)return{path:n.path,mode:n.mode,base64:base64Encode(n.source.data)};throw Error(`gjsify ship: internal error — the ${C.id} overlay entry ${n.path} is a file reference, and a stage manifest may only carry rendered bytes. Render it in \`planOverlay\` instead.`)});let C={schema:6,tool:{name:`@gjsify/cli`,version:cliVersion()},target:{os:n.settings.layoutOs,arch:n.settings.arch},formats:n.formats.map(n=>n.id),mtime:n.mtime,namespaces:[...n.namespaces],settings:toPackSettings(n.settings),staged:n.staged.map(S=>({path:S.path,mode:S.mode,bytes:statSync(js(n.stageDir,S.path.split(`/`).join(zs))).size})),overlay:S};return writeFileSync(stageManifestPath(n.stageDir),`${JSON.stringify(C,null,2)}\n`),C}function readStageManifest(n){let S=stageManifestPath(n);if(!existsSync(S))throw Error(`gjsify ship: ${n} has no ${Lz}, so it is not a stage this command can pack. A stage is produced by \`gjsify ship --stage\`, which writes that file at the stage root beside the payload. If you pointed --from-stage at a project's \`ship/\` directory, point it at \`ship/stage/\` instead.`);let C;try{C=JSON.parse(readFileSync(S,`utf-8`))}catch(n){throw Error(`gjsify ship: ${S} is not readable JSON (${n.message}). Re-run the \`--stage\` phase; a truncated manifest means the stage transfer was truncated too.`)}if(typeof C!=`object`||!C||Array.isArray(C))throw Error(`gjsify ship: ${S} is not a JSON object. Re-run the \`--stage\` phase.`);let N=C,F=N.schema;if(typeof F!=`number`||!Number.isInteger(F))throw Error(`gjsify ship: ${S} has no integer \`schema\` field, so it was not written by \`gjsify ship --stage\`. Re-run the \`--stage\` phase.`);if(F>6)throw Error(`gjsify ship: ${S} declares schema ${F} and this gjsify understands 6. The stage was assembled by a newer gjsify: upgrade this one (\`gjsify self-update\`), or re-run the \`--stage\` phase with this version. A manifest from the future is refused rather than partially read, because an unknown field could be the one that decides a file's mode.`);if(F<6)throw Error(`gjsify ship: ${S} declares schema ${F} and this gjsify understands 6. Re-run the \`--stage\` phase with this gjsify. A stage is a short-lived intermediate between two jobs of one run, not an archive, so no migration is kept for it.`);let at=n=>`${S} → ${n}`,I=record(N.tool,at(`tool`)),H=record(N.target,at(`target`)),W={schema:F,tool:{name:expectString(I.name,at(`tool.name`)),version:expectString(I.version,at(`tool.version`))},target:{os:expectLayoutOs(expectString(H.os,at(`target.os`)),at(`target.os`)),arch:expectString(H.arch,at(`target.arch`))},formats:expectArray(N.formats,at(`formats`)).map((n,S)=>{let C=expectString(n,at(`formats[${S}]`));if(!hz.includes(C))throw Error(`gjsify ship: ${at(`formats[${S}]`)} is "${C}", which this gjsify does not know. Known formats: ${hz.join(`, `)}.`);return C}),mtime:expectInteger(N.mtime,at(`mtime`)),namespaces:expectArray(N.namespaces,at(`namespaces`)).map((n,S)=>expectString(n,at(`namespaces[${S}]`))),settings:readPackSettings(record(N.settings,at(`settings`)),at(`settings`)),staged:expectArray(N.staged,at(`staged`)).map((n,S)=>{let C=record(n,at(`staged[${S}]`));return{path:expectString(C.path,at(`staged[${S}].path`)),mode:expectInteger(C.mode,at(`staged[${S}].mode`)),bytes:expectInteger(C.bytes,at(`staged[${S}].bytes`))}}),overlay:{}};if(W.staged.length===0)throw Error(`gjsify ship: ${at(`staged`)} is empty, so this stage describes no payload. A stage always carries at least the launcher its plan named. Re-run the \`--stage\` phase; a stage that lost its plan cannot be packed into anything but an empty package.`);let q=record(N.overlay,at(`overlay`));for(let n of W.formats)W.overlay[n]=expectArray(q[n],at(`overlay.${n}`)).map((S,C)=>{let N=record(S,at(`overlay.${n}[${C}]`)),F=at(`overlay.${n}[${C}]`);if(N.text===void 0==(N.base64===void 0))throw Error(`gjsify ship: ${F} must carry exactly one of \`text\` and \`base64\`. An overlay entry is either rendered text or rendered bytes; an entry with neither would pack an empty file at a path the format requires content at.`);return{path:expectString(N.path,at(`overlay.${n}[${C}].path`)),mode:expectInteger(N.mode,at(`overlay.${n}[${C}].mode`)),...N.text===void 0?{base64:expectString(N.base64,at(`overlay.${n}[${C}].base64`))}:{text:expectString(N.text,at(`overlay.${n}[${C}].text`))}}});return W}function expectLayoutOs(n,S){try{return layoutForOs(n).os}catch{let C=cR.map(n=>sR[n].os).join(`, `);throw Error(`gjsify ship: ${S} is "${n}", which is not a layout this gjsify can pack. It carries the \`process.platform\` spelling and only that — ${C}, so \`win32\` and never \`windows\`. A stage holds exactly one OS's layout and every path in it has that OS's shape, so there is nothing to pack here. Re-run the \`--stage\` phase.`)}}function overlayFiles(n,S){return(n.overlay[S]??[]).map(n=>({path:n.path,mode:n.mode,source:n.base64===void 0?{kind:`text`,text:n.text??``}:{kind:`bytes`,data:base64Decode(n.base64)}}))}function assertExpectedTarget(n,S){if(S===void 0)return;let C=formatTarget(n.target);if(S!==C)throw Error(`gjsify ship: --expect-target ${S} but this stage was assembled for ${C}. The stage records the target its \`--arch\` resolved to at stage time, so this is a stage from another matrix leg: download the artifact belonging to ${S}, or drop --expect-target if packing this one is what you meant.`)}function assertFormatsStaged(n,S){let C=S.filter(S=>!n.formats.includes(S.id)).map(n=>n.id);if(C.length!==0)throw Error(`gjsify ship: this stage was assembled for ${n.formats.length===0?`no format at all`:n.formats.join(`, `)}, and --target names ${C.join(`, `)}. Phase one renders each format's overlay — rpm wants the licence at \`share/licenses/<pkg>/LICENSE\`, deb wants a machine-readable copyright at \`share/doc/<pkg>/copyright\` — so a format the stage never saw would pack without it, and Debian Policy § 12.5 makes that a broken package. Re-run \`gjsify ship --stage --target ${[...n.formats,...C].join(`,`)}\` on the assembling host.`)}function resolveStageMtime(n,S=process.env){let C=S.SOURCE_DATE_EPOCH;return C===void 0||Number(C)===n.mtime?{mtime:n.mtime,warnings:[]}:{mtime:n.mtime,warnings:[`SOURCE_DATE_EPOCH is ${C} here and this stage was stamped ${n.mtime}. The stage's stamp wins, because changing it would make this artifact differ from the same stage packed on the assembling host. Set the same value in both jobs, or set it in neither.`]}}function warnOnToolSkew(n){let S=cliVersion();return n.tool.version===S?[]:[`this stage was assembled by ${n.tool.name} ${n.tool.version} and is being packed by ${S}. Both phases run the same packer, so a version difference can change the artifact's bytes. Pin both jobs to one gjsify version.`]}function readPackSettings(n,S){let field=n=>`${S}.${n}`,C=record(n.extraDepends,field(`extraDepends`)),N=record(n.typelibPackages,field(`typelibPackages`));return{binaryName:expectString(n.binaryName,field(`binaryName`)),appId:expectString(n.appId,field(`appId`)),name:expectString(n.name,field(`name`)),version:expectString(n.version,field(`version`)),release:expectString(n.release,field(`release`)),maintainer:expectString(n.maintainer,field(`maintainer`)),summary:expectString(n.summary,field(`summary`)),description:expectArray(n.description,field(`description`)).map((n,S)=>expectString(n,field(`description[${S}]`))),license:expectString(n.license,field(`license`)),...n.homepage===void 0?{}:{homepage:expectString(n.homepage,field(`homepage`))},section:expectString(n.section,field(`section`)),group:expectString(n.group,field(`group`)),extraDepends:{deb:expectArray(C.deb??[],field(`extraDepends.deb`)).map((n,S)=>expectString(n,field(`extraDepends.deb[${S}]`))),rpm:expectArray(C.rpm??[],field(`extraDepends.rpm`)).map((n,S)=>expectString(n,field(`extraDepends.rpm[${S}]`)))},typelibPackages:Object.fromEntries(Object.entries(N).map(([n,S])=>{let C=record(S,field(`typelibPackages.${n}`));return[n,{deb:expectString(C.deb,field(`typelibPackages.${n}.deb`)),rpm:expectString(C.rpm,field(`typelibPackages.${n}.rpm`))}]})),app:expectApp(n.app,field(`app`)),minGjsVersion:expectString(n.minGjsVersion,field(`minGjsVersion`)),minNodeVersion:expectString(n.minNodeVersion,field(`minNodeVersion`)),flatpak:readFlatpakSettings(record(n.flatpak,field(`flatpak`)),field(`flatpak`))}}function readFlatpakSettings(n,S){let field=n=>`${S}.${n}`,strings=(n,S)=>expectArray(n,field(S)).map((n,C)=>expectString(n,field(`${S}[${C}]`)));return{runtime:expectString(n.runtime,field(`runtime`)),runtimeVersion:expectString(n.runtimeVersion,field(`runtimeVersion`)),sdk:expectString(n.sdk,field(`sdk`)),branch:expectString(n.branch,field(`branch`)),sdkExtensions:strings(n.sdkExtensions,`sdkExtensions`),appendPath:strings(n.appendPath,`appendPath`),finishArgs:strings(n.finishArgs,`finishArgs`),cleanup:strings(n.cleanup,`cleanup`)}}function record(n,S){if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`gjsify ship: ${S} must be an object. Re-run the \`--stage\` phase.`);return n}function expectArray(n,S){if(!Array.isArray(n))throw Error(`gjsify ship: ${S} must be an array. Re-run the \`--stage\` phase.`);return n}function expectApp(n,S){if(n===`gjs`||n===`node`)return n;throw Error(`gjsify ship: ${S} must be "gjs" or "node", got ${JSON.stringify(n)}.`)}function expectString(n,S){if(typeof n!=`string`)throw Error(`gjsify ship: ${S} must be a string. Re-run the \`--stage\` phase.`);return n}function expectInteger(n,S){if(typeof n!=`number`||!Number.isInteger(n)||n<0)throw Error(`gjsify ship: ${S} must be a non-negative integer. Re-run the \`--stage\` phase. (Modes are decimal here — JSON has no octal literal, so 0o755 is written 493.)`);return n}var Lz,Rz=__esmMin(()=>{Vl(),Hs(),Iz(),np(),_z(),uR(),Lz=`.gjsify-ship-stage.json`});function writeStage(n,S){for(let n of S)if(n.path===`.gjsify-ship-stage.json`)throw Error(`gjsify ship: a payload file may not be called \`${Lz}\` — that name belongs to the stage manifest, which sits at the stage root beside the payload and carries what the packing host needs (ADR 0024 § A2). Rename the \`gjsify.ship.extraFiles\` destination.`);rmSync(n,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(n,{recursive:!0});for(let C of S){let S=js(n,C.path.split(`/`).join(zs));mkdirSync(Ps(S),{recursive:!0});let N;switch(C.source.kind){case`text`:N=new TextEncoder().encode(C.source.text);break;case`file`:N=new Uint8Array(readFileSync(C.source.path));break;case`bytes`:N=C.source.data;break;default:{let n=C.source;throw Error(`gjsify ship: no writer for the "${JSON.stringify(n)}" source kind.`)}}writeFileSync(S,N),chmodSync(S,C.mode)}}function readStage(n,S){let C=new Map(S.map(n=>[n.path,n])),N=new Map;for(let S of n)for(let n of listFilesRecursive(S)){if(n===`.gjsify-ship-stage.json`)continue;let F=C.get(n);if(F===void 0)throw Error(`gjsify ship: ${js(S,n.split(`/`).join(zs))} is in the stage and not in its manifest, so nothing knows what mode to give it. Every payload file takes its mode from the plan, never from the filesystem, so a file that arrived some other way would be packed 0644 — unrunnable if it is a program. Remove it, or add it through \`gjsify.ship.extraFiles\` and re-run the \`--stage\` phase.`);let I=new Uint8Array(readFileSync(js(S,n.split(`/`).join(zs))));if(F.bytes!==void 0&&F.bytes!==I.byteLength)throw Error(`gjsify ship: ${n} is ${I.byteLength} bytes in the stage and ${F.bytes} in its manifest. The stage arrived truncated or was edited after it was assembled. Re-upload it, or re-run the \`--stage\` phase.`);N.set(n,{path:n,mode:F.mode,data:I})}let F=S.filter(n=>!N.has(n.path)).map(n=>n.path);if(F.length>0)throw Error(`gjsify ship: the stage manifest lists ${F.length} file(s) the stage does not contain: ${F.slice(0,5).join(`, `)}${F.length>5?`, …`:``}. A payload has to be complete before it is packed — both formats would pack the rest without complaint and install a package that cannot start. Re-run the \`--stage\` phase, and check that whatever moved the stage between hosts copied every file (an artifact upload that drops empty files or dotfiles is the usual cause).`);return[...N.values()].sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}function writePayload(n,S,C){let N=C===``?``:`${C}/`;rmSync(n,{recursive:!0,force:!0,maxRetries:5}),mkdirSync(n,{recursive:!0});for(let F of S){if(!F.path.startsWith(N))throw Error(`gjsify ship: ${F.path} is outside ${C||`the artifact`}, which this artifact IS — so there is nowhere inside it for the file to go. A payload file that escaped the bundle would ship beside it, unsigned and unfound.`);let S=js(n,F.path.slice(N.length).split(`/`).join(zs));mkdirSync(Ps(S),{recursive:!0}),writeFileSync(S,F.data),chmodSync(S,F.mode)}}function directorySize(n){let S=0;for(let C of listFilesRecursive(n))S+=statSync(js(n,C.split(`/`).join(zs))).size;return S}var zz=__esmMin(()=>{Vl(),Hs(),VR(),Rz()});function resolveSignPlan(n){let S=Bz[n.layoutOs];if(S===void 0){if(n.flag!==void 0)throw Error(`gjsify ship: --sign has nothing to sign in the ${n.layoutOs} layout. A .deb and an .rpm carry no per-file signature — the artifact is signed as a whole by the repository that serves it (\`debsigs\`, \`rpmsign\`), with that repository's key and not with a build-time identity. Drop --sign, or assemble the darwin or windows layout.`);return{kind:`unsupported`}}let C=n.config?.[n.layoutOs]?.identity,[N,F]=n.flag===void 0?[C,`config`]:[n.flag,`flag`];return N===void 0||N===``?{kind:`skip`,message:`${N===``?`an empty identity was ${F===`flag`?`passed to --sign`:`set in \`${S.configKey}\``}`:`no identity was given`} — skipping ${S.tool}. An unsigned artifact is the default path and a legitimate deliverable (ADR 0024 § A13). Pass \`--sign <identity>\` or set \`${S.configKey}\` to sign; \`--sign -\` signs ad-hoc and needs no developer identity.`}:{kind:`sign`,identity:N,signer:S,source:F}}function assertHostCanSign(n){let S=process.platform;if(!n.signOn.includes(S))throw Error(`gjsify ship: signing the ${n.layoutOs} layout needs ${n.tool}, which runs on ${n.signOn.join(`, `)} and this host is ${S}. Assembly is not host-bound — \`gjsify ship <os> --stage\` here, then \`gjsify ship --from-stage <dir> --sign <identity>\` on a host that has both the tool and the identity (ADR 0024 § A1, § A14).`);if(!isOnPath(n.tool))throw Error(`gjsify ship: --sign was given and \`${n.tool}\` is not on PATH, so nothing can make the signature — ${n.installHint}. Dropping --sign produces an unsigned artifact, which is a legitimate output (ADR 0024 § A13); silently producing one while --sign was asked for is not.`)}function partitionSignedFileSet(n){let S=new Set(n.planned),C=new Set(n.arrived),N=[...C].filter(n=>!S.has(n)).sort(),F=n.sealPrefix;return{sealed:F===void 0?[]:N.filter(n=>n.startsWith(F)),unexpected:F===void 0?N:N.filter(n=>!n.startsWith(F)),removed:[...S].filter(n=>!C.has(n)).sort()}}async function signPayload(n){let{payload:S,signer:C,workDir:N}=n;writePayload(N,S,``);let F=n.identity===`-`,I;C.entitlements.length>0&&(mkdirSync(Ps(n.entitlementsPath),{recursive:!0}),writeFileSync(n.entitlementsPath,renderEntitlements(C.entitlements)),I=n.entitlementsPath);let run=async(S,H)=>{let W=C.args({identity:n.identity,file:S,adhoc:F,...I?{entitlements:I}:{}});n.verbose&&n.log(`${C.tool} ${W.join(` `)}`);let q=await spawnToCompletion(C.tool,W,{completion:`return`,cwd:N,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${C.tool}\` is not on PATH — ${C.installHint}.`)});if(q.code!==0)throw Error(`gjsify ship: ${C.tool} failed on ${H} with ${describeExit(q)}. Nothing is packed from a payload whose signature failed: an artifact that is half signed installs and is refused at first launch, which is worse than not shipping.`)},H=S.filter(n=>classifyBinary(n.data)===C.signs);if(H.length===0&&!C.sealsBundle)return n.log(`nothing in this payload is a ${C.signs===`macho`?`Mach-O`:`PE`} image, so ${C.tool} signed 0 file(s). The artifact carries no signature.`),[...S];for(let n of H)await run(js(N,n.path.split(`/`).join(zs)),n.path);let W;if(C.sealsBundle){if(n.bundleRoot===``)throw Error(`gjsify ship: the ${C.layoutOs} signer seals a bundle and this layout has no root to seal. \`Layout.root\` is what names the artifact directory; a signer that sealed the whole stage would sign the payload of every other format beside it.`);W=C.sealAddPrefix(n.bundleRoot),await run(js(N,n.bundleRoot.split(`/`).join(zs)),`${n.bundleRoot} (bundle seal)`)}let q=partitionSignedFileSet({arrived:listFilesRecursive(N),planned:S.map(n=>n.path),...W===void 0?{}:{sealPrefix:W}});if(q.unexpected.length>0||q.removed.length>0)throw Error(`gjsify ship: ${C.tool} changed the payload's file set — ${q.unexpected.length} added (${q.unexpected.slice(0,3).join(`, `)||`—`}), ${q.removed.length} removed (${q.removed.slice(0,3).join(`, `)||`—`}). Signing is a mutation of the files that are already in the payload (ADR 0024 § A4), plus exactly the seal's own directory${W===void 0?``:` (\`${W}\`)`}.`);let Y=q.sealed;n.log(`${C.tool} signed ${H.length} of ${S.length} payload file(s) as ${F?"ad-hoc (`-`)":`\`${n.identity}\``}${W===void 0?``:` and sealed ${n.bundleRoot} (${Y.length} seal file(s))`} — ${C.gap}.`);let read=n=>new Uint8Array(readFileSync(js(N,n.split(`/`).join(zs))));return[...S.map(n=>({path:n.path,mode:n.mode,data:read(n.path)})),...Y.map(n=>({path:n,mode:420,data:read(n)}))].sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}function resolveNotaryPlan(n){let S=Vz[n.layoutOs];if(S===void 0){if(n.flag!==void 0)throw Error(`gjsify ship: --notarize has no meaning in the ${n.layoutOs} layout. Notarisation is Apple's pre-clearance of a signed artifact and nothing else asks for it — Windows SmartScreen accrues reputation per file hash instead (ADR 0024 § A5).`);return{kind:`unsupported`}}if(n.flag===void 0||n.flag===``)return{kind:`skip`,message:`no notarisation credential was given — skipping ${S.tool} notarytool. Pass \`--notarize <keychain-profile>\`, naming a profile a prior \`notarytool store-credentials\` put in this host's keychain.`};if(n.sign.kind!==`sign`)throw Error("gjsify ship: --notarize was given without an identity to sign with. Notarisation is a check ON a signature, so submitting an unsigned artifact has nothing to clear. Pass `--sign <identity>` as well, or drop --notarize.");return{kind:`notarize`,credential:n.flag,notary:S}}async function notarizeArtifact(n){let{notary:S,credential:C}=n.plan,N=process.platform;if(!S.notarizeOn.includes(N))throw Error(`gjsify ship: notarising the ${S.layoutOs} layout needs ${S.tool}, which runs on ${S.notarizeOn.join(`, `)} and this host is ${N}.`);let F=S.args(C,n.artifact);n.verbose&&n.log(`${S.tool} ${F.join(` `)}`);let I=await spawnToCompletion(S.tool,F,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${S.tool}\` is not on PATH — ${S.installHint}.`)});if(I.code!==0)throw Error(`gjsify ship: ${S.tool} notarytool failed with ${describeExit(I)}.`);n.log(`${S.tool} notarytool accepted ${n.artifact}.`)}async function stapleArtifact(n){let S=[`stapler`,`staple`,n.artifact];n.verbose&&n.log(`${n.notary.tool} ${S.join(` `)}`);let C=await spawnToCompletion(n.notary.tool,S,{completion:`return`,stdio:`inherit`,notFound:()=>Error(`gjsify ship: \`${n.notary.tool}\` is not on PATH — ${n.notary.installHint}.`)});if(C.code!==0)throw Error(`gjsify ship: ${n.notary.tool} stapler failed with ${describeExit(C)}. The artifact is notarised and NOT stapled, which means every launch asks Gatekeeper to check online — and fails closed on a machine with no network. Re-run the finish phase; \`stapler\` requires internet access and the ticket may not have propagated yet.`);n.log(`${n.notary.tool} stapler attached the ticket to ${n.artifact}.`)}var Bz,Vz,Hz=__esmMin(()=>{Vl(),Hs(),dN(),_P(),VR(),TR(),aR(),zz(),Bz={darwin:{layoutOs:`darwin`,tool:`codesign`,signOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",signs:`macho`,args:({identity:n,file:S,entitlements:C,adhoc:N})=>[`--force`,`--sign`,n,`--options`,`runtime`,...C===void 0?[]:[`--entitlements`,C],...N?[]:[`--timestamp`],S],entitlements:[`com.apple.security.cs.allow-jit`,`com.apple.security.cs.allow-unsigned-executable-memory`,`com.apple.security.cs.disable-executable-page-protection`,`com.apple.security.cs.allow-dyld-environment-variables`],sealsBundle:!0,sealAddPrefix:n=>`${n}/Contents/_CodeSignature/`,configKey:`gjsify.ship.sign.darwin.identity`,gap:"the images are signed and the bundle is sealed; UNVERIFIED end to end — no macOS host in this repository has run a `--sign` over a real `.app`, and ADR 0024 § A16 still leaves library validation unmeasured"},win32:{layoutOs:`win32`,tool:`signtool`,signOn:[`win32`],installHint:"install the Windows SDK (signtool.exe ships in its `bin/<version>/x64` directory)",signs:`pe`,args:({identity:n,file:S})=>[`sign`,`/n`,n,`/fd`,`sha256`,S],entitlements:[],sealsBundle:!1,sealAddPrefix:()=>``,configKey:`gjsify.ship.sign.win32.identity`,gap:`no timestamp countersignature is requested, so the signature expires with the certificate (UNVERIFIED: no run in this repository has ever invoked signtool)`}},Vz={darwin:{layoutOs:`darwin`,tool:`xcrun`,notarizeOn:[`darwin`],installHint:"install the Xcode Command Line Tools (`xcode-select --install`) on a macOS host",args:(n,S)=>[`notarytool`,`submit`,`--keychain-profile`,n,`--wait`,S]}}});function stagedFontDir(n,S){return`${n}/${xs.basename(FL.fonts)}/${S}`}function shellQuote(n){return`'${n.replace(/'/g,`'\\''`)}'`}function cmdQuote(n){let S=/["%!\r\n]/.exec(n);if(S!==null)throw Error(`gjsify ship: \`gjsify.ship.execArgs\` contains ${JSON.stringify(n)}, and cmd.exe has no way to pass ${JSON.stringify(S[0])} through a Windows launcher literally — \`%\` expands at parse time and \`"\` ends the quoted run. Move the value into the app (it can read it from its own config) or drop the character.`);return`"${n}"`}function renderLauncher(n,S,C,N={}){switch(C.name){case`linux`:return renderPrefixLauncher(n,S,C);case`darwin`:return renderAppBundleLauncher(n,S,C,N);case`windows`:return renderWindowsLauncher(n,S,C,N);default:{let n=C.name;throw Error(`gjsify ship: no launcher is wired for the "${String(n)}" layout.`)}}}function renderPrefixLauncher(n,S,C){let N=C.dirs(n),F=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`self=$(readlink -f "$0")`,`prefix=$(dirname "$(dirname "$self")")`,`XDG_DATA_DIRS="$prefix/${N.data}:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"`,`export XDG_DATA_DIRS`];if(n.typelibFiles.length>0){let n=`"$prefix"/${N.native}`;for(let S of[`GI_TYPELIB_PATH`,`LD_LIBRARY_PATH`])F.push(`${S}=${n}\${${S}:+:$${S}}`,`export ${S}`)}return n.localeFiles.length>0&&F.push(`GJSIFY_LOCALE_DIR="$prefix"/${N.data}/locale`,`export GJSIFY_LOCALE_DIR`),n.fontFiles.length>0&&F.push(`GJSIFY_FONT_DIR="$prefix"/${stagedFontDir(N.data,n.appId)}`,`export GJSIFY_FONT_DIR`),F.push(`exec ${execLine(C,`"$prefix"/${N.bundle}/${S}`,n)} "$@"`,``),F.join(`
|
|
1105
1108
|
`)}function renderAppBundleLauncher(n,S,C,N){let F=`${C.root(n)}/Contents`,I=C.dirs(n),under=n=>xs.relative(F,n),beside=n=>xs.relative(I.launcher,n),H=[`#!/bin/sh`,"# Generated by `gjsify ship` — do not edit.",`set -e`,`here=$(cd -- "$(dirname -- "$0")" && pwd)`,`contents=$(dirname -- "$here")`,`XDG_DATA_DIRS="$contents/${under(I.data)}:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"`,`export XDG_DATA_DIRS`];N.gtkRuntimeDir!==void 0&&H.push(`GJSIFY_GTK_RUNTIME="$contents/${under(N.gtkRuntimeDir)}"`,`export GJSIFY_GTK_RUNTIME`),N.nodeGiAddon!==void 0&&H.push(`NODE_GI_NATIVE="$contents/${under(N.nodeGiAddon)}"`,`export NODE_GI_NATIVE`),n.typelibFiles.length>0&&(H.push(`GI_TYPELIB_PATH="$contents/${under(I.native)}"\${GI_TYPELIB_PATH:+:$GI_TYPELIB_PATH}`,`export GI_TYPELIB_PATH`),H.push(`GJSIFY_GI_LIBRARY_PATH="$contents/${under(I.native)}"\${GJSIFY_GI_LIBRARY_PATH:+:$GJSIFY_GI_LIBRARY_PATH}`,`export GJSIFY_GI_LIBRARY_PATH`)),n.localeFiles.length>0&&H.push(`GJSIFY_LOCALE_DIR="$contents/${under(I.data)}/locale"`,`export GJSIFY_LOCALE_DIR`),n.fontFiles.length>0&&H.push(`GJSIFY_FONT_DIR="$contents/${stagedFontDir(under(I.data),n.appId)}"`,`export GJSIFY_FONT_DIR`);let W=N.interpreter===void 0?void 0:`"$here/${beside(N.interpreter)}"`;return H.push(`exec ${execLine(C,`"$contents/${under(I.bundle)}/${S}"`,n,W)} "$@"`,``),H.join(`
|
|
1106
1109
|
`)}function renderWindowsLauncher(n,S,C,N){let F=C.dirs(n),at=n=>`%HERE%${windowsPath(n)}`,I=[`@echo off`,`rem Generated by "gjsify ship" - do not edit.`,`setlocal`,`set "HERE=%~dp0"`,prependVar(`XDG_DATA_DIRS`,at(F.data))];N.gtkRuntimeDir!==void 0&&I.push(`set "GJSIFY_GTK_RUNTIME=${at(N.gtkRuntimeDir)}"`),N.nodeGiAddon!==void 0&&I.push(`set "NODE_GI_NATIVE=${at(N.nodeGiAddon)}"`),n.typelibFiles.length>0&&I.push(prependVar(`GI_TYPELIB_PATH`,at(F.native)),prependVar(`PATH`,at(F.native))),n.localeFiles.length>0&&I.push(`set "GJSIFY_LOCALE_DIR=${at(F.data)}\\locale"`),n.fontFiles.length>0&&I.push(`set "GJSIFY_FONT_DIR=${at(stagedFontDir(F.data,n.appId))}"`);let H=N.interpreter===void 0?void 0:`"${at(N.interpreter)}"`;return I.push(`${execLine(C,`"${at(F.bundle)}\\${windowsPath(S)}"`,n,H)} %*`,``),I.join(`\r
|
|
1107
|
-
`)}function prependVar(n,S){return`if defined ${n} (set "${n}=${S};%${n}%") else (set "${n}=${S}")`}function windowsPath(n){return n.split(`/`).filter(n=>n.length>0).join(`\\`)}function execLine(n,S,C,N){let F=n.name===`windows`?cmdQuote:shellQuote,I=C.execArgs.map(F).join(` `),H=N??(C.app===`node`?`node`:`gjs`);return`${C.app===`node`?H:`${H} -m`} ${S}${I?` ${I}`:``}`}var
|
|
1110
|
+
`)}function prependVar(n,S){return`if defined ${n} (set "${n}=${S};%${n}%") else (set "${n}=${S}")`}function windowsPath(n){return n.split(`/`).filter(n=>n.length>0).join(`\\`)}function execLine(n,S,C,N){let F=n.name===`windows`?cmdQuote:shellQuote,I=C.execArgs.map(F).join(` `),H=N??(C.app===`node`?`node`:`gjs`);return`${C.app===`node`?H:`${H} -m`} ${S}${I?` ${I}`:``}`}var Uz=__esmMin(()=>{Hs(),IL()});function createCpioArchive(n){let S=[],C=0;n.forEach((n,N)=>{let F=n.linkTarget===void 0?n.data??new Uint8Array:encodeUtf8(n.linkTarget),I=encodeUtf8(`${n.name}\0`),H=buildHeader({ino:n.ino??N+1,mode:n.mode,nlink:n.nlink??1,mtime:n.mtime??0,filesize:F.byteLength,namesize:I.byteLength});C=push(S,H,C),C=push(S,I,C),C=padTo4(S,C),C=push(S,F,C),C=padTo4(S,C)});let N=encodeUtf8(`TRAILER!!!\0`);return C=push(S,buildHeader({ino:0,mode:0,nlink:1,mtime:0,filesize:0,namesize:N.byteLength}),C),C=push(S,N,C),padTo4(S,C),concatBytes(S)}function buildHeader(n){let S=Wz+hex8(n.ino)+hex8(n.mode)+hex8(0)+hex8(0)+hex8(n.nlink)+hex8(n.mtime)+hex8(n.filesize)+hex8(0)+hex8(0)+hex8(0)+hex8(0)+hex8(n.namesize)+hex8(0);if(S.length!==Gz)throw Error(`gjsify ship: internal error — cpio header is ${S.length} bytes, expected ${Gz}.`);return encodeUtf8(S)}function hex8(n){if(n<0||!Number.isInteger(n))throw Error(`gjsify ship: cpio header field must be a non-negative integer, got ${n}.`);let S=n.toString(16).toUpperCase();if(S.length>8)throw Error(`gjsify ship: cpio header field ${n} does not fit in 8 hex digits.`);return S.padStart(8,`0`)}function push(n,S,C){return S.byteLength>0&&n.push(S),C+S.byteLength}function padTo4(n,S){let C=S%4;if(C===0)return S;let N=4-C;return n.push(new Uint8Array(N)),S+N}var Wz,Gz,Kz,qz,Jz=__esmMin(()=>{xL(),Wz=`070701`,Gz=110,Kz=32768,qz=16384});function buildRpmHeader(n,S){let C=[...n].sort((n,S)=>n.tag-S.tag),N=[],F=[],I=0;for(let n of C){if(n.tag<100)throw Error(`gjsify ship: rpm tag ${n.tag} is below 100 and would be rejected by hdrchkTag.`);let{data:S,count:C}=encodeValue(n.type,n.value,n.tag),H=Qz[n.type],W=(H-I%H)%H;W>0&&(F.push(new Uint8Array(W)),I+=W),N.push({tag:n.tag,type:n.type,offset:I,count:C}),F.push(S),I+=S.byteLength}let H=I,W=N.length+1;F.push(indexEntry(S,7,-(Xz*W),Zz)),I+=Xz;let q=new Uint8Array(Yz.byteLength+8+W*Xz+I),Y=new DataView(q.buffer);q.set(Yz,0),Y.setUint32(8,W),Y.setUint32(12,I);let X=16;q.set(indexEntry(S,7,H,Zz),X),X+=Xz;for(let n of N)q.set(indexEntry(n.tag,n.type,n.offset,n.count),X),X+=Xz;for(let n of F)q.set(n,X),X+=n.byteLength;return q}function indexEntry(n,S,C,N){let F=new Uint8Array(Xz),I=new DataView(F.buffer);return I.setInt32(0,n),I.setInt32(4,S),I.setInt32(8,C),I.setInt32(12,N),F}function encodeValue(n,S,C){let N=new TextEncoder;switch(n){case 6:if(typeof S!=`string`)throw typeMismatch(C,`a string`);return{data:N.encode(`${S}\0`),count:1};case 8:case 9:{let n=typeof S==`string`?[S]:S;if(!Array.isArray(n))throw typeMismatch(C,`a string array`);if(n.length===0)throw Error(`gjsify ship: rpm tag ${C} has an empty array; omit it instead.`);return{data:N.encode(n.map(n=>`${n}\0`).join(``)),count:n.length}}case 7:if(!(S instanceof Uint8Array))throw typeMismatch(C,`binary data`);return{data:S,count:S.byteLength};case 3:case 4:{let N=typeof S==`number`?[S]:S;if(!Array.isArray(N))throw typeMismatch(C,`a number array`);if(N.length===0)throw Error(`gjsify ship: rpm tag ${C} has an empty array; omit it instead.`);let F=n===3?2:4,I=new Uint8Array(N.length*F),H=new DataView(I.buffer);return N.forEach((S,C)=>{n===3?H.setUint16(C*F,S&65535):H.setUint32(C*F,S>>>0)}),{data:I,count:N.length}}}}function typeMismatch(n,S){return Error(`gjsify ship: internal error — rpm tag ${n} expects ${S}.`)}function buildRpmLead(n){let S=new Uint8Array(96),C=new DataView(S.buffer);S.set([237,171,238,219],0),S[4]=3,S[5]=0,C.setInt16(6,0),C.setInt16(8,0);let N=new TextEncoder().encode(n).slice(0,65);return S.set(N,10),C.setInt16(76,0),C.setInt16(78,5),S}function padToEight(n){let S=(8-n.byteLength%8)%8;if(S===0)return n;let C=new Uint8Array(n.byteLength+S);return C.set(n,0),C}var Yz,Xz,Zz,Qz,$z=__esmMin(()=>{Yz=Uint8Array.from([142,173,232,1,0,0,0,0]),Xz=16,Zz=16,Qz={3:2,4:4,6:1,7:1,8:1,9:1}});async function buildRpm(n){let{settings:S,mtime:C}=n,N=collectFiles(n,`/${n.prefix.replace(/^\/+|\/+$/g,``)}`),F=createCpioArchive(N.map((n,S)=>({name:`.${n.path}`,mode:n.mode,data:n.data,mtime:C,ino:S+1}))),I=await gzipDeterministic(F),H=buildRpmHeader(mainHeaderEntries(n,N,F,I),63),W=concatBytes([H,I]),q=padToEight(buildRpmHeader([{tag:tB.SHA1HEADER,type:6,value:hashHex(`sha1`,H)},{tag:tB.SHA256HEADER,type:6,value:hashHex(`sha256`,H)},{tag:tB.SIZE,type:4,value:[W.byteLength]},{tag:tB.MD5,type:7,value:hashBytes(`md5`,W)},{tag:tB.PAYLOADSIZE,type:4,value:[F.byteLength]}],62));return concatBytes([buildRpmLead(`${S.binaryName}-${S.version}-${S.release}`),q,W])}function collectFiles(n,S){let C=n.payload.map(n=>{if(n.data.byteLength>4294967295)throw Error(`gjsify ship: ${n.path} is larger than 4 GiB, which needs rpm's LONGFILESIZES tag. That is not implemented — split the payload.`);return{path:`${S}/${n.path}`,mode:Kz|n.mode&4095,data:n.data,isDirectory:!1}}),N=new Set;for(let n of C){let S=n.path.split(`/`).slice(1);S.pop();let C=``;for(let n of S)C=`${C}/${n}`,aB.has(C)||N.add(C)}for(let n of N)C.push({path:n,mode:qz|493,data:new Uint8Array,isDirectory:!0});return C.sort((n,S)=>n.path<S.path?-1:+(n.path>S.path))}function mainHeaderEntries(n,S,C,N){let{settings:F}=n,I=`${F.version}-${F.release}`,H=[],W=[],q=[];for(let n of S){let S=n.path.lastIndexOf(`/`),C=`${n.path.slice(0,S)}/`,N=H.indexOf(C);N===-1&&(N=H.push(C)-1),W.push(N),q.push(n.path.slice(S+1))}let Y=renderRpmScriptlets(readPayloadFacts(n.payload),n.prefix),X=buildRequires(n.depends,Y,readShebangInterpreters(n.payload)),Z=[{tag:eB.HEADERI18NTABLE,type:8,value:[`C`]},{tag:eB.NAME,type:6,value:F.binaryName},{tag:eB.VERSION,type:6,value:F.version},{tag:eB.RELEASE,type:6,value:F.release},{tag:eB.SUMMARY,type:9,value:[F.summary]},{tag:eB.DESCRIPTION,type:9,value:[F.description.join(`
|
|
1108
1111
|
|
|
1109
|
-
`)]},{tag:Uz.BUILDTIME,type:4,value:[n.mtime]},{tag:Uz.BUILDHOST,type:6,value:`localhost`},{tag:Uz.SIZE,type:4,value:[S.reduce((n,S)=>n+S.data.byteLength,0)]},{tag:Uz.LICENSE,type:6,value:F.license},{tag:Uz.GROUP,type:9,value:[F.group]},{tag:Uz.OS,type:6,value:`linux`},{tag:Uz.ARCH,type:6,value:n.archLabel},{tag:Uz.SOURCERPM,type:6,value:`${F.binaryName}-${I}.src.rpm`},{tag:Uz.RPMVERSION,type:6,value:`4.20.0`},{tag:Uz.ENCODING,type:6,value:`utf-8`},{tag:Uz.FILESIZES,type:4,value:S.map(n=>n.data.byteLength)},{tag:Uz.FILEMODES,type:3,value:S.map(n=>n.mode)},{tag:Uz.FILERDEVS,type:3,value:S.map(()=>0)},{tag:Uz.FILEMTIMES,type:4,value:S.map(()=>n.mtime)},{tag:Uz.FILEDIGESTS,type:8,value:S.map(n=>n.isDirectory?``:hashHex(`sha256`,n.data))},{tag:Uz.FILELINKTOS,type:8,value:S.map(()=>``)},{tag:Uz.FILEFLAGS,type:4,value:S.map(()=>0)},{tag:Uz.FILEUSERNAME,type:8,value:S.map(()=>`root`)},{tag:Uz.FILEGROUPNAME,type:8,value:S.map(()=>`root`)},{tag:Uz.FILEVERIFYFLAGS,type:4,value:S.map(()=>4294967295)},{tag:Uz.FILEDEVICES,type:4,value:S.map(()=>1)},{tag:Uz.FILEINODES,type:4,value:S.map((n,S)=>S+1)},{tag:Uz.FILELANGS,type:8,value:S.map(()=>``)},{tag:Uz.FILEDIGESTALGO,type:4,value:[Kz]},{tag:Uz.DIRINDEXES,type:4,value:W},{tag:Uz.BASENAMES,type:8,value:q},{tag:Uz.DIRNAMES,type:8,value:H},{tag:Uz.PROVIDENAME,type:8,value:[F.binaryName]},{tag:Uz.PROVIDEFLAGS,type:4,value:[Gz.EQUAL]},{tag:Uz.PROVIDEVERSION,type:8,value:[I]},{tag:Uz.REQUIRENAME,type:8,value:X.names},{tag:Uz.REQUIREFLAGS,type:4,value:X.flags},{tag:Uz.REQUIREVERSION,type:8,value:X.versions},{tag:Uz.PAYLOADFORMAT,type:6,value:`cpio`},{tag:Uz.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:Uz.PAYLOADFLAGS,type:6,value:`9`},{tag:Uz.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,N)]},{tag:Uz.PAYLOADDIGESTALGO,type:4,value:[Kz]},{tag:Uz.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,C)]}];return assertParallelFileArrays(Z,S.length),F.homepage&&Z.push({tag:Uz.URL,type:6,value:F.homepage}),Y.post!==void 0&&(Z.push({tag:Uz.POSTIN,type:6,value:Y.post}),Z.push({tag:Uz.POSTINPROG,type:6,value:`/bin/sh`})),Y.postun!==void 0&&(Z.push({tag:Uz.POSTUN,type:6,value:Y.postun}),Z.push({tag:Uz.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(n,S){let C=new Set([Uz.FILESIZES,Uz.FILEMODES,Uz.FILERDEVS,Uz.FILEMTIMES,Uz.FILEDIGESTS,Uz.FILELINKTOS,Uz.FILEFLAGS,Uz.FILEUSERNAME,Uz.FILEGROUPNAME,Uz.FILEVERIFYFLAGS,Uz.FILEDEVICES,Uz.FILEINODES,Uz.FILELANGS,Uz.DIRINDEXES,Uz.BASENAMES]);for(let N of n){if(!C.has(N.tag))continue;let n=Array.isArray(N.value)?N.value.length:1;if(n!==S)throw Error(`gjsify ship: internal error — rpm tag ${N.tag} has ${n} values for ${S} files.`)}}function buildRequires(n,S,C){let N=[],F=[],I=[];for(let S of n){let n=parseDepend(S);N.push(n.name),F.push(senseFor(n.relation)),I.push(n.version??``)}S.post!==void 0&&(N.push(`/bin/sh`),F.push(Gz.INTERP|Gz.SCRIPT_POST),I.push(``)),S.postun!==void 0&&(N.push(`/bin/sh`),F.push(Gz.INTERP|Gz.SCRIPT_POSTUN),I.push(``));for(let n of C)N.push(n),F.push(Gz.FIND_REQUIRES),I.push(``);for(let[n,S]of qz)N.push(n),F.push(Gz.RPMLIB|Gz.LESS|Gz.EQUAL),I.push(S);return{names:N,flags:F,versions:I}}function senseFor(n){switch(n){case`>=`:return Gz.GREATER|Gz.EQUAL;case`>`:return Gz.GREATER;case`<=`:return Gz.LESS|Gz.EQUAL;case`<`:return Gz.LESS;case`=`:return Gz.EQUAL;default:return 0}}function hashHex(n,S){return createHash(n).update(S).digest(`hex`)}function hashBytes(n,S){return new Uint8Array(createHash(n).update(S).digest())}var Uz,Wz,Gz,Kz,qz,Jz,Yz=__esmMin(()=>{No(),bL(),Lz(),ML(),wR(),Hz(),NL(),IL(),FL(),Uz={HEADERI18NTABLE:100,NAME:1e3,VERSION:1001,RELEASE:1002,SUMMARY:1004,DESCRIPTION:1005,BUILDTIME:1006,BUILDHOST:1007,SIZE:1009,LICENSE:1014,GROUP:1016,URL:1020,OS:1021,ARCH:1022,POSTIN:1024,POSTUN:1026,FILESIZES:1028,FILEMODES:1030,FILERDEVS:1033,FILEMTIMES:1034,FILEDIGESTS:1035,FILELINKTOS:1036,FILEFLAGS:1037,FILEUSERNAME:1039,FILEGROUPNAME:1040,SOURCERPM:1044,FILEVERIFYFLAGS:1045,PROVIDENAME:1047,REQUIREFLAGS:1048,REQUIRENAME:1049,REQUIREVERSION:1050,RPMVERSION:1064,POSTINPROG:1086,POSTUNPROG:1088,FILEDEVICES:1095,FILEINODES:1096,FILELANGS:1097,PROVIDEFLAGS:1112,PROVIDEVERSION:1113,DIRINDEXES:1116,BASENAMES:1117,DIRNAMES:1118,PAYLOADFORMAT:1124,PAYLOADCOMPRESSOR:1125,PAYLOADFLAGS:1126,FILEDIGESTALGO:5011,ENCODING:5062,PAYLOADDIGEST:5092,PAYLOADDIGESTALGO:5093,PAYLOADDIGESTALT:5097},Wz={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},Gz={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},Kz=8,qz=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],Jz=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${PL.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${PL.metainfo}`,`/usr/share/glib-2.0`,`/usr/${PL.schemas}`,`/usr/${PL.fonts}`,`/etc`,`/opt`,`/var`])});async function assemble(n){let S=process.cwd(),C=n.os===void 0?hostLayout():resolveLayout(n.os),N=await new Config().forCommand(S),F=N.ship??{},I=N.flatpak??{},H=resolveShipApp({project:N.app,perTarget:F.app,layoutOs:C.os}),W=H.app;H.overridden&&ve.log(`${Xz} runtime for ${C.name}: ${W} — \`${H.key}\` overrides \`gjsify.app${N.app===void 0?``:`: "${N.app}"`}\`.`);let q=readPackageJson$2(js(S,`package.json`))??{},Y,X=[];if(n.target!==void 0)Y=resolveFormats(n.target,C);else if(F.targets!==void 0){let n=configuredFormats(F.targets,C);Y=n.formats,n.dropped.length>0&&ve.log(`${Xz} \`gjsify.ship.targets\` names ${n.dropped.join(`, `)}, which wrap another layout — not built for ${C.name}. Pass --target to ask for one explicitly.`)}else{let n=defaultFormatIds(C.os).map(n=>cz[n]);Y=n.filter(n=>n.interpreters.includes(W)),X=n.filter(n=>!n.interpreters.includes(W)),X.length>0&&ve.log(`${Xz} ${X.map(n=>n.id).join(`, `)} wrap the ${C.name} layout but cannot run \`${W}\`, which \`${H.key}\` resolves to — ${X[0]?.interpreterGap??``}. Set \`gjsify.ship.app.${C.os}\` to "${X[0]?.interpreters.join(`" / "`)}" to ship this OS on that runtime; it leaves every other target on \`gjsify.app\`. Assembling the layout only; pass --target to be told the same thing as an error.`)}n.stage||assertPackable(Y,C,n.os===void 0?`host`:`positional`,X);let Z=resolveSignPlan({flag:n.sign,config:F.sign,layoutOs:C.os}),te=resolveNotaryPlan({flag:n.notarize,layoutOs:C.os,sign:Z});if(n.stage&&assertNothingToSignYet(n),n.stage||(announceSigning(Z,te),Z.kind===`sign`&&assertHostCanSign(Z.signer)),!n.stage)for(let n of Y)assertCanPack(n);n[`skip-build`]||await runProjectBuild(S);let ne=discoverPayload({projectDir:S,pkg:q,ship:F,flatpakIcon:I.icon,declaredBundle:declaredBundlePath(q,F)}),{settings:re,metadata:ie,warnings:ae}=resolveShipSettings({projectDir:S,pkg:q,ship:F,flatpak:I,cli:{outDir:n.out,arch:n.arch,layoutOs:C.os},discovered:ne,app:W});for(let n of ae)ve.warn(`${Xz} ${n}`);for(let n of Y)assertFormatCanRunInterpreter(n,re.app);let oe=buildTimestamp(re.bundlePath),se={appId:re.appId,name:re.name,command:re.binaryName,kind:re.kind,metadata:ie,configKey:`gjsify.ship`,copyrightYear:new Date(oe*1e3).getUTCFullYear()};for(let n of validateAppMetadata(se))ve.warn(`${Xz} ${n.field} is not set — ${n.hint}`);re.licenseFile!==void 0&&Ps(re.licenseFile)!==S&&ve.log(`${Xz} licence text from ${Ms(S,re.licenseFile)} (this package carries none of its own)`);let Q=localizeMetadata({metainfo:re.kind===`app`?renderMetainfoApp$1(se):renderMetainfoCli$1(se),desktopEntry:re.kind===`app`?renderDesktopEntry(se):void 0},re.localeFiles),ce=resolveCarriedRuntime(C,re,S),le={bundleFiles:ne.bundleFiles,launcher:renderLauncher(re,Fs(re.bundlePath),C,ce.launcher),metainfo:Q.metainfo,desktopEntry:Q.desktopEntry,licenseText:re.licenseFile===void 0?void 0:readFileSync(re.licenseFile,`utf-8`)},ue=Os(S,re.outDir),de=js(ue,`stage`),fe=[...planStage(re,le),...C.os===`linux`?[]:await compileSchemasForStage({schemaFiles:re.schemaFiles,workDir:js(ue,`schemas`)})],pe=placeStage(C,re,fe,ce.files);if(writeStage(de,pe),ve.log(`${Xz} staged ${pe.length} file(s) for ${C.name} in ${Ms(S,de)}/`),n.verbose)for(let n of pe)ve.log(`${Xz} ${n.path}`);if(assertPayloadMatchesArch(readStage([de],pe),re.arch),C.os!==`linux`){let n=linuxInstallDependent(fe);if(n.length>0){ve.warn(`${Xz} the ${C.name} layout carries ${n.length} file(s) whose Linux correctness comes from a package install step it has no equivalent for:`);let S={aborts:`ABORTS: `,unknown:`UNCLASSIFIED: `,inert:``};for(let{path:C,verdict:N,why:F}of n)ve.warn(`${Xz} ${S[N]??``}${C} — ${F}`)}for(let n of ce.found)ve.log(`${Xz} carries its own ${n}`);for(let n of ce.missing)ve.warn(`${Xz} ${n}`);ce.launcher.interpreter===void 0&&C.runtimeGap!==void 0&&ve.warn(`${Xz} ${C.runtimeGap}`),C.fontGap!==void 0&&fe.some(n=>isUnder(n.path,PL.fonts))&&ve.warn(`${Xz} ${C.fontGap}`),C.arches!==null&&!C.arches.only.includes(re.arch)&&ve.warn(`${Xz} this stage is labelled ${re.arch} and the ${C.name} layout has no runtime for it — ${C.arches.why}. Nothing can pack this stage; \`--arch ${C.arches.only.join(`|`)}\` is what produces an artifact.`)}let me=scanGiNamespaces(readFileSync(re.bundlePath,`utf-8`));n.verbose&&ve.log(`${Xz} gi namespaces: ${me.join(`, `)||`(none)`}`);let he=new Map;for(let n of Y)he.set(n.id,planOverlay(re,n,le).map(n=>({...n,path:place(C,re,n.path)})));let ge=readPayloadFacts(fe);for(let n of Y){if(n.depends===null)continue;deriveDepends(n.depends,{namespaces:me,hasIcons:ge.hasIcons,hasSchemas:ge.hasSchemas,interpreter:re.app,extra:re.extraDepends[n.depends],typelibPackages:re.typelibPackages,bundledTypelibs:ge.bundledTypelibs,minGjsVersion:re.minGjsVersion,minNodeVersion:re.minNodeVersion});let S=re.app===`node`?warnAboutNodeFloor(n.depends,re.minNodeVersion):warnAboutGjsFloor(n.depends,re.minGjsVersion);for(let n of S)ve.warn(`${Xz} ${n}`)}let _e=writeStageManifest({stageDir:de,settings:re,formats:Y,mtime:oe,namespaces:me,staged:pe,overlay:he});if(n.stage){let n=X.length>0?`(none — ${X.map(n=>n.id).join(` and `)} need \`gjsify.ship.app.${C.os}: "node"\`)`:formatIdsFor(C.os).length===0?`(none — no format wraps the ${C.name} layout)`:`(none asked for)`,S=_e.formats.join(`, `)||n;ve.log(`${Xz} stage manifest: ${formatTarget(_e.target)}, formats ${S}`);return}let ye=[];for(let S of Y)ye.push(await packOne({format:S,settings:re,arch:re.arch,staged:pe,overlay:he.get(S.id)??[],stageDir:de,outRoot:ue,namespaces:me,mtime:oe,sign:Z,notarize:te,verbose:n.verbose}));printArtifacts(S,ye)}function assertNothingToSignYet(n){let S=n.sign===void 0?n.notarize===void 0?void 0:`--notarize`:`--sign`;if(S!==void 0)throw Error(`gjsify ship: ${S} belongs to the finish phase, and --stage produces no artifact to sign — it writes the tree a packing host reads back. Assemble here, then run \`gjsify ship --from-stage <dir> --sign <identity>\` on the host that holds the identity (ADR 0024 § A2, § A14).`)}function announceSigning(n,S){n.kind===`skip`&&ve.warn(`${Xz} ${n.message}`),S.kind===`skip`&&n.kind===`sign`&&ve.warn(`${Xz} ${S.message}`)}function resolveCarriedRuntime(n,S,C){let N={files:[],launcher:{},found:[],missing:[]};if(n.os===`linux`||S.app!==`node`)return N;let F=`${n.os}-${S.arch}`;return isGtkRuntimeTarget(F)?stageAppRuntime({layout:n,identity:S,target:F,cwd:C,interpreter:isNodeRuntimeTarget(F)?resolveNodeRuntime(F,{cwd:C}):null}):N}async function finishFromStage(n,S){if(n.stage)throw Error("gjsify ship: --stage and --from-stage are the two halves of one split and cannot run together. `--stage` assembles a payload and stops; `--from-stage <dir>` packs one that is already assembled. Run them as two commands, on the host each belongs on (ADR 0024 § A2).");if(n[`skip-build`])throw Error(`gjsify ship: --from-stage never runs a build — the payload it packs was built and staged by an earlier run — so --skip-build has nothing to skip. Drop it.`);if(n.arch!==void 0)throw Error("gjsify ship: --arch is decided when the stage is assembled, not when it is packed: the launcher, the payload and the recorded target were all fixed then. Pass --arch to `gjsify ship --stage`, and use `--expect-target <os>-<arch>` here to assert which leg you are packing.");if(n.os!==void 0)throw Error(`gjsify ship: the layout is decided when the stage is assembled, so "${n.os}" has nothing to change here — the staged tree already IS one OS's layout. Use \`--expect-target <os>-<arch>\` to assert which one you are packing.`);let C=process.cwd(),N=Os(C,S),F=readStageManifest(N);assertExpectedTarget(F,n[`expect-target`]);let I=layoutForOs(F.target.os);n.target===void 0&&assertPackable(F.formats.map(n=>cz[n]),I,`stage`,defaultFormatIds(I.os).map(n=>cz[n]).filter(n=>!n.interpreters.includes(F.settings.app)));let H=resolveFormats(n.target??F.formats,I);assertFormatsStaged(F,H);for(let n of H)assertCanPack(n);let W=resolveSignPlan({flag:n.sign,layoutOs:I.os}),q=resolveNotaryPlan({flag:n.notarize,layoutOs:I.os,sign:W});announceSigning(W,q),W.kind===`sign`&&assertHostCanSign(W.signer);for(let n of warnOnToolSkew(F))ve.warn(`${Xz} ${n}`);let{mtime:Y,warnings:X}=resolveStageMtime(F);for(let n of X)ve.warn(`${Xz} ${n}`);if(ve.log(`${Xz} packing ${F.settings.binaryName} ${F.settings.version}-${F.settings.release} for ${formatTarget(F.target)} from ${Ms(C,N)||`.`}/`),n.verbose){for(let n of F.staged)ve.log(`${Xz} ${n.path}`);ve.log(`${Xz} gi namespaces: ${F.namespaces.join(`, `)||`(none)`}`)}let Z=n.out===void 0?Ps(N):Os(C,n.out),te=[];for(let S of H){if(assertFormatCanRunInterpreter(S,F.settings.app),S.depends!==null){let n=F.settings.app===`node`?warnAboutNodeFloor(S.depends,F.settings.minNodeVersion):warnAboutGjsFloor(S.depends,F.settings.minGjsVersion);for(let S of n)ve.warn(`${Xz} ${S}`)}te.push(await packOne({format:S,settings:F.settings,arch:F.target.arch,staged:F.staged,overlay:overlayFiles(F,S.id),stageDir:N,outRoot:Z,namespaces:F.namespaces,mtime:Y,sign:W,notarize:q,verbose:n.verbose}))}printArtifacts(C,te)}async function packOne(n){let{format:S,settings:C,stageDir:N,outRoot:F,mtime:I}=n;assertOverlayIsLicensed(S.id,C.binaryName,n.overlay);let H=js(F,`overlay`,S.id);writeStage(H,n.overlay);let W=readStage([N,H],[...n.staged,...n.overlay]),q=readPayloadFacts(W),Y=S.depends===null?[]:deriveDepends(S.depends,{namespaces:n.namespaces,hasIcons:q.hasIcons,hasSchemas:q.hasSchemas,interpreter:C.app,extra:C.extraDepends[S.depends],typelibPackages:C.typelibPackages,bundledTypelibs:q.bundledTypelibs,minGjsVersion:C.minGjsVersion,minNodeVersion:C.minNodeVersion});assertPayloadMatchesArch(W,n.arch);let X=layoutForOs(S.layoutOs);assertLauncherMatchesInterpreter(W,X,C,C.app),assertLayoutSupportsArch(X,n.arch);let Z=n.sign.kind===`sign`?await signPayload({payload:W,identity:n.sign.identity,signer:n.sign.signer,workDir:js(F,`signed`,S.id),bundleRoot:X.root(C),entitlementsPath:js(F,`signed`,`${S.id}.entitlements.plist`),verbose:n.verbose,log:n=>ve.log(`${Xz} ${n}`)}):W,te=S.archName(n.arch,isArchIndependent(Z)),ne={settings:C,payload:Z,prefix:S.prefix,depends:Y,archLabel:te,mtime:I},re=js(F,`out`);mkdirSync(re,{recursive:!0});let ie=js(re,S.fileName(C,te));switch(S.id){case`deb`:writeFileSync(ie,await buildDeb(ne));break;case`rpm`:writeFileSync(ie,await buildRpm(ne));break;case`flatpak`:await buildFlatpakBundle({settings:C,stageDir:N,overlayDir:H,stageManifestFile:Ez,workDir:js(F,`flatpak`),target:ie,archLabel:te,verbose:n.verbose});break;case`macos-app`:case`windows-dir`:writePayload(ie,Z,X.root(C));break;case`macos-app-dmg`:{let S=dmgVolumeDir(F);writePayload(S,Z,``),await buildDmgImage({volumeName:dmgVolumeName(C),sourceDir:S,target:ie,workDir:Ps(S),verbose:n.verbose});break}case`macos-app-zip`:writeFileSync(ie,buildZip(zipEntriesFromPayload(Z),I));break;case`windows-dir-zip`:writeFileSync(ie,buildZip(zipEntriesFromPayload(Z,windowsProgramDirName(C)),I));break;case`msi`:{let S=js(F,`msi`);writePayload(js(S,mz),Z,X.root(C)),await buildMsi({settings:C,files:Z.map(n=>({path:n.path,source:`${mz}/${n.path}`})),programDirName:windowsProgramDirName(C),archLabel:te,workDir:S,target:ie,verbose:n.verbose});break}default:{let n=S.id;throw Error(`gjsify ship: no packer is wired for format "${String(n)}".`)}}let ae=S.artifactKind===`directory`?directorySize(ie):statSync(ie).size;return n.notarize.kind===`notarize`&&(S.artifactKind===`directory`?ve.warn(`${Xz} ${S.id} is a directory, and notarytool submits an archive or an installer — not notarised. The container format beside it is what carries the ticket.`):(await notarizeArtifact({plan:n.notarize,artifact:ie,verbose:n.verbose,log:n=>ve.log(`${Xz} ${n}`)}),canCarryTicket(S.id)?await stapleArtifact({notary:n.notarize.notary,artifact:ie,verbose:n.verbose,log:n=>ve.log(`${Xz} ${n}`)}):ve.warn(`${Xz} ${S.id} is notarised and NOT stapled: \`stapler\` takes a UDIF image, a signed flat package or a code-signed bundle, and an archive is none of them. Apple's remedy is to staple each item that went INTO the archive and re-create it — for this artifact that is the \`.app\`, which \`--target macos-app\` writes beside it.`))),{format:S.id,path:ie,size:ae}}function printArtifacts(n,S){for(let C of S)ve.log(`${Xz} ${C.format}: ${Ms(n,C.path)} (${C.size} bytes)`)}function assertCanPack(n){assertHostCanFinish(n),assertToolsInstalled(n)}function assertPackable(n,S,C,N=[]){if(n.length>0)return;if(N.length>0)throw Error(`gjsify ship: ${N.map(n=>n.id).join(` and `)} wrap the ${S.name} layout, and neither can run this project — ${N[0]?.interpreterGap??``}.\n Set \`gjsify.ship.app.${S.os}\` to "${N[0]?.interpreters.join(`" / "`)}" — it overrides \`gjsify.app\` for THIS target and\n leaves every other one alone, which is what lets one project be GJS on Linux and Node here.
|
|
1112
|
+
`)]},{tag:eB.BUILDTIME,type:4,value:[n.mtime]},{tag:eB.BUILDHOST,type:6,value:`localhost`},{tag:eB.SIZE,type:4,value:[S.reduce((n,S)=>n+S.data.byteLength,0)]},{tag:eB.LICENSE,type:6,value:F.license},{tag:eB.GROUP,type:9,value:[F.group]},{tag:eB.OS,type:6,value:`linux`},{tag:eB.ARCH,type:6,value:n.archLabel},{tag:eB.SOURCERPM,type:6,value:`${F.binaryName}-${I}.src.rpm`},{tag:eB.RPMVERSION,type:6,value:`4.20.0`},{tag:eB.ENCODING,type:6,value:`utf-8`},{tag:eB.FILESIZES,type:4,value:S.map(n=>n.data.byteLength)},{tag:eB.FILEMODES,type:3,value:S.map(n=>n.mode)},{tag:eB.FILERDEVS,type:3,value:S.map(()=>0)},{tag:eB.FILEMTIMES,type:4,value:S.map(()=>n.mtime)},{tag:eB.FILEDIGESTS,type:8,value:S.map(n=>n.isDirectory?``:hashHex(`sha256`,n.data))},{tag:eB.FILELINKTOS,type:8,value:S.map(()=>``)},{tag:eB.FILEFLAGS,type:4,value:S.map(()=>0)},{tag:eB.FILEUSERNAME,type:8,value:S.map(()=>`root`)},{tag:eB.FILEGROUPNAME,type:8,value:S.map(()=>`root`)},{tag:eB.FILEVERIFYFLAGS,type:4,value:S.map(()=>4294967295)},{tag:eB.FILEDEVICES,type:4,value:S.map(()=>1)},{tag:eB.FILEINODES,type:4,value:S.map((n,S)=>S+1)},{tag:eB.FILELANGS,type:8,value:S.map(()=>``)},{tag:eB.FILEDIGESTALGO,type:4,value:[rB]},{tag:eB.DIRINDEXES,type:4,value:W},{tag:eB.BASENAMES,type:8,value:q},{tag:eB.DIRNAMES,type:8,value:H},{tag:eB.PROVIDENAME,type:8,value:[F.binaryName]},{tag:eB.PROVIDEFLAGS,type:4,value:[nB.EQUAL]},{tag:eB.PROVIDEVERSION,type:8,value:[I]},{tag:eB.REQUIRENAME,type:8,value:X.names},{tag:eB.REQUIREFLAGS,type:4,value:X.flags},{tag:eB.REQUIREVERSION,type:8,value:X.versions},{tag:eB.PAYLOADFORMAT,type:6,value:`cpio`},{tag:eB.PAYLOADCOMPRESSOR,type:6,value:`gzip`},{tag:eB.PAYLOADFLAGS,type:6,value:`9`},{tag:eB.PAYLOADDIGEST,type:8,value:[hashHex(`sha256`,N)]},{tag:eB.PAYLOADDIGESTALGO,type:4,value:[rB]},{tag:eB.PAYLOADDIGESTALT,type:8,value:[hashHex(`sha256`,C)]}];return assertParallelFileArrays(Z,S.length),F.homepage&&Z.push({tag:eB.URL,type:6,value:F.homepage}),Y.post!==void 0&&(Z.push({tag:eB.POSTIN,type:6,value:Y.post}),Z.push({tag:eB.POSTINPROG,type:6,value:`/bin/sh`})),Y.postun!==void 0&&(Z.push({tag:eB.POSTUN,type:6,value:Y.postun}),Z.push({tag:eB.POSTUNPROG,type:6,value:`/bin/sh`})),Z}function assertParallelFileArrays(n,S){let C=new Set([eB.FILESIZES,eB.FILEMODES,eB.FILERDEVS,eB.FILEMTIMES,eB.FILEDIGESTS,eB.FILELINKTOS,eB.FILEFLAGS,eB.FILEUSERNAME,eB.FILEGROUPNAME,eB.FILEVERIFYFLAGS,eB.FILEDEVICES,eB.FILEINODES,eB.FILELANGS,eB.DIRINDEXES,eB.BASENAMES]);for(let N of n){if(!C.has(N.tag))continue;let n=Array.isArray(N.value)?N.value.length:1;if(n!==S)throw Error(`gjsify ship: internal error — rpm tag ${N.tag} has ${n} values for ${S} files.`)}}function buildRequires(n,S,C){let N=[],F=[],I=[];for(let S of n){let n=parseDepend(S);N.push(n.name),F.push(senseFor(n.relation)),I.push(n.version??``)}S.post!==void 0&&(N.push(`/bin/sh`),F.push(nB.INTERP|nB.SCRIPT_POST),I.push(``)),S.postun!==void 0&&(N.push(`/bin/sh`),F.push(nB.INTERP|nB.SCRIPT_POSTUN),I.push(``));for(let n of C)N.push(n),F.push(nB.FIND_REQUIRES),I.push(``);for(let[n,S]of iB)N.push(n),F.push(nB.RPMLIB|nB.LESS|nB.EQUAL),I.push(S);return{names:N,flags:F,versions:I}}function senseFor(n){switch(n){case`>=`:return nB.GREATER|nB.EQUAL;case`>`:return nB.GREATER;case`<=`:return nB.LESS|nB.EQUAL;case`<`:return nB.LESS;case`=`:return nB.EQUAL;default:return 0}}function hashHex(n,S){return createHash(n).update(S).digest(`hex`)}function hashBytes(n,S){return new Uint8Array(createHash(n).update(S).digest())}var eB,tB,nB,rB,iB,aB,oB=__esmMin(()=>{No(),xL(),Jz(),NL(),TR(),$z(),PL(),LL(),IL(),eB={HEADERI18NTABLE:100,NAME:1e3,VERSION:1001,RELEASE:1002,SUMMARY:1004,DESCRIPTION:1005,BUILDTIME:1006,BUILDHOST:1007,SIZE:1009,LICENSE:1014,GROUP:1016,URL:1020,OS:1021,ARCH:1022,POSTIN:1024,POSTUN:1026,FILESIZES:1028,FILEMODES:1030,FILERDEVS:1033,FILEMTIMES:1034,FILEDIGESTS:1035,FILELINKTOS:1036,FILEFLAGS:1037,FILEUSERNAME:1039,FILEGROUPNAME:1040,SOURCERPM:1044,FILEVERIFYFLAGS:1045,PROVIDENAME:1047,REQUIREFLAGS:1048,REQUIRENAME:1049,REQUIREVERSION:1050,RPMVERSION:1064,POSTINPROG:1086,POSTUNPROG:1088,FILEDEVICES:1095,FILEINODES:1096,FILELANGS:1097,PROVIDEFLAGS:1112,PROVIDEVERSION:1113,DIRINDEXES:1116,BASENAMES:1117,DIRNAMES:1118,PAYLOADFORMAT:1124,PAYLOADCOMPRESSOR:1125,PAYLOADFLAGS:1126,FILEDIGESTALGO:5011,ENCODING:5062,PAYLOADDIGEST:5092,PAYLOADDIGESTALGO:5093,PAYLOADDIGESTALT:5097},tB={SIZE:1e3,MD5:1004,PAYLOADSIZE:1007,SHA1HEADER:269,SHA256HEADER:273},nB={LESS:2,GREATER:4,EQUAL:8,INTERP:256,SCRIPT_POST:1024,SCRIPT_POSTUN:4096,FIND_REQUIRES:16384,RPMLIB:1<<24},rB=8,iB=[[`rpmlib(CompressedFileNames)`,`3.0.4-1`],[`rpmlib(FileDigests)`,`4.6.0-1`],[`rpmlib(PayloadFilesHavePrefix)`,`4.0-1`]],aB=new Set([`/usr`,`/usr/bin`,`/usr/lib`,`/usr/lib64`,`/usr/libexec`,`/usr/sbin`,`/usr/share`,`/usr/${FL.applications}`,`/usr/share/doc`,`/usr/share/icons`,`/usr/share/licenses`,`/usr/share/man`,`/usr/${FL.metainfo}`,`/usr/share/glib-2.0`,`/usr/${FL.schemas}`,`/usr/${FL.fonts}`,`/etc`,`/opt`,`/var`])});async function assemble(n){let S=process.cwd(),C=n.os===void 0?hostLayout():resolveLayout(n.os),N=await new Config().forCommand(S),F=N.ship??{},I=N.flatpak??{},H=resolveShipApp({project:N.app,perTarget:F.app,layoutOs:C.os}),W=H.app;H.overridden&&ve.log(`${sB} runtime for ${C.name}: ${W} — \`${H.key}\` overrides \`gjsify.app${N.app===void 0?``:`: "${N.app}"`}\`.`);let q=readPackageJson$2(js(S,`package.json`))??{},Y,X=[];if(n.target!==void 0)Y=resolveFormats(n.target,C);else if(F.targets!==void 0){let n=configuredFormats(F.targets,C);Y=n.formats,n.dropped.length>0&&ve.log(`${sB} \`gjsify.ship.targets\` names ${n.dropped.join(`, `)}, which wrap another layout — not built for ${C.name}. Pass --target to ask for one explicitly.`)}else{let n=defaultFormatIds(C.os).map(n=>mz[n]);Y=n.filter(n=>n.interpreters.includes(W)),X=n.filter(n=>!n.interpreters.includes(W)),X.length>0&&ve.log(`${sB} ${X.map(n=>n.id).join(`, `)} wrap the ${C.name} layout but cannot run \`${W}\`, which \`${H.key}\` resolves to — ${X[0]?.interpreterGap??``}. Set \`gjsify.ship.app.${C.os}\` to "${X[0]?.interpreters.join(`" / "`)}" to ship this OS on that runtime; it leaves every other target on \`gjsify.app\`. Assembling the layout only; pass --target to be told the same thing as an error.`)}n.stage||assertPackable(Y,C,n.os===void 0?`host`:`positional`,X);let Z=resolveSignPlan({flag:n.sign,config:F.sign,layoutOs:C.os}),te=resolveNotaryPlan({flag:n.notarize,layoutOs:C.os,sign:Z});if(n.stage&&assertNothingToSignYet(n),n.stage||(announceSigning(Z,te),Z.kind===`sign`&&assertHostCanSign(Z.signer)),!n.stage)for(let n of Y)assertCanPack(n);n[`skip-build`]||await runProjectBuild(S);let ne=resolveShipBundle({pkg:q,ship:F,layoutOs:C.os});ne.overridden&&ve.log(`${sB} entry for ${C.name}: ${ne.declared} — \`${ne.key}\` overrides \`gjsify.main\`.`);let re=discoverPayload({projectDir:S,pkg:q,ship:F,flatpakIcon:I.icon,declaredBundle:ne.declared,foreignBundles:ne.foreign}),{settings:ie,metadata:ae,warnings:oe}=resolveShipSettings({projectDir:S,pkg:q,ship:F,flatpak:I,cli:{outDir:n.out,arch:n.arch,layoutOs:C.os},discovered:re,app:W});for(let n of oe)ve.warn(`${sB} ${n}`);for(let n of Y)assertFormatCanRunInterpreter(n,ie.app);let se=readFileSync(ie.bundlePath,`utf-8`);assertEntryRunsUnder({interpreter:ie.app,source:se,entry:Ms(S,ie.bundlePath)||ie.bundlePath,appKey:H.key,bundleKey:ne.key,layoutOs:C.os});let Q=buildTimestamp(ie.bundlePath),ce={appId:ie.appId,name:ie.name,command:ie.binaryName,kind:ie.kind,metadata:ae,configKey:`gjsify.ship`,copyrightYear:new Date(Q*1e3).getUTCFullYear()};for(let n of validateAppMetadata(ce))ve.warn(`${sB} ${n.field} is not set — ${n.hint}`);ie.licenseFile!==void 0&&Ps(ie.licenseFile)!==S&&ve.log(`${sB} licence text from ${Ms(S,ie.licenseFile)} (this package carries none of its own)`);let le=localizeMetadata({metainfo:ie.kind===`app`?renderMetainfoApp$1(ce):renderMetainfoCli$1(ce),desktopEntry:ie.kind===`app`?renderDesktopEntry(ce):void 0},ie.localeFiles),ue=resolveCarriedRuntime(C,ie,S),de={bundleFiles:re.bundleFiles,launcher:renderLauncher(ie,Fs(ie.bundlePath),C,ue.launcher),metainfo:le.metainfo,desktopEntry:le.desktopEntry,licenseText:ie.licenseFile===void 0?void 0:readFileSync(ie.licenseFile,`utf-8`),changelogText:ie.changelogFile===void 0?void 0:readFileSync(ie.changelogFile,`utf-8`),mtime:Q},fe=Os(S,ie.outDir),pe=js(fe,`stage`),me=[...planStage(ie,de),...C.os===`linux`?[]:await compileSchemasForStage({schemaFiles:ie.schemaFiles,workDir:js(fe,`schemas`)})],he=placeStage(C,ie,me,ue.files);if(writeStage(pe,he),ve.log(`${sB} staged ${he.length} file(s) for ${C.name} in ${Ms(S,pe)}/`),n.verbose)for(let n of he)ve.log(`${sB} ${n.path}`);if(assertPayloadMatchesArch(readStage([pe],he),ie.arch),C.os!==`linux`){let n=linuxInstallDependent(me);if(n.length>0){ve.warn(`${sB} the ${C.name} layout carries ${n.length} file(s) whose Linux correctness comes from a package install step it has no equivalent for:`);let S={aborts:`ABORTS: `,unknown:`UNCLASSIFIED: `,inert:``};for(let{path:C,verdict:N,why:F}of n)ve.warn(`${sB} ${S[N]??``}${C} — ${F}`)}for(let n of ue.found)ve.log(`${sB} carries its own ${n}`);for(let n of ue.missing)ve.warn(`${sB} ${n}`);ue.launcher.interpreter===void 0&&C.runtimeGap!==void 0&&ve.warn(`${sB} ${C.runtimeGap}`),C.fontGap!==void 0&&me.some(n=>isUnder(n.path,FL.fonts))&&ve.warn(`${sB} ${C.fontGap}`),C.arches!==null&&!C.arches.only.includes(ie.arch)&&ve.warn(`${sB} this stage is labelled ${ie.arch} and the ${C.name} layout has no runtime for it — ${C.arches.why}. Nothing can pack this stage; \`--arch ${C.arches.only.join(`|`)}\` is what produces an artifact.`)}let ge=scanGiNamespaces(se);n.verbose&&ve.log(`${sB} gi namespaces: ${ge.join(`, `)||`(none)`}`);let _e=new Map;for(let n of Y)_e.set(n.id,(await planOverlay(ie,n,de)).map(n=>({...n,path:place(C,ie,n.path)})));let ye=readPayloadFacts(me);for(let n of Y){if(n.depends===null)continue;deriveDepends(n.depends,{namespaces:ge,hasIcons:ye.hasIcons,hasSchemas:ye.hasSchemas,interpreter:ie.app,extra:ie.extraDepends[n.depends],typelibPackages:ie.typelibPackages,bundledTypelibs:ye.bundledTypelibs,minGjsVersion:ie.minGjsVersion,minNodeVersion:ie.minNodeVersion});let S=ie.app===`node`?warnAboutNodeFloor(n.depends,ie.minNodeVersion):warnAboutGjsFloor(n.depends,ie.minGjsVersion);for(let n of S)ve.warn(`${sB} ${n}`)}let be=writeStageManifest({stageDir:pe,settings:ie,formats:Y,mtime:Q,namespaces:ge,staged:he,overlay:_e});if(n.stage){let n=X.length>0?`(none — ${X.map(n=>n.id).join(` and `)} need \`gjsify.ship.app.${C.os}: "node"\`)`:formatIdsFor(C.os).length===0?`(none — no format wraps the ${C.name} layout)`:`(none asked for)`,S=be.formats.join(`, `)||n;ve.log(`${sB} stage manifest: ${formatTarget(be.target)}, formats ${S}`);return}let xe=[];for(let S of Y)xe.push(await packOne({format:S,settings:ie,arch:ie.arch,staged:he,overlay:_e.get(S.id)??[],stageDir:pe,outRoot:fe,namespaces:ge,mtime:Q,sign:Z,notarize:te,verbose:n.verbose}));printArtifacts(S,xe)}function assertNothingToSignYet(n){let S=n.sign===void 0?n.notarize===void 0?void 0:`--notarize`:`--sign`;if(S!==void 0)throw Error(`gjsify ship: ${S} belongs to the finish phase, and --stage produces no artifact to sign — it writes the tree a packing host reads back. Assemble here, then run \`gjsify ship --from-stage <dir> --sign <identity>\` on the host that holds the identity (ADR 0024 § A2, § A14).`)}function announceSigning(n,S){n.kind===`skip`&&ve.warn(`${sB} ${n.message}`),S.kind===`skip`&&n.kind===`sign`&&ve.warn(`${sB} ${S.message}`)}function resolveCarriedRuntime(n,S,C){let N={files:[],launcher:{},found:[],missing:[]};if(n.os===`linux`||S.app!==`node`)return N;let F=`${n.os}-${S.arch}`;return isGtkRuntimeTarget(F)?stageAppRuntime({layout:n,identity:S,target:F,cwd:C,interpreter:isNodeRuntimeTarget(F)?resolveNodeRuntime(F,{cwd:C}):null}):N}async function finishFromStage(n,S){if(n.stage)throw Error("gjsify ship: --stage and --from-stage are the two halves of one split and cannot run together. `--stage` assembles a payload and stops; `--from-stage <dir>` packs one that is already assembled. Run them as two commands, on the host each belongs on (ADR 0024 § A2).");if(n[`skip-build`])throw Error(`gjsify ship: --from-stage never runs a build — the payload it packs was built and staged by an earlier run — so --skip-build has nothing to skip. Drop it.`);if(n.arch!==void 0)throw Error("gjsify ship: --arch is decided when the stage is assembled, not when it is packed: the launcher, the payload and the recorded target were all fixed then. Pass --arch to `gjsify ship --stage`, and use `--expect-target <os>-<arch>` here to assert which leg you are packing.");if(n.os!==void 0)throw Error(`gjsify ship: the layout is decided when the stage is assembled, so "${n.os}" has nothing to change here — the staged tree already IS one OS's layout. Use \`--expect-target <os>-<arch>\` to assert which one you are packing.`);let C=process.cwd(),N=Os(C,S),F=readStageManifest(N);assertExpectedTarget(F,n[`expect-target`]);let I=layoutForOs(F.target.os);n.target===void 0&&assertPackable(F.formats.map(n=>mz[n]),I,`stage`,defaultFormatIds(I.os).map(n=>mz[n]).filter(n=>!n.interpreters.includes(F.settings.app)));let H=resolveFormats(n.target??F.formats,I);assertFormatsStaged(F,H);for(let n of H)assertCanPack(n);let W=resolveSignPlan({flag:n.sign,layoutOs:I.os}),q=resolveNotaryPlan({flag:n.notarize,layoutOs:I.os,sign:W});announceSigning(W,q),W.kind===`sign`&&assertHostCanSign(W.signer);for(let n of warnOnToolSkew(F))ve.warn(`${sB} ${n}`);let{mtime:Y,warnings:X}=resolveStageMtime(F);for(let n of X)ve.warn(`${sB} ${n}`);if(ve.log(`${sB} packing ${F.settings.binaryName} ${F.settings.version}-${F.settings.release} for ${formatTarget(F.target)} from ${Ms(C,N)||`.`}/`),n.verbose){for(let n of F.staged)ve.log(`${sB} ${n.path}`);ve.log(`${sB} gi namespaces: ${F.namespaces.join(`, `)||`(none)`}`)}let Z=n.out===void 0?Ps(N):Os(C,n.out),te=[];for(let S of H){if(assertFormatCanRunInterpreter(S,F.settings.app),S.depends!==null){let n=F.settings.app===`node`?warnAboutNodeFloor(S.depends,F.settings.minNodeVersion):warnAboutGjsFloor(S.depends,F.settings.minGjsVersion);for(let S of n)ve.warn(`${sB} ${S}`)}te.push(await packOne({format:S,settings:F.settings,arch:F.target.arch,staged:F.staged,overlay:overlayFiles(F,S.id),stageDir:N,outRoot:Z,namespaces:F.namespaces,mtime:Y,sign:W,notarize:q,verbose:n.verbose}))}printArtifacts(C,te)}async function packOne(n){let{format:S,settings:C,stageDir:N,outRoot:F,mtime:I}=n;assertOverlayIsLicensed(S.id,C.binaryName,n.overlay);let H=js(F,`overlay`,S.id);writeStage(H,n.overlay);let W=readStage([N,H],[...n.staged,...n.overlay]),q=readPayloadFacts(W),Y=S.depends===null?[]:deriveDepends(S.depends,{namespaces:n.namespaces,hasIcons:q.hasIcons,hasSchemas:q.hasSchemas,interpreter:C.app,extra:C.extraDepends[S.depends],typelibPackages:C.typelibPackages,bundledTypelibs:q.bundledTypelibs,minGjsVersion:C.minGjsVersion,minNodeVersion:C.minNodeVersion});assertPayloadMatchesArch(W,n.arch);let X=layoutForOs(S.layoutOs);assertLauncherMatchesInterpreter(W,X,C,C.app),assertLayoutSupportsArch(X,n.arch);let Z=n.sign.kind===`sign`?await signPayload({payload:W,identity:n.sign.identity,signer:n.sign.signer,workDir:js(F,`signed`,S.id),bundleRoot:X.root(C),entitlementsPath:js(F,`signed`,`${S.id}.entitlements.plist`),verbose:n.verbose,log:n=>ve.log(`${sB} ${n}`)}):W,te=S.archName(n.arch,isArchIndependent(Z)),ne={settings:C,payload:Z,prefix:S.prefix,depends:Y,archLabel:te,mtime:I},re=js(F,`out`);mkdirSync(re,{recursive:!0});let ie=js(re,S.fileName(C,te));switch(S.id){case`deb`:writeFileSync(ie,await buildDeb(ne));break;case`rpm`:writeFileSync(ie,await buildRpm(ne));break;case`flatpak`:await buildFlatpakBundle({settings:C,stageDir:N,overlayDir:H,stageManifestFile:Lz,workDir:js(F,`flatpak`),target:ie,archLabel:te,verbose:n.verbose});break;case`macos-app`:case`windows-dir`:writePayload(ie,Z,X.root(C));break;case`macos-app-dmg`:{let S=dmgVolumeDir(F);writePayload(S,Z,``),await buildDmgImage({volumeName:dmgVolumeName(C),sourceDir:S,target:ie,workDir:Ps(S),verbose:n.verbose});break}case`macos-app-zip`:writeFileSync(ie,buildZip(zipEntriesFromPayload(Z),I));break;case`windows-dir-zip`:writeFileSync(ie,buildZip(zipEntriesFromPayload(Z,windowsProgramDirName(C)),I));break;case`msi`:{let S=js(F,`msi`);writePayload(js(S,bz),Z,X.root(C)),await buildMsi({settings:C,files:Z.map(n=>({path:n.path,source:`${bz}/${n.path}`})),programDirName:windowsProgramDirName(C),archLabel:te,workDir:S,target:ie,verbose:n.verbose});break}default:{let n=S.id;throw Error(`gjsify ship: no packer is wired for format "${String(n)}".`)}}let ae=S.artifactKind===`directory`?directorySize(ie):statSync(ie).size;return n.notarize.kind===`notarize`&&(S.artifactKind===`directory`?ve.warn(`${sB} ${S.id} is a directory, and notarytool submits an archive or an installer — not notarised. The container format beside it is what carries the ticket.`):(await notarizeArtifact({plan:n.notarize,artifact:ie,verbose:n.verbose,log:n=>ve.log(`${sB} ${n}`)}),canCarryTicket(S.id)?await stapleArtifact({notary:n.notarize.notary,artifact:ie,verbose:n.verbose,log:n=>ve.log(`${sB} ${n}`)}):ve.warn(`${sB} ${S.id} is notarised and NOT stapled: \`stapler\` takes a UDIF image, a signed flat package or a code-signed bundle, and an archive is none of them. Apple's remedy is to staple each item that went INTO the archive and re-create it — for this artifact that is the \`.app\`, which \`--target macos-app\` writes beside it.`))),{format:S.id,path:ie,size:ae}}function printArtifacts(n,S){for(let C of S)ve.log(`${sB} ${C.format}: ${Ms(n,C.path)} (${C.size} bytes)`)}function assertCanPack(n){assertHostCanFinish(n),assertToolsInstalled(n)}function assertPackable(n,S,C,N=[]){if(n.length>0)return;if(N.length>0)throw Error(`gjsify ship: ${N.map(n=>n.id).join(` and `)} wrap the ${S.name} layout, and neither can run this project — ${N[0]?.interpreterGap??``}.\n Set \`gjsify.ship.app.${S.os}\` to "${N[0]?.interpreters.join(`" / "`)}" — it overrides \`gjsify.app\` for THIS target and\n leaves every other one alone, which is what lets one project be GJS on Linux and Node here.
|
|
1110
1113
|
\`gjsify ship ${S.name} --stage\` assembles the tree either way.`);let F=formatIdsFor(S.os).sort();if(F.length>0){let n=C===`stage`?`${S.name} --stage --target`:`${S.name} --target`;throw Error(`gjsify ship: this run records no formats for the ${S.name} layout, so there is nothing to pack — and it is not that none exist: ${F.join(`, `)} wrap it.\n An empty list means none were SELECTED. \`gjsify.ship.targets\` is filtered to the layout being assembled,
|
|
1111
1114
|
so a configured list naming only another OS's formats leaves this one empty and says so at stage time.
|
|
1112
|
-
Name one where the payload is assembled: \`gjsify ship ${n} ${F[0]}\`.`)}let I=defaultFormatIds(`linux`).join(`,`),H={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${S.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${I} from right here.`,positional:`\`gjsify ship ${S.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${S.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[C];throw Error(`gjsify ship: no format wraps the ${S.name} layout, so there is nothing to pack. ${H} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(n,S){if(!n.interpreters.includes(S))throw Error(`gjsify ship: this ${n.layoutOs} target runs \`${S}\`, and the ${n.id} runtime cannot run it — it provides ${n.interpreters.join(`, `)}.\n ${n.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${n.layoutOs}: "${n.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(n){if(typeof readPackageJson$2(js(n,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ve.log(`${
|
|
1113
|
-
`);let F=S.verbose?C.entries:C.entries.slice(0,
|
|
1114
|
-
`)}function automaticPruneRefusal(n,S){return Object.keys(readPlatformOverrides(n)).length>0?`the platform target was overridden on the command line`:S?`--immutable`:null}function pruneAfterInstall(n,S,C={}){try{if(automaticPruneRefusal(C.env??process.env,C.immutable??!1))return;let N=planPrune({prefix:n,target:S});if(N.entries.length===0)return;let F=executePrune(N);if(F.removed.length===0)return;let I=C.hint?` (${C.hint} to review)`:``;ve.log(`gjsify: pruned ${F.removed.length} package(s) this host cannot use, freeing ${humanBytes(F.bytes)}${I}`)}catch(n){process.env.GJSIFY_DEBUG&&ve.error(`gjsify: prune skipped — ${n.message}`)}}var
|
|
1115
|
-
`)}catch{}}async function workspaceInstall(n,S,C){let N=await acquireInstallLock(n,{signal:C});try{await workspaceInstallLocked(n,S,C)}finally{N.release()}}async function workspaceInstallLocked(n,S,C){let N=discoverWorkspaces(n,{includeRoot:!0});if(N.length===0)throw Error(`gjsify install: ${n} has a "workspaces" field but no workspaces were discovered`);let F=new Map(N.map(n=>[n.name,n])),I=new Set,H=new Map,W=[];for(let n of N){let S=n.manifest;for(let C of[`dependencies`,`devDependencies`,`optionalDependencies`]){let N=S[C];if(N)for(let[S,C]of Object.entries(N)){if(typeof C!=`string`)continue;let N=F.get(S);if(N&&!/^(link|file|portal|git\+|https?):/.test(C)){W.push({fromWorkspaceName:n.name,depName:S,targetLocation:N.location});continue}if(C.startsWith(`workspace:`))throw Error(`gjsify install: ${n.name} declares "${S}: ${C}" but no workspace with that name exists`);if(/^(link|file|portal|git\+|https?):/.test(C))continue;let q=`${S}@${C}`;I.add(q);let Y=H.get(q);Y||(Y=new Set,H.set(q,Y)),Y.add(n.name)}}}ve.log(`gjsify install: ${N.length} workspace(s), ${I.size} external dep spec(s), ${W.length} workspace symlink(s)`),writeWorkspaceBinShims(n,N);let wireWorkspaceSymlinks=async()=>{if(W.length>0){let n=await Promise.resolve().then(()=>(Cl(),bl)),S=new Set,C=[];for(let n of W){let N=F.get(n.fromWorkspaceName);if(!N)continue;let I=js(N.location,`node_modules`,n.depName);S.add(Ps(I));let H=workspaceLinkTarget(I,n.targetLocation);C.push({linkPath:I,relTarget:H})}await Promise.all([...S].map(S=>n.mkdir(S,{recursive:!0})));let N=0,I=[],wireOne=async(S,C)=>{try{await n.rm(S,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}await n.symlink(C,S,
|
|
1116
|
-
`+(n?C:S)}if(H)return`#!/bin/sh\nexec node "${H}" "$@"\n`;if(W)return`#!/bin/sh\n${q}exec gjs -m "${W}" "$@"\n`;throw Error(`buildBinShim: either nodeTarget or gjsTarget must be provided`)}function buildWorkspaceBinShimsForWindows(n,S,C,N=[]){let F=S?js(n,S):null,I=C?js(n,C):null;if(F)return buildLauncherShims({interpreter:`node`,target:F});if(I){let n=N.join(`;`);return buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:I,prependEnv:N.length===0?{}:{GI_TYPELIB_PATH:n,PATH:n}})}throw Error(`buildWorkspaceBinShimsForWindows: either nodeTarget or gjsTarget must be provided`)}function mergeWorkspaceBins(n,S,C){let N=new Map,F=n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n,get=n=>{let S=N.get(n);return S||(S={},N.set(n,S)),S};if(typeof C==`string`)get(F).nodeTarget=C;else if(C&&typeof C==`object`)for(let[n,S]of Object.entries(C))typeof S==`string`&&S.length>0&&(get(n).nodeTarget=S);if(typeof S==`string`)get(F).gjsTarget=S;else if(S&&typeof S==`object`)for(let[n,C]of Object.entries(S))typeof C==`string`&&C.length>0&&(get(n).gjsTarget=C);return N}async function projectInstallViaNpm(n){let S=[`install`];n[`save-dev`]&&S.push(`--save-dev`),n[`save-peer`]&&S.push(`--save-peer`),n[`save-optional`]&&S.push(`--save-optional`),n.verbose&&S.push(`--loglevel`,`verbose`),n.packages&&n.packages.length>0&&S.push(...n.packages),await spawnNpm(S)}async function spawnNpm(n){return spawnToCompletion(`npm`,n,{completion:`return`,notFound:()=>Error(`npm not found on PATH — install Node.js first.`)}).then(({code:n})=>{if(n!==0)throw Error(`npm install exited with code ${n}`)}).catch(n=>{let S=n.code;ve.error(S===void 0?n.message:`npm install failed: ${n.message}`),process.exit(1)})}async function installGlobalAndLink(n,S){let C=defaultGlobalLayout();mkdirSync(C.prefix,{recursive:!0}),ve.log(`gjsify install --global → ${C.prefix}`),ve.log(` bins → ${C.binDir}`);let N=await acquireInstallLock(C.prefix,{});try{let N=await installPackages({prefix:C.prefix,specs:n,verbose:S.verbose}),F=n.map(specToPackageName);if(F.includes(`@gjsify/cli`)){let n=N.installed.find(n=>n.name===`@gjsify/cli`)?.version??`latest`;await installGjsEnginePackages(C.prefix,n,{verbose:S.verbose})}S.prune!==!1&&pruneAfterInstall(C.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`}),reportLinkedBins(linkGlobalBins(F,C),C.binDir)}finally{N.release()}}function pruneProjectPrefix(n){n.prune!==!1&&pruneAfterInstall(process.cwd(),resolveHostPlatform({env:{}}),{immutable:n.immutable===!0,hint:`gjsify prune --dry-run`})}function reportLinkedBins(n,S){if(n.length===0)ve.warn("\nNo bins declared (neither `gjsify.bin` nor `bin` in package.json) — nothing was symlinked.");else{ve.log(`\nLinked ${n.length} bin(s):`);for(let S of n)ve.log(` • ${S.link} → ${S.target}`)}n.length>0&&!binDirOnPath(S)&&ve.warn(`\nNote: ${S} is not on your PATH.\nAdd it to your shell rc file:\n export PATH="${S}:$PATH"`)}async function ensureProjectGjsEngine(n,S,C={}){let N=C.cwd??process.cwd(),F=C.hasEngineFn??hasBundlerEngineInstalled;if(!existsSync(js(N,`node_modules`,`@gjsify`,`cli`,`package.json`))||!S||F(N))return;if(n.immutable){ve.warn(`\nWarning: \`gjsify build\` will fail under GJS — ${
|
|
1117
|
-
gjsify install ${
|
|
1115
|
+
Name one where the payload is assembled: \`gjsify ship ${n} ${F[0]}\`.`)}let I=defaultFormatIds(`linux`).join(`,`),H={host:`This host is ${process.platform}, so \`gjsify ship\` assembled the ${S.name} layout. Assembly is not host-bound (ADR 0024 § A1), so the Linux packages are still one word away: \`gjsify ship linux\` builds ${I} from right here.`,positional:`\`gjsify ship ${S.name} --stage\` assembles the payload and stops, which is the whole of what this command does for that OS today.`,stage:`This stage carries the ${S.name} layout and nothing here can wrap it — a stage is a build intermediate, not an artifact. Keep it for the milestone that packs it, or re-assemble with \`gjsify ship linux --stage\` if a Linux package is what you wanted.`}[C];throw Error(`gjsify ship: no format wraps the ${S.name} layout, so there is nothing to pack. ${H} Every layout this gjsify knows has one (ADR 0024 stages 2-5), so this is a layout added without a \`FORMATS\` row.`)}function assertFormatCanRunInterpreter(n,S){if(!n.interpreters.includes(S))throw Error(`gjsify ship: this ${n.layoutOs} target runs \`${S}\`, and the ${n.id} runtime cannot run it — it provides ${n.interpreters.join(`, `)}.\n ${n.interpreterGap}.\n Build the formats that wrap this layout and can run it, or set \`gjsify.ship.app.${n.layoutOs}: "${n.interpreters.join(`" / "`)}"\` (which overrides \`gjsify.app\` for this target alone).`)}async function runProjectBuild(n){if(typeof readPackageJson$2(js(n,`package.json`))?.scripts?.build!=`string`)throw Error("gjsify ship: this project has no `build` script to run. Add one, or pass --skip-build to package what is already built.");ve.log(`${sB} running the project's build script`);let S=await spawnToCompletion(`gjsify`,[`run`,`build`],{completion:`return`,cwd:n,stdio:`inherit`,notFound:()=>Error("gjsify ship: `gjsify` is not on PATH, so the project build cannot be run. Build the project yourself and pass --skip-build.")});if(S.code!==0)throw Error(`gjsify ship: the project's build script failed with ${describeExit(S)}.`)}var sB,cB,lB=__esmMin(()=>{ye(),Vl(),Hs(),nP(),qI(),KM(),_P(),ER(),NL(),QR(),VR(),tz(),nz(),rz(),_z(),uR(),UR(),IL(),hR(),xz(),kz(),Mz(),Fz(),TR(),JR(),Hz(),Uz(),oB(),LR(),Rz(),zz(),sB=`[gjsify ship]`,cB={command:`ship [os]`,description:`Build installable artifacts (${hz.join(`, `)}) from the current project.`,builder:n=>n.positional(`os`,{type:`string`,description:`Operating system whose LAYOUT to assemble (${cR.join(`|`)}, ADR 0024 § A2). Default: this host. Assembly is not host-bound, so any of them can be staged anywhere.`}).option(`target`,{type:`string`,array:!0,description:`Formats to build, comma-separated or repeated. Default: every format wrapping the target OS's layout that needs no extra tooling — on linux, ${defaultFormatIds(`linux`).join(`,`)}. Also available for linux, and opt-in because it needs tooling this CLI does not carry: ${formatIdsFor(`linux`).filter(n=>!defaultFormatIds(`linux`).includes(n)).join(`, `)}.`}).option(`out`,{type:`string`,normalize:!0,description:"Output root, relative to the project. Default: `gjsify.ship.outDir`, else `ship`."}).option(`stage`,{type:`boolean`,default:!1,description:`Produce the staged payload and stop, without packing anything.`}).option(`from-stage`,{type:`string`,normalize:!0,description:"Pack a staged payload written by an earlier `--stage` run. Needs no project: the stage carries its own closure."}).option(`expect-target`,{type:`string`,description:"With --from-stage: refuse unless the stage was assembled for this `<os>-<arch>`, e.g. `linux-arm64`."}).option(`skip-build`,{type:`boolean`,default:!1,description:"Package what is already built instead of running the project's `build` script."}).option(`arch`,{type:`string`,description:"Target architecture in `process.arch` spelling. Default: this host."}).option(`sign`,{type:`string`,requiresArg:!0,description:"Sign the payload with this identity, e.g. a Developer ID name or SHA-1 fingerprint. `-` signs ad-hoc and needs no developer identity. Default: `gjsify.ship.sign.<darwin|win32>.identity`; absent means unsigned, which is a legitimate output."}).option(`notarize`,{type:`string`,requiresArg:!0,description:"Submit the signed artifact to Apple with this `notarytool` keychain profile. Needs --sign; darwin only."}).option(`verbose`,{type:`boolean`,default:!1,description:`Print each staged file, the GI namespaces the bundle imports, and every tool a host-bound packer invokes.`}),handler:async n=>{if(n[`from-stage`]!==void 0)return await finishFromStage(n,n[`from-stage`]);await assemble(n)}}});function forceExit(n){if(process.exitCode=n,!gjsExit(n))return process.exit(n)}var uB=__esmMin(()=>{th()});function isReservedEntry(n){return n.startsWith(`.`)}function readManifest(n){try{let S=JSON.parse(readFileSync(js(n,`package.json`),`utf8`)),C={os:S.os,cpu:S.cpu,libc:S.libc};return{name:typeof S.name==`string`?S.name:void 0,version:typeof S.version==`string`?S.version:void 0,platform:declaresPlatform(C)?C:void 0}}catch{return null}}function collect(n,S){let C;try{C=readdirSync(n,{withFileTypes:!0})}catch{return}for(let N of C){if(isReservedEntry(N.name))continue;let C=js(n,N.name);if(N.name.startsWith(`@`)){let n;try{n=readdirSync(C,{withFileTypes:!0})}catch{continue}for(let N of n)isReservedEntry(N.name)||addPackage(js(C,N.name),S);continue}addPackage(C,S)}}function addPackage(n,S){let C=!1;try{C=lstatSync(n).isSymbolicLink()}catch{return}let N=readManifest(n);S.push({name:N?.name??n,version:N?.version??`0.0.0`,dir:n,linked:C,platform:N?.platform}),C||collect(js(n,`node_modules`),S)}function scanPrefix(n){let S=[];return collect(js(n,`node_modules`),S),S}function planPlatformPrune(n,S){let C=[];for(let N of n){if(N.linked||!N.platform)continue;let n=checkPlatform(N.platform,S);n.ok||C.push({pkg:N,bytes:0,verdict:n})}return C}function dirBytes(n){let S=0,C=[n];for(;C.length>0;){let n=C.pop(),N;try{N=readdirSync(n,{withFileTypes:!0})}catch{continue}for(let F of N){let N=js(n,F.name);if(F.isDirectory())C.push(N);else if(F.isFile())try{S+=statSync(N).size}catch{}}}return S}function planPrune(n){let S=scanPrefix(n.prefix),C=planPlatformPrune(S,n.target);for(let n of C)n.bytes=dirBytes(n.pkg.dir);return{prefix:n.prefix,target:n.target,scanned:S.length,entries:C,bytes:C.reduce((n,S)=>n+S.bytes,0)}}function executePrune(n,S={}){let C=[],N=[],F=[],I=S.remove??(n=>rmSync(n,{recursive:!0,force:!0,maxRetries:10}));if(!S.dryRun){for(let S of n.entries)try{I(S.pkg.dir),C.push(S)}catch(n){N.push({entry:S,error:n.message})}F.push(...pruneDeadBinLinks(n.prefix))}return{plan:n,removed:C,failed:N,bytes:C.reduce((n,S)=>n+S.bytes,0),binLinks:F}}function pruneDeadBinLinks(n){let S=js(n,`node_modules`,`.bin`),C=[],N;try{N=readdirSync(S,{withFileTypes:!0})}catch{return C}for(let n of N){let N=js(S,n.name);try{if(!lstatSync(N).isSymbolicLink()||existsSync(N))continue;unlinkSync(N),C.push(n.name)}catch{}}return C}function humanBytes(n){if(n<1024)return`${n} B`;let S=[`KB`,`MB`,`GB`],C=n/1024,N=0;for(;C>=1024&&N<S.length-1;)C/=1024,N+=1;return`${C.toFixed(1)} ${S[N]}`}function formatPruneReport(n,S){let{plan:C}=n,N=[`${C.prefix} · target ${describePlatformTarget(C.target)} · scanned ${C.scanned} package(s)`];if(C.entries.length===0)return N.push(`nothing to prune — no installed package declares a platform this target cannot use.`),N.join(`
|
|
1116
|
+
`);let F=S.verbose?C.entries:C.entries.slice(0,dB);for(let n of F){let S=JSON.stringify(n.verdict.required);N.push(` ${n.pkg.name}@${n.pkg.version} ${humanBytes(n.bytes)} requires ${S}`)}F.length<C.entries.length&&N.push(` … and ${C.entries.length-F.length} more (--verbose to list them)`),N.push(S.dryRun?`would free ${humanBytes(C.bytes)} across ${C.entries.length} package(s) (apparent size)`:`freed ${humanBytes(n.bytes)} across ${n.removed.length} package(s) (apparent size)`),n.binLinks.length>0&&N.push(`removed ${n.binLinks.length} dangling .bin link(s): ${n.binLinks.join(`, `)}`);for(let S of n.failed)N.push(`FAILED ${S.entry.pkg.name}: ${S.error}`);return N.join(`
|
|
1117
|
+
`)}function automaticPruneRefusal(n,S){return Object.keys(readPlatformOverrides(n)).length>0?`the platform target was overridden on the command line`:S?`--immutable`:null}function pruneAfterInstall(n,S,C={}){try{if(automaticPruneRefusal(C.env??process.env,C.immutable??!1))return;let N=planPrune({prefix:n,target:S});if(N.entries.length===0)return;let F=executePrune(N);if(F.removed.length===0)return;let I=C.hint?` (${C.hint} to review)`:``;ve.log(`gjsify: pruned ${F.removed.length} package(s) this host cannot use, freeing ${humanBytes(F.bytes)}${I}`)}catch(n){process.env.GJSIFY_DEBUG&&ve.error(`gjsify: prune skipped — ${n.message}`)}}var dB,fB=__esmMin(()=>{ye(),Vl(),Hs(),uF(),dB=10});function workspaceLinkTarget(n,S){return pB===`junction`?Os(S):Ms(Ps(n),S)}function applyPlatformConfigFromFlags(n){for(let[S,C]of[[`os`,`npm_config_os`],[`cpu`,`npm_config_cpu`],[`libc`,`npm_config_libc`]]){let N=n[S];if(typeof N!=`string`)continue;let F=N.trim();F!==``&&(process.env[C]=F)}n.force&&(process.env.npm_config_force=`true`)}function isAbortedFromOverallTimeout(n){if(!n||typeof n!=`object`)return!1;let S=n.name;if(S===`AbortError`)return!0;let C=n.message;return!!(typeof C==`string`&&C.includes(`install-overall-timeout`)||S===`RegistryTimeoutError`)}function readCliVersionFrom(n){try{if(!existsSync(n))return null;let S=JSON.parse(readFileSync(n,`utf-8`));if(S.name===gB&&typeof S.version==`string`)return S.version}catch{}return null}function readRunningCliVersion(){try{let n=Ps(Os(fileURLToPath(import.meta.url)));for(let S=0;S<8&&n!==Ps(n);S++){let S=readCliVersionFrom(js(n,`package.json`));if(S)return S;n=Ps(n)}}catch{}return null}function readWorkspaceCliVersion(n){return readCliVersionFrom(js(n,`node_modules`,gB,`package.json`))??readCliVersionFrom(js(n,`packages`,`infra`,`cli`,`package.json`))}function warnOnCliVersionSkew(n){if(process.env.GJSIFY_NO_VERSION_SKEW_WARNING===`1`)return;let S=readRunningCliVersion(),C=readWorkspaceCliVersion(n);!S||!C||S===C||ve.warn(`gjsify install: version skew — you are running @gjsify/cli v${S}, but this workspace pins v${C}.\n A mismatched CLI can stall the install (lock discarded → full re-resolve) or silently produce a wrong build.\n Align them: run \`gjsify self-update\` (global CLI) or use the workspace-local \`node_modules/.bin/gjsify\`.\n Suppress this with GJSIFY_NO_VERSION_SKEW_WARNING=1.`)}function isWorkspaceRoot(n){let S=readPackageJson$1(js(n,`package.json`));return S?S.workspaces!==void 0:!1}function optionalDependencyNames(n){let S=new Set,C=new Set;for(let N of n){let n=new Set(Object.keys(N.optionalDependencies??{}));for(let C of n)S.add(C);for(let S of[`dependencies`,`devDependencies`])for(let F of Object.keys(N[S]??{}))n.has(F)||C.add(F)}for(let n of C)S.delete(n);return S}function depKindFromArgs(n){return n[`save-dev`]?`devDependencies`:n[`save-peer`]?`peerDependencies`:n[`save-optional`]?`optionalDependencies`:`dependencies`}async function projectInstallNative(n,S){let C=process.cwd(),N=js(C,`package.json`),F=[`.pnp.cjs`,`.pnp.loader.mjs`].filter(n=>existsSync(js(C,n)));if(F.length>0)throw Error(`gjsify install uses the node_modules linker and cannot run in a Yarn PnP project (found ${F.join(`, `)} in ${C}).\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){let N=isWorkspaceRoot(C)?C:findWorkspaceRoot(C);if(N){N!==C&&ve.log(`gjsify install: resolved workspace root ${N} (from ${C}); installing the workspace.`),await workspaceInstall(N,n,S);return}}let I,H=readPackageJson$1(N),W=H?projectSpecsFromPackageJson(H):[];if(n.packages&&n.packages.length>0){let S=new Set(n.packages.map(n=>parseSpec$2(n).name));I=[...W.filter(n=>!S.has(parseSpec$2(n).name)),...n.packages]}else{if(!H)throw Error(`gjsify install: no package.json in ${C}`);if(I=W,I.length===0){ve.log(`gjsify install: no dependencies declared in package.json — nothing to do.`);return}}mkdirSync(C,{recursive:!0});let q=makeProgressReporter({enabled:!n.verbose&&!n.quiet&&n.progress!==!1}),Y=await acquireInstallLock(C,{signal:S});try{let F=await installPackages({prefix:C,specs:I,verbose:n.verbose,lockfile:!n.immutable,frozen:n.immutable,refreshLockfile:n[`refresh-lockfile`],signal:S,progress:q,optionalSpecs:new Set([...optionalDependencyNames(H?[H]:[]),...n[`save-optional`]?(n.packages??[]).map(n=>parseSpec$2(n).name):[]])});if(n.packages&&n.packages.length>0&&H){let S=depKindFromArgs(n);for(let C of n.packages){let{name:n,range:N}=parseSpec$2(C),I=F.installed.find(S=>S.name===n);addDependencyEntry(H,n,N??(I?defaultRangeFromVersion(I.version):`latest`),S)}writePackageJson(N,H),n.immutable||syncLockfileRequested(C,projectSpecsFromPackageJson(H))}}finally{Y.release()}}function syncLockfileRequested(n,S){let C=js(n,`gjsify-lock.json`);if(existsSync(C))try{let n=JSON.parse(readFileSync(C,`utf-8`)),N=[...S].sort(),F=[...n.requested??[]].sort();if(N.length===F.length&&N.every((n,S)=>n===F[S]))return;n.requested=S,atomicWriteStrict(C,JSON.stringify(n,null,2)+`
|
|
1118
|
+
`)}catch{}}async function workspaceInstall(n,S,C){let N=await acquireInstallLock(n,{signal:C});try{await workspaceInstallLocked(n,S,C)}finally{N.release()}}async function workspaceInstallLocked(n,S,C){let N=discoverWorkspaces(n,{includeRoot:!0});if(N.length===0)throw Error(`gjsify install: ${n} has a "workspaces" field but no workspaces were discovered`);let F=new Map(N.map(n=>[n.name,n])),I=new Set,H=new Map,W=[];for(let n of N){let S=n.manifest;for(let C of[`dependencies`,`devDependencies`,`optionalDependencies`]){let N=S[C];if(N)for(let[S,C]of Object.entries(N)){if(typeof C!=`string`)continue;let N=F.get(S);if(N&&!/^(link|file|portal|git\+|https?):/.test(C)){W.push({fromWorkspaceName:n.name,depName:S,targetLocation:N.location});continue}if(C.startsWith(`workspace:`))throw Error(`gjsify install: ${n.name} declares "${S}: ${C}" but no workspace with that name exists`);if(/^(link|file|portal|git\+|https?):/.test(C))continue;let q=`${S}@${C}`;I.add(q);let Y=H.get(q);Y||(Y=new Set,H.set(q,Y)),Y.add(n.name)}}}ve.log(`gjsify install: ${N.length} workspace(s), ${I.size} external dep spec(s), ${W.length} workspace symlink(s)`),writeWorkspaceBinShims(n,N);let wireWorkspaceSymlinks=async()=>{if(W.length>0){let n=await Promise.resolve().then(()=>(Cl(),bl)),S=new Set,C=[];for(let n of W){let N=F.get(n.fromWorkspaceName);if(!N)continue;let I=js(N.location,`node_modules`,n.depName);S.add(Ps(I));let H=workspaceLinkTarget(I,n.targetLocation);C.push({linkPath:I,relTarget:H})}await Promise.all([...S].map(S=>n.mkdir(S,{recursive:!0})));let N=0,I=[],wireOne=async(S,C)=>{try{await n.rm(S,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}await n.symlink(C,S,pB)};for(let n=0;n<Math.min(32,C.length);n++)I.push((async()=>{for(;;){let n=N++;if(n>=C.length)return;let S=C[n];if(!S)return;await wireOne(S.linkPath,S.relTarget)}})());await Promise.all(I),ve.log(`gjsify install: wired ${W.length} workspace symlink(s)`)}let S=js(n,`node_modules`),C=0;for(let F of N){if(F.location===n||!F.name)continue;let N=js(S,F.name),I=!1;try{lstatSync(N),I=!0}catch{}I||(mkdirSync(Ps(N),{recursive:!0}),symlinkSync(workspaceLinkTarget(N,F.location),N,pB),C++)}C>0&&ve.log(`gjsify install: hoisted ${C} workspace(s) to root node_modules/`)};await wireWorkspaceSymlinks();let q=N.find(S=>S.location===n)?.manifest,Y=extractOverrides(q),X=Y?.global,Z=new Map,te=new Set;if(Y&&Y.scoped.size>0){for(let n of N){let S=n.manifest;for(let C of[`dependencies`,`devDependencies`,`optionalDependencies`]){let N=S[C];if(N)for(let[S,C]of Object.entries(N)){let N=scopedOverrideFor(n,S,Y);if(!N)continue;let F=N,I=n.location,H=Z.get(I);H||(H=new Set,Z.set(I,H)),H.add(`${S}@${F}`),te.add(`${S}@${C}`)}}}let n=new Set;for(let S of N)for(let C of[`dependencies`,`devDependencies`,`optionalDependencies`]){let N=S.manifest[C];if(N)for(let[C,F]of Object.entries(N))scopedOverrideFor(S,C,Y)||n.add(`${C}@${F}`)}for(let S of te)n.has(S)||I.delete(S);Z.size>0&&ve.log(`gjsify install: ${Z.size} workspace(s) have scoped overrides — they will install their overridden deps locally after the root install`)}if(I.size>0){let W=makeProgressReporter({enabled:!S.verbose&&!S.quiet&&S.progress!==!1});await installPackages({prefix:n,specs:[...I],verbose:S.verbose,lockfile:!S.immutable,frozen:S.immutable,refreshLockfile:S[`refresh-lockfile`],overrides:X,signal:C,progress:W,workspaceNames:new Set(F.keys()),specOrigins:new Map([...H].map(([n,S])=>[n,[...S]])),optionalSpecs:optionalDependencyNames(N.map(n=>n.manifest))})}else S.verbose&&ve.log(`gjsify install: no external deps to fetch`);for(let[n,I]of Z){if(I.size===0)continue;let H=N.find(S=>S.location===n)?.name??n;S.verbose&&ve.log(`gjsify install: ${H} — installing ${I.size} scoped-override spec(s) into ${n}/node_modules/`),await installPackages({prefix:n,specs:[...I],verbose:S.verbose,lockfile:!S.immutable,frozen:S.immutable,signal:C,workspaceNames:new Set(F.keys()),optionalSpecs:optionalDependencyNames(N.map(n=>n.manifest))})}await wireWorkspaceSymlinks();let ne=writeWorkspaceBinShims(n,N);ne>0&&ve.log(`gjsify install: linked ${ne} workspace bin(s) into node_modules/.bin/`)}function writeWorkspaceBinShims(n,S){let C=js(n,`node_modules`,`.bin`),N=detectNativePackages(n).map(n=>n.prebuildsDir),F=0;for(let I of S){let S=I.manifest,H=S.gjsify?.bin,W=S.bin,q=mergeWorkspaceBins(I.name,H,W);if(q.size!==0){mkdirSync(C,{recursive:!0});for(let[S,{nodeTarget:H,gjsTarget:W}]of q){let q=js(C,S);for(let n of[q,`${q}.cmd`,`${q}.ps1`])try{rmSync(n,{force:!0,maxRetries:10,retryDelay:100})}catch{}if(writeFileSync(q,buildBinShim(I.location,H,W,N,process.platform,n),{mode:493}),chmodSync(q,493),process.platform===`win32`)for(let[n,S]of Object.entries(buildWorkspaceBinShimsForWindows(I.location,H,W,N)))writeFileSync(`${q}.${n}`,S,{mode:493});F++}}}return F}function extractOverrides(n){if(!n)return;let S={},C=new Map,merge=(n,N)=>{if(n){for(let[F,I]of Object.entries(n))if(!F.startsWith(`_`)){if(typeof I==`string`){let n=F,C=F.startsWith(`@`)?F.indexOf(`@`,1):F.indexOf(`@`);C>0&&(n=F.slice(0,C)),S[n]=I;continue}if(I&&typeof I==`object`&&!Array.isArray(I)){let n={};for(let[S,C]of Object.entries(I)){if(S.startsWith(`_`))continue;if(typeof C!=`string`){ve.warn(`gjsify install: ${N}["${F}"]["${S}"] is not a string — only one level of nesting is supported, skipping`);continue}let I=S,H=S.startsWith(`@`)?S.indexOf(`@`,1):S.indexOf(`@`);H>0&&(I=S.slice(0,H)),n[I]=C}if(Object.keys(n).length>0){let S=C.get(F)??{};C.set(F,{...S,...n})}continue}ve.warn(`gjsify install: ${N}["${F}"] is not a string or object — skipping`)}}};if(merge(n.overrides,`overrides`),merge(n.resolutions,`resolutions`),!(Object.keys(S).length===0&&C.size===0))return{global:S,scoped:C}}function scopedOverrideFor(n,S,C){if(!C||C.scoped.size===0)return;let N=[n.name,n.relativeLocation];for(let n of N){let N=C.scoped.get(n);if(N?.[S])return N[S]}}function buildBinShim(n,S,C,N=[],F=process.platform,I=n){let H=S?js(n,S):null,W=C?js(n,C):null,q=buildNativeEnvPreamble(I,N,{platform:F});if(H&&W){let n=F===`darwin`||F===`win32`,S=`if command -v gjs >/dev/null 2>&1 && [ -f "${W}" ]; then\n${q}exec gjs -m "${W}" "$@"\nfi\nexec node "${H}" "$@"\n`,C=`if command -v node >/dev/null 2>&1 && [ -f "${H}" ]; then\nexec node "${H}" "$@"\nfi\n${q}exec gjs -m "${W}" "$@"\n`;return`#!/bin/sh
|
|
1119
|
+
`+(n?C:S)}if(H)return`#!/bin/sh\nexec node "${H}" "$@"\n`;if(W)return`#!/bin/sh\n${q}exec gjs -m "${W}" "$@"\n`;throw Error(`buildBinShim: either nodeTarget or gjsTarget must be provided`)}function buildWorkspaceBinShimsForWindows(n,S,C,N=[]){let F=S?js(n,S):null,I=C?js(n,C):null;if(F)return buildLauncherShims({interpreter:`node`,target:F});if(I){let n=N.join(`;`);return buildLauncherShims({interpreter:`gjs`,interpreterArgs:[`-m`],target:I,prependEnv:N.length===0?{}:{GI_TYPELIB_PATH:n,PATH:n}})}throw Error(`buildWorkspaceBinShimsForWindows: either nodeTarget or gjsTarget must be provided`)}function mergeWorkspaceBins(n,S,C){let N=new Map,F=n.startsWith(`@`)?n.slice(n.indexOf(`/`)+1):n,get=n=>{let S=N.get(n);return S||(S={},N.set(n,S)),S};if(typeof C==`string`)get(F).nodeTarget=C;else if(C&&typeof C==`object`)for(let[n,S]of Object.entries(C))typeof S==`string`&&S.length>0&&(get(n).nodeTarget=S);if(typeof S==`string`)get(F).gjsTarget=S;else if(S&&typeof S==`object`)for(let[n,C]of Object.entries(S))typeof C==`string`&&C.length>0&&(get(n).gjsTarget=C);return N}async function projectInstallViaNpm(n){let S=[`install`];n[`save-dev`]&&S.push(`--save-dev`),n[`save-peer`]&&S.push(`--save-peer`),n[`save-optional`]&&S.push(`--save-optional`),n.verbose&&S.push(`--loglevel`,`verbose`),n.packages&&n.packages.length>0&&S.push(...n.packages),await spawnNpm(S)}async function spawnNpm(n){return spawnToCompletion(`npm`,n,{completion:`return`,notFound:()=>Error(`npm not found on PATH — install Node.js first.`)}).then(({code:n})=>{if(n!==0)throw Error(`npm install exited with code ${n}`)}).catch(n=>{let S=n.code;ve.error(S===void 0?n.message:`npm install failed: ${n.message}`),process.exit(1)})}async function installGlobalAndLink(n,S){let C=defaultGlobalLayout();mkdirSync(C.prefix,{recursive:!0}),ve.log(`gjsify install --global → ${C.prefix}`),ve.log(` bins → ${C.binDir}`);let N=await acquireInstallLock(C.prefix,{});try{let N=await installPackages({prefix:C.prefix,specs:n,verbose:S.verbose}),F=n.map(specToPackageName);if(F.includes(`@gjsify/cli`)){let n=N.installed.find(n=>n.name===`@gjsify/cli`)?.version??`latest`;await installGjsEnginePackages(C.prefix,n,{verbose:S.verbose})}S.prune!==!1&&pruneAfterInstall(C.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`}),reportLinkedBins(linkGlobalBins(F,C),C.binDir)}finally{N.release()}}function pruneProjectPrefix(n){n.prune!==!1&&pruneAfterInstall(process.cwd(),resolveHostPlatform({env:{}}),{immutable:n.immutable===!0,hint:`gjsify prune --dry-run`})}function reportLinkedBins(n,S){if(n.length===0)ve.warn("\nNo bins declared (neither `gjsify.bin` nor `bin` in package.json) — nothing was symlinked.");else{ve.log(`\nLinked ${n.length} bin(s):`);for(let S of n)ve.log(` • ${S.link} → ${S.target}`)}n.length>0&&!binDirOnPath(S)&&ve.warn(`\nNote: ${S} is not on your PATH.\nAdd it to your shell rc file:\n export PATH="${S}:$PATH"`)}async function ensureProjectGjsEngine(n,S,C={}){let N=C.cwd??process.cwd(),F=C.hasEngineFn??hasBundlerEngineInstalled;if(!existsSync(js(N,`node_modules`,`@gjsify`,`cli`,`package.json`))||!S||F(N))return;if(n.immutable){ve.warn(`\nWarning: \`gjsify build\` will fail under GJS — ${SF} is not installed, and\n --immutable cannot add it (the lockfile does not name it). Declare it so the lockfile carries it:
|
|
1120
|
+
gjsify install ${SF}\n Under Node the npm \`rolldown\` engine is used instead and this does not apply.`);return}let I=readCliVersionFrom(js(N,`node_modules`,`@gjsify`,`cli`,`package.json`))??`latest`;ve.log(`\n${SF} is missing and this host can run gjs, so \`gjsify build\` would have no\n bundler engine (there is no npm \`rolldown\` fallback under GJS). Installing the GJS engine set at\n ${I}, in lockstep with the CLI.`),await(C.installFn??installGjsEnginePackages)(N,I,{verbose:n.verbose})}async function runPostInstallChecks(n){ve.log(`
|
|
1118
1121
|
--- gjsify post-install checks ---`);let S=runMinimalChecks(),C=S.filter(n=>!n.found&&n.severity===`required`);if(C.length>0){ve.warn(`Missing required system dependencies:
|
|
1119
|
-
`);for(let n of C)ve.warn(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),C);n&&ve.warn(`\nInstall with:\n ${n}`)}else ve.log(`System dependencies OK.`);await ensureProjectGjsEngine(n,S.find(n=>n.id===`gjs`)?.found??!1);let N=detectNativePackages(process.cwd());if(N.length>0){ve.log(`\nDetected ${N.length} @gjsify/* package(s) with native prebuilds:`);for(let n of N)ve.log(` • ${n.name}`);ve.log("\nUse `gjsify run <bundle>` to launch with LD_LIBRARY_PATH/GI_TYPELIB_PATH set.")}maybeInstallGitHooks()}function maybeInstallGitHooks(){let n=process.cwd(),S=js(n,`scripts`,`install-git-hooks.mjs`);if(existsSync(S)&&existsSync(js(n,`.git`)))try{let C=spawnSync(nodeBinary(),[S,`--quiet`],{cwd:n,stdio:`inherit`,env:process.env});C.status!==0&&ve.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${C.status} — git hooks may not be active.`)}catch(n){ve.warn(`[gjsify install] git hook installation skipped: ${n instanceof Error?n.message:String(n)}`)}}var nB,rB,iB,aB,oB=__esmMin(()=>{ye(),Vl(),Hs(),gn(),Dh(),$z(),GM(),dN(),gN(),AP(),yF(),WP(),$P(),xP(),_P(),qM(),CF(),lF(),tB(),wP(),nB=process.platform===`win32`?`junction`:void 0,rB=18e5,iB={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:rB}).option(`os`,{description:"Resolve/install for this OS instead of the running one (npm config key `os`, e.g. darwin, win32, linux). Affects which packages pass the os/cpu/libc compatibility check; the lockfile stays platform-independent either way.",type:`string`}).option(`cpu`,{description:"Resolve/install for this CPU architecture instead of the running one (npm config key `cpu`, e.g. x64, arm64).",type:`string`}).option(`libc`,{description:"Resolve/install for this libc family instead of probing the host (npm config key `libc`: glibc or musl). Only meaningful with --os=linux. A package declaring a libc is incompatible when the target libc is unknown.",type:`string`}).option(`force`,{description:"Install a REQUIRED dependency even when its os/cpu/libc excludes the target, instead of failing with EBADPLATFORM (npm config key `force`). Incompatible OPTIONAL dependencies stay skipped — npm ignores --force for those too, and a binary that cannot load is not worth downloading.",type:`boolean`,default:!1}).option(`prune`,{description:`After installing, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable. Skipped automatically under --immutable, and whenever --os/--cpu/--libc is given: an install must never delete against a target the user typed.`,type:`boolean`,default:!0}),handler:async n=>{if(applyPlatformConfigFromFlags(n),n.immutable){if(n.packages&&n.packages.length>0)return ve.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(n.global)return ve.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(n[`refresh-lockfile`])return ve.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1)}if(n.global){if(!n.packages||n.packages.length===0)return ve.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let S of[`save-dev`,`save-peer`,`save-optional`])n[S]&&ve.warn(`gjsify install --global ignores --${S}: global installs do not modify a project package.json.`);await installGlobalAndLink(n.packages,{verbose:n.verbose,prune:n.prune});return}if(warnOnCliVersionSkew(process.cwd()),(n.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(n),pruneProjectPrefix(n),await runPostInstallChecks(n);return}let S=n.timeout>0?n.timeout:0,C=S>0?new AbortController:null,N=C===null?null:setTimeout(()=>C.abort(Error(`install-overall-timeout`)),S),F=S>0?setTimeout(()=>{let n=Math.round(S/100)/10;ve.error(`gjsify install: the ${n}s budget elapsed and the abort did not unwind within 10s — forcing exit. That means one of two things, and this timer cannot distinguish them: the install was still WORKING (a cold tree here extracts several GB, and extraction blocks the loop in multi-second synchronous stretches), or a step genuinely wedged. Re-running tells you which, and is safe: extraction is idempotent, every package already on disk is skipped, so a second run finishes the remainder in a fraction of the time. A re-run that makes NO further progress is a real wedge — file an issue.`),forceExit(1)},S+1e4):null;F?.unref?.();try{await projectInstallNative(n,C?.signal),pruneProjectPrefix(n),await runPostInstallChecks(n)}catch(n){if(C!==null&&C.signal.aborted&&isAbortedFromOverallTimeout(n)){let n=Math.round(S/100)/10;return ve.error(`gjsify install: timed out after ${n}s — likely a registry slowdown or a wedged extract.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw n}finally{N!==null&&clearTimeout(N),F!==null&&clearTimeout(F)}}},aB=`@gjsify/cli`});function readDirectChildren(n){let S;try{S=readdirSync(`/proc/${n}/task`)}catch{return null}let C=[],N=!1;for(let F of S)try{let S=readFileSync(`/proc/${n}/task/${F}/children`,`utf-8`);N=!0;for(let n of S.trim().split(/\s+/)){let S=Number(n);Number.isInteger(S)&&S>0&&C.push(S)}}catch{}return N?C:null}function buildPpidMap(){let n=new Map,S=[];try{S=`1.16093.16099.16106.16107.16114.24930.24941.acpi.bootconfig.buddyinfo.bus.cgroups.cmdline.consoles.cpuinfo.crypto.devices.diskstats.dma.driver.dynamic_debug.execdomains.fb.filesystems.fs.interrupts.iomem.ioports.irq.kallsyms.kcore.key-users.keys.kmsg.kpagecgroup.kpagecount.kpageflags.latency_stats.loadavg.locks.mdstat.meminfo.misc.modules.mounts.mtrr.net.pagetypeinfo.partitions.pressure.schedstat.scsi.self.slabinfo.softirqs.stat.swaps.sys.sysrq-trigger.sysvipc.thread-self.timer_list.tty.uptime.version.version_signature.vmallocinfo.vmstat.zoneinfo`.split(`.`)}catch{return n}for(let C of S){let S=Number(C);if(!(!Number.isInteger(S)||S<=0))try{let C=readFileSync(`/proc/${S}/stat`,`utf-8`),N=C.slice(C.lastIndexOf(`)`)+2).split(` `),F=Number(N[1]);if(!Number.isInteger(F)||F<=0)continue;let I=n.get(F);I?I.push(S):n.set(F,[S])}catch{}}return n}function collectDescendants(n){let S=[],C=new Set([n]),N=[n],F=null;for(;N.length>0;){let n=N.shift(),I=readDirectChildren(n);I===null&&(F??=buildPpidMap(),I=F.get(n)??[]);for(let n of I)C.has(n)||(C.add(n),S.push(n),N.push(n))}return S}function signalTree(n,S,C){for(let n=S.length-1;n>=0;n--)try{process.kill(S[n],C)}catch{}try{n.kill(C)}catch{}}function killActiveChildren(){let n=new Map;for(let S of sB){let C=S.pid?collectDescendants(S.pid):[];n.set(S,C),signalTree(S,C,`SIGTERM`)}setTimeout(()=>{for(let S of sB){let C=new Set(S.pid?collectDescendants(S.pid):[]);for(let N of n.get(S)??[])C.add(N);signalTree(S,[...C],`SIGKILL`)}},cB).unref?.()}function assertEveryIncludeMatches(n,S){if(!S||S.length===0)return;let C=S.filter(S=>filterWorkspaces(n,{include:[S]}).length===0);if(C.length===0)return;let N=[`gjsify foreach: --include matched no workspace (${C.length} of ${S.length} pattern(s)):`];for(let S of C){N.push(` ${JSON.stringify(S)}`);let C=stripSurroundingQuotes(S);if(C!==S&&filterWorkspaces(n,{include:[C]}).length>0){N.push(` → matches as ${JSON.stringify(C)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let F=n.map(n=>n.name).filter(n=>n.toLowerCase().includes(C.replace(/\*/g,``).toLowerCase())).slice(0,3);F.length>0&&N.push(` → did you mean: ${F.join(`, `)}?`)}throw N.push(` ${n.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ve.error(N.join(`
|
|
1120
|
-
`)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(n){return n.length>=2&&(n[0]===`'`||n[0]===`"`)&&n[n.length-1]===n[0]?n.slice(1,-1):n}async function runSequential(n,S,C,N,F,I){for(let H of n)await runOne(H,S,C,!1,N,F,I)}async function runParallel(n,S,C,N,F,I,H){let W=0,q=[];for(let Y=0;Y<N;Y++)q.push((async()=>{for(;W<n.length;)await runOne(n[W++],S,C,!0,F,I,H)})());await Promise.all(q)}async function runTopologicalParallel(n,S,C,N,F,I,H,W){let q=new Set(n.map(n=>n.name)),Y=new Map;for(let S of n){let n=new Set,C=S.manifest;for(let S of[C.dependencies,I?C.devDependencies:void 0,C.optionalDependencies])if(S)for(let[C,N]of Object.entries(S))typeof N==`string`&&N.startsWith(`workspace:`)&&q.has(C)&&n.add(C);Y.set(S.name,n)}let X=new Map(n.map(n=>[n.name,n])),Z=n.length,te=new Set,ne=0,re=!process.stdout.isTTY||F,ie=new Map,ae=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),oe=(Number.isFinite(ae)&&ae>0?ae:20)*6e4;return new Promise((n,I)=>{let q=null,ae=Date.now(),describeInflight=()=>[...ie.entries()].map(([n,S])=>`${n} (${Math.round((Date.now()-S)/1e3)}s)`).join(`, `),failFast=n=>{q||(q=n,killActiveChildren(),setTimeout(()=>settle(),lB).unref?.())},se=setInterval(()=>{let n=Date.now()-ae;n<3e5||ie.size===0||(ve.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(n/6e4)}min — in-flight: ${describeInflight()}`),n>=oe&&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);se.unref?.();let settle=()=>{clearInterval(se),q?I(q):n()},pump=()=>{if(!q){for(;ne<N;){let n=[...Y.entries()].filter(([,n])=>[...n].every(n=>te.has(n))).map(([n])=>n);if(n.length===0)break;let N=n.sort()[0];Y.delete(N),ne++,ie.set(N,Date.now()),re&&ve.error(`[gjsify foreach] start ${N} (${te.size}/${Z} done, ${ne} in flight)`),runOne(X.get(N),S,C,!0,F,H,W).then(()=>{te.add(N)}).catch(n=>{failFast(n instanceof Error?n:Error(String(n)))}).finally(()=>{ne--,ie.delete(N),ae=Date.now(),q?ne===0&&settle():Y.size===0&&ne===0?settle():pump()})}Y.size>0&&ne===0&&!q&&(clearInterval(se),I(Error(`gjsify foreach --topological: stuck — workspaces ${[...Y.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne(n,S,C,N,F,I,H){if(I){F&&ve.error(`[${n.name}] $ ${S} ${C.join(` `)}`),await spawnPrefixed(S,C,n.location,N?`[${n.name}] `:null);return}if(H&&H.tryRestore(n))return;let W=H?.snapshotOutputs(n),q=detectPackageManager(),Y=q===`gjsify`?[`run`,S,...C]:[`run`,S,...C.length>0?[`--`,...C]:[]];F&&ve.error(`[${n.name}] $ ${q} ${Y.join(` `)}`),await spawnPrefixed(q,Y,n.location,N?`[${n.name}] `:null),H&&W&&H.storeAfterSuccess(n,W)}async function spawnPrefixed(n,S,C,N){let F=null,I=[];try{let H=await spawnToCompletion(n,S,{completion:`exit`,cwd:C,stdio:N?`pipe`:`inherit`,color:!0,onSpawn:n=>{F=n,sB.add(n);let S=!process.stdout.isTTY;N&&n.stdout&&n.stderr&&(I.push(prefixLines(n.stdout,process.stdout,N,S)),I.push(prefixLines(n.stderr,process.stderr,N,S)))}});for(let n of I)n();if(H.code!==0)throw Error(`${n} ${S.join(` `)} exited with code ${H.code}`)}finally{F&&sB.delete(F)}}var sB,cB,lB,uB,dB=__esmMin(()=>{ye(),_P(),Vl(),Dm(),GM(),qM(),wz(),LF(),WF(),qF(),sB=new Set,cB=5e3,lB=15e3,uB={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). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0}),handler:async n=>{let S=findWorkspaceRoot(process.cwd())??process.cwd(),C=discoverWorkspaces(S),N=n.exec===!0,F=n.script,I=n.args??[];if(!N){let S=(n[`--`]??[]).filter(n=>typeof n==`string`);S.length>0&&(I=[...I,...S])}if(N){let S=(n[`--`]??[]).filter(n=>typeof n==`string`);if(S.length>0&&(F?I=[...I,...S]:(F=S[0],I=[...I,...S.slice(1)])),!F)return ve.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(C,n.include);let H=filterWorkspaces(C,{include:n.include,exclude:n.exclude,noPrivate:n.private===!1});if(n[`with-dependencies`]===!0){let S=affectedClosure(buildDependencyGraph(C,{includeDev:n[`topological-dev`]===!0}),H.map(n=>n.name));H=filterWorkspaces(C.filter(n=>S.has(n.name)),{exclude:n.exclude,noPrivate:n.private===!1})}if(!N){if(!F)return ve.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let n=F;H=H.filter(S=>typeof(S.manifest.scripts??{})[n]==`string`)}if(typeof n.shard==`string`&&n.shard.length>0){let S=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(n.shard);if(!S)return ve.error(`gjsify foreach: invalid --shard "${n.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let C=Number(S[1]),N=Number(S[2]);if(N<1||C<1||C>N)return ve.error(`gjsify foreach: invalid --shard "${n.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(N>1){let n=[...H].sort((n,S)=>n.name<S.name?-1:+(n.name>S.name));H=n.filter((n,S)=>S%N===C-1),ve.log(`gjsify foreach: shard ${C}/${N} → ${H.length} of ${n.length} workspace(s)`)}}if(H.length===0){ve.log(`gjsify foreach: no workspaces match (${N?`exec`:`script`}="${F}", include=${JSON.stringify(n.include??[])}, exclude=${JSON.stringify(n.exclude??[])})`);return}(n.topological||n[`topological-dev`])&&(H=topologicalSort(buildDependencyGraph(H,{includeDev:n[`topological-dev`]===!0})));let W=n.verbose===!0,q=F,Y=n.cached??buildCacheEnabledByEnv();if(n.cached===!0&&N)return ve.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let X=Y&&!N?new BuildCacheRunner({root:S,workspaces:C,script:q,args:I,targets:H.map(n=>n.name)}):void 0,Z=n.parallel===!0?cliRuntimeClosure(C):new Set,te=Z.size>0?H.filter(n=>Z.has(n.name)):[],ne=te.length>0?H.filter(n=>!Z.has(n.name)):H;try{if(te.length>0){ve.error(`[gjsify foreach] serial prefix: ${te.length} package(s) the running CLI imports — ${te.map(n=>n.name).join(`, `)}`);for(let n of te)ve.error(`[gjsify foreach] start ${n.name} (serial prefix)`),await runOne(n,q,I,!0,W,N,X)}if(n.parallel&&!n.topological&&!n[`topological-dev`]){let S=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runParallel(ne,q,I,S,W,N,X)}else if(n.parallel){let S=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runTopologicalParallel(ne,q,I,S,W,n[`topological-dev`]===!0,N,X)}else await runSequential(ne,q,I,W,N,X)}catch(n){return killActiveChildren(),ve.error(n.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(n,S,C,N={}){let F=(S.scripts??{})[C];if(typeof F!=`string`){if(N.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${C}" in ${n}/package.json`)}let I=findWorkspaceRoot(n),H=[js(n,`node_modules`,`.bin`)];I&&I!==n&&H.push(js(I,`node_modules`,`.bin`));let W=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},q={...process.env,...W,PATH:[...H,process.env.PATH??``].filter(Boolean).join(Bs),npm_lifecycle_event:C,npm_package_name:S.name??``,npm_package_version:S.version??``,...N.env};if(N.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let Y=await spawnToCompletion(F,[],{completion:`return`,cwd:n,env:q,shell:!0,stdio:N.stdio===`inherit-stderr`?`inherit-stderr`:N.stdio===`pipe`?`pipe`:`inherit`});if(Y.code!==0)throw Error(`gjsify lifecycle-script: "${C}" in ${n} exited with ${describeExit(Y)}`);return!0}var fB=__esmMin(()=>{Hs(),_P(),qM()});async function packWorkspace(n,S={}){let C=js(n,`package.json`);if(!existsSync(C))throw Error(`gjsify pack: no package.json at ${n}`);let N=readFileSync(C,`utf-8`),F=JSON.parse(N),I=typeof F.name==`string`?F.name:``,H=typeof F.version==`string`?F.version:`0.0.0`;if(!I)throw Error(`gjsify pack: package.json at ${n} has no "name"`);let W=S.lifecycleScripts??[`prepack`];for(let C of W)await runLifecycleScript(n,F,C,{optional:!0,stdio:S.lifecycleStdio});let q=readFileSync(C,`utf-8`),Y=q===N?F:JSON.parse(q),X=S.skipWorkspaceRewrite?Y:rewriteWorkspaceDeps(Y,n),Z=JSON.stringify(X,null,indentOf(q))+`
|
|
1122
|
+
`);for(let n of C)ve.warn(` ✗ ${n.name}`);let n=buildInstallCommand(detectPackageManager$1(),C);n&&ve.warn(`\nInstall with:\n ${n}`)}else ve.log(`System dependencies OK.`);await ensureProjectGjsEngine(n,S.find(n=>n.id===`gjs`)?.found??!1);let N=detectNativePackages(process.cwd());if(N.length>0){ve.log(`\nDetected ${N.length} @gjsify/* package(s) with native prebuilds:`);for(let n of N)ve.log(` • ${n.name}`);ve.log("\nUse `gjsify run <bundle>` to launch with LD_LIBRARY_PATH/GI_TYPELIB_PATH set.")}maybeInstallGitHooks()}function maybeInstallGitHooks(){let n=process.cwd(),S=js(n,`scripts`,`install-git-hooks.mjs`);if(existsSync(S)&&existsSync(js(n,`.git`)))try{let C=spawnSync(nodeBinary(),[S,`--quiet`],{cwd:n,stdio:`inherit`,env:process.env});C.status!==0&&ve.warn(`[gjsify install] scripts/install-git-hooks.mjs exited ${C.status} — git hooks may not be active.`)}catch(n){ve.warn(`[gjsify install] git hook installation skipped: ${n instanceof Error?n.message:String(n)}`)}}var pB,mB,hB,gB,_B=__esmMin(()=>{ye(),Vl(),Hs(),gn(),Dh(),uB(),GM(),dN(),gN(),jP(),bF(),GP(),eF(),xP(),_P(),qM(),wF(),uF(),fB(),TP(),pB=process.platform===`win32`?`junction`:void 0,mB=18e5,hB={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:mB}).option(`os`,{description:"Resolve/install for this OS instead of the running one (npm config key `os`, e.g. darwin, win32, linux). Affects which packages pass the os/cpu/libc compatibility check; the lockfile stays platform-independent either way.",type:`string`}).option(`cpu`,{description:"Resolve/install for this CPU architecture instead of the running one (npm config key `cpu`, e.g. x64, arm64).",type:`string`}).option(`libc`,{description:"Resolve/install for this libc family instead of probing the host (npm config key `libc`: glibc or musl). Only meaningful with --os=linux. A package declaring a libc is incompatible when the target libc is unknown.",type:`string`}).option(`force`,{description:"Install a REQUIRED dependency even when its os/cpu/libc excludes the target, instead of failing with EBADPLATFORM (npm config key `force`). Incompatible OPTIONAL dependencies stay skipped — npm ignores --force for those too, and a binary that cannot load is not worth downloading.",type:`boolean`,default:!1}).option(`prune`,{description:`After installing, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable. Skipped automatically under --immutable, and whenever --os/--cpu/--libc is given: an install must never delete against a target the user typed.`,type:`boolean`,default:!0}),handler:async n=>{if(applyPlatformConfigFromFlags(n),n.immutable){if(n.packages&&n.packages.length>0)return ve.error(`gjsify install --immutable does not accept package arguments. Remove the package names or drop --immutable.`),process.exit(1);if(n.global)return ve.error(`gjsify install --immutable is incompatible with --global.`),process.exit(1);if(n[`refresh-lockfile`])return ve.error(`gjsify install --immutable is incompatible with --refresh-lockfile (--immutable forbids rewriting the lockfile). Drop one.`),process.exit(1)}if(n.global){if(!n.packages||n.packages.length===0)return ve.error(`gjsify install --global requires at least one <pkg> argument.`),process.exit(1);for(let S of[`save-dev`,`save-peer`,`save-optional`])n[S]&&ve.warn(`gjsify install --global ignores --${S}: global installs do not modify a project package.json.`);await installGlobalAndLink(n.packages,{verbose:n.verbose,prune:n.prune});return}if(warnOnCliVersionSkew(process.cwd()),(n.backend??process.env.GJSIFY_INSTALL_BACKEND??`native`)===`npm`){await projectInstallViaNpm(n),pruneProjectPrefix(n),await runPostInstallChecks(n);return}let S=n.timeout>0?n.timeout:0,C=S>0?new AbortController:null,N=C===null?null:setTimeout(()=>C.abort(Error(`install-overall-timeout`)),S),F=S>0?setTimeout(()=>{let n=Math.round(S/100)/10;ve.error(`gjsify install: the ${n}s budget elapsed and the abort did not unwind within 10s — forcing exit. That means one of two things, and this timer cannot distinguish them: the install was still WORKING (a cold tree here extracts several GB, and extraction blocks the loop in multi-second synchronous stretches), or a step genuinely wedged. Re-running tells you which, and is safe: extraction is idempotent, every package already on disk is skipped, so a second run finishes the remainder in a fraction of the time. A re-run that makes NO further progress is a real wedge — file an issue.`),forceExit(1)},S+1e4):null;F?.unref?.();try{await projectInstallNative(n,C?.signal),pruneProjectPrefix(n),await runPostInstallChecks(n)}catch(n){if(C!==null&&C.signal.aborted&&isAbortedFromOverallTimeout(n)){let n=Math.round(S/100)/10;return ve.error(`gjsify install: timed out after ${n}s — likely a registry slowdown or a wedged extract.\nRe-run, or override with --timeout <ms> (set --timeout 0 to disable the overall budget).`),process.exit(1)}throw n}finally{N!==null&&clearTimeout(N),F!==null&&clearTimeout(F)}}},gB=`@gjsify/cli`});function readDirectChildren(n){let S;try{S=readdirSync(`/proc/${n}/task`)}catch{return null}let C=[],N=!1;for(let F of S)try{let S=readFileSync(`/proc/${n}/task/${F}/children`,`utf-8`);N=!0;for(let n of S.trim().split(/\s+/)){let S=Number(n);Number.isInteger(S)&&S>0&&C.push(S)}}catch{}return N?C:null}function buildPpidMap(){let n=new Map,S=[];try{S=`1.10329.10340.1951.1957.1964.acpi.bootconfig.buddyinfo.bus.cgroups.cmdline.consoles.cpuinfo.crypto.devices.diskstats.dma.driver.dynamic_debug.execdomains.fb.filesystems.fs.interrupts.iomem.ioports.irq.kallsyms.kcore.key-users.keys.kmsg.kpagecgroup.kpagecount.kpageflags.latency_stats.loadavg.locks.mdstat.meminfo.misc.modules.mounts.mtrr.net.pagetypeinfo.partitions.pressure.schedstat.scsi.self.slabinfo.softirqs.stat.swaps.sys.sysrq-trigger.sysvipc.thread-self.timer_list.tty.uptime.version.version_signature.vmallocinfo.vmstat.zoneinfo`.split(`.`)}catch{return n}for(let C of S){let S=Number(C);if(!(!Number.isInteger(S)||S<=0))try{let C=readFileSync(`/proc/${S}/stat`,`utf-8`),N=C.slice(C.lastIndexOf(`)`)+2).split(` `),F=Number(N[1]);if(!Number.isInteger(F)||F<=0)continue;let I=n.get(F);I?I.push(S):n.set(F,[S])}catch{}}return n}function collectDescendants(n){let S=[],C=new Set([n]),N=[n],F=null;for(;N.length>0;){let n=N.shift(),I=readDirectChildren(n);I===null&&(F??=buildPpidMap(),I=F.get(n)??[]);for(let n of I)C.has(n)||(C.add(n),S.push(n),N.push(n))}return S}function signalTree(n,S,C){for(let n=S.length-1;n>=0;n--)try{process.kill(S[n],C)}catch{}try{n.kill(C)}catch{}}function killActiveChildren(){let n=new Map;for(let S of vB){let C=S.pid?collectDescendants(S.pid):[];n.set(S,C),signalTree(S,C,`SIGTERM`)}setTimeout(()=>{for(let S of vB){let C=new Set(S.pid?collectDescendants(S.pid):[]);for(let N of n.get(S)??[])C.add(N);signalTree(S,[...C],`SIGKILL`)}},yB).unref?.()}function assertEveryIncludeMatches(n,S){if(!S||S.length===0)return;let C=S.filter(S=>filterWorkspaces(n,{include:[S]}).length===0);if(C.length===0)return;let N=[`gjsify foreach: --include matched no workspace (${C.length} of ${S.length} pattern(s)):`];for(let S of C){N.push(` ${JSON.stringify(S)}`);let C=stripSurroundingQuotes(S);if(C!==S&&filterWorkspaces(n,{include:[C]}).length>0){N.push(` → matches as ${JSON.stringify(C)}: the QUOTES are part of the value. A shell expansion`," is not re-scanned for quoting, so a pre-quoted filter spliced through `sh -c` arrives with",` the quotes attached. Pass the bare name and let word splitting do the work.`);continue}let F=n.map(n=>n.name).filter(n=>n.toLowerCase().includes(C.replace(/\*/g,``).toLowerCase())).slice(0,3);F.length>0&&N.push(` → did you mean: ${F.join(`, `)}?`)}throw N.push(` ${n.length} workspace(s) discovered. Refusing to run: a filter that selects nothing would`,` otherwise exit 0 and look exactly like a successful run over the whole set.`),ve.error(N.join(`
|
|
1123
|
+
`)),process.exit(1),Error(`gjsify foreach: --include matched no workspace`)}function stripSurroundingQuotes(n){return n.length>=2&&(n[0]===`'`||n[0]===`"`)&&n[n.length-1]===n[0]?n.slice(1,-1):n}async function runSequential(n,S,C,N,F,I){for(let H of n)await runOne(H,S,C,!1,N,F,I)}async function runParallel(n,S,C,N,F,I,H){let W=0,q=[];for(let Y=0;Y<N;Y++)q.push((async()=>{for(;W<n.length;)await runOne(n[W++],S,C,!0,F,I,H)})());await Promise.all(q)}async function runTopologicalParallel(n,S,C,N,F,I,H,W){let q=new Set(n.map(n=>n.name)),Y=new Map;for(let S of n){let n=new Set,C=S.manifest;for(let S of[C.dependencies,I?C.devDependencies:void 0,C.optionalDependencies])if(S)for(let[C,N]of Object.entries(S))typeof N==`string`&&N.startsWith(`workspace:`)&&q.has(C)&&n.add(C);Y.set(S.name,n)}let X=new Map(n.map(n=>[n.name,n])),Z=n.length,te=new Set,ne=0,re=!process.stdout.isTTY||F,ie=new Map,ae=Number(process.env.GJSIFY_FOREACH_STALL_MINUTES??`20`),oe=(Number.isFinite(ae)&&ae>0?ae:20)*6e4;return new Promise((n,I)=>{let q=null,ae=Date.now(),describeInflight=()=>[...ie.entries()].map(([n,S])=>`${n} (${Math.round((Date.now()-S)/1e3)}s)`).join(`, `),failFast=n=>{q||(q=n,killActiveChildren(),setTimeout(()=>settle(),bB).unref?.())},se=setInterval(()=>{let n=Date.now()-ae;n<3e5||ie.size===0||(ve.error(`[gjsify foreach] WARNING: no workspace completed for ${Math.round(n/6e4)}min — in-flight: ${describeInflight()}`),n>=oe&&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);se.unref?.();let settle=()=>{clearInterval(se),q?I(q):n()},pump=()=>{if(!q){for(;ne<N;){let n=[...Y.entries()].filter(([,n])=>[...n].every(n=>te.has(n))).map(([n])=>n);if(n.length===0)break;let N=n.sort()[0];Y.delete(N),ne++,ie.set(N,Date.now()),re&&ve.error(`[gjsify foreach] start ${N} (${te.size}/${Z} done, ${ne} in flight)`),runOne(X.get(N),S,C,!0,F,H,W).then(()=>{te.add(N)}).catch(n=>{failFast(n instanceof Error?n:Error(String(n)))}).finally(()=>{ne--,ie.delete(N),ae=Date.now(),q?ne===0&&settle():Y.size===0&&ne===0?settle():pump()})}Y.size>0&&ne===0&&!q&&(clearInterval(se),I(Error(`gjsify foreach --topological: stuck — workspaces ${[...Y.keys()].join(`, `)} have unsatisfied deps in the selected set`)))}};pump()})}async function runOne(n,S,C,N,F,I,H){if(I){F&&ve.error(`[${n.name}] $ ${S} ${C.join(` `)}`),await spawnPrefixed(S,C,n.location,N?`[${n.name}] `:null);return}if(H&&H.tryRestore(n))return;let W=H?.snapshotOutputs(n),q=detectPackageManager(),Y=q===`gjsify`?[`run`,S,...C]:[`run`,S,...C.length>0?[`--`,...C]:[]];F&&ve.error(`[${n.name}] $ ${q} ${Y.join(` `)}`),await spawnPrefixed(q,Y,n.location,N?`[${n.name}] `:null),H&&W&&H.storeAfterSuccess(n,W)}async function spawnPrefixed(n,S,C,N){let F=null,I=[];try{let H=await spawnToCompletion(n,S,{completion:`exit`,cwd:C,stdio:N?`pipe`:`inherit`,color:!0,onSpawn:n=>{F=n,vB.add(n);let S=!process.stdout.isTTY;N&&n.stdout&&n.stderr&&(I.push(prefixLines(n.stdout,process.stdout,N,S)),I.push(prefixLines(n.stderr,process.stderr,N,S)))}});for(let n of I)n();if(H.code!==0)throw Error(`${n} ${S.join(` `)} exited with code ${H.code}`)}finally{F&&vB.delete(F)}}var vB,yB,bB,xB,SB=__esmMin(()=>{ye(),_P(),Vl(),Dm(),GM(),qM(),Az(),RF(),wP(),GF(),JF(),vB=new Set,yB=5e3,bB=15e3,xB={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). A pattern that matches NO discovered workspace is a hard error — a filter selecting nothing is a typo or a caller-side quoting bug, never an intent.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude workspaces by name (repeatable).`,type:`string`,array:!0}).option(`with-dependencies`,{description:`Also select everything the filtered set DEPENDS ON (production deps; add --topological-dev for devDependencies). --include only filters and --topological only orders, so neither can say 'and the packages these need'. Excludes are re-applied afterwards.`,type:`boolean`,alias:`d`,default:!1}).option(`private`,{description:`Include private workspaces (default true). Pass --no-private to skip them.`,type:`boolean`,default:!0}).option(`verbose`,{description:`Echo every spawned command before running it.`,type:`boolean`,alias:`v`,default:!1}).option(`jobs`,{description:`Maximum concurrent workspaces in --parallel mode (default: cpu count).`,type:`number`,alias:`j`}).option(`exec`,{description:"Treat <script> [args..] as an arbitrary command (yarn `workspaces foreach exec`-equivalent) instead of a package.json script lookup. Workspace filtering by script presence is skipped. Use `-- <cmd> <args...>` to pass flags to the command without yargs intercepting them.",type:`boolean`,default:!1}).option(`cached`,{description:`Content-hash build cache (ADR 0006): skip a workspace whose inputs (src/**, package.json, tsconfig*.json, transitive workspace deps, toolchain versions) are unchanged and restore its stored outputs instead; on miss run the script and store the output dirs it modified. Script mode only. Default from GJSIFY_BUILD_CACHE=1.`,type:`boolean`}).option(`shard`,{description:`Run only a deterministic slice "<index>/<total>" (1-based) of the matched workspaces, e.g. --shard 2/4. For fanning a long run across parallel CI jobs. Partitions by sorted name (round-robin) so the shards are disjoint and their union is the full set; order-independent, so safe for tests but NOT for ordered builds.`,type:`string`}).parserConfiguration({"populate--":!0,"parse-positional-numbers":!1}),handler:async n=>{let S=findWorkspaceRoot(process.cwd())??process.cwd(),C=discoverWorkspaces(S),N=n.exec===!0,F=n.script,I=n.args??[];if(!N){let S=doubleDashArgs(n);S.length>0&&(I=[...I,...S])}if(N){let S=doubleDashArgs(n);if(S.length>0&&(F?I=[...I,...S]:(F=S[0],I=[...I,...S.slice(1)])),!F)return ve.error("gjsify foreach --exec: missing command. Pass it after `--`, e.g. `gjsify foreach --exec -- npm publish --tag latest`."),process.exit(1)}assertEveryIncludeMatches(C,n.include);let H=filterWorkspaces(C,{include:n.include,exclude:n.exclude,noPrivate:n.private===!1});if(n[`with-dependencies`]===!0){let S=affectedClosure(buildDependencyGraph(C,{includeDev:n[`topological-dev`]===!0}),H.map(n=>n.name));H=filterWorkspaces(C.filter(n=>S.has(n.name)),{exclude:n.exclude,noPrivate:n.private===!1})}if(!N){if(!F)return ve.error(`gjsify foreach: missing <script> positional. Pass --exec to run an arbitrary command instead.`),process.exit(1);let n=F;H=H.filter(S=>typeof(S.manifest.scripts??{})[n]==`string`)}if(typeof n.shard==`string`&&n.shard.length>0){let S=/^\s*(\d+)\s*\/\s*(\d+)\s*$/.exec(n.shard);if(!S)return ve.error(`gjsify foreach: invalid --shard "${n.shard}" — expected "<index>/<total>" (1-based), e.g. 2/4.`),process.exit(1);let C=Number(S[1]),N=Number(S[2]);if(N<1||C<1||C>N)return ve.error(`gjsify foreach: invalid --shard "${n.shard}" — need 1 <= index <= total and total >= 1.`),process.exit(1);if(N>1){let n=[...H].sort((n,S)=>n.name<S.name?-1:+(n.name>S.name));H=n.filter((n,S)=>S%N===C-1),ve.log(`gjsify foreach: shard ${C}/${N} → ${H.length} of ${n.length} workspace(s)`)}}if(H.length===0){ve.log(`gjsify foreach: no workspaces match (${N?`exec`:`script`}="${F}", include=${JSON.stringify(n.include??[])}, exclude=${JSON.stringify(n.exclude??[])})`);return}(n.topological||n[`topological-dev`])&&(H=topologicalSort(buildDependencyGraph(H,{includeDev:n[`topological-dev`]===!0})));let W=n.verbose===!0,q=F,Y=n.cached??buildCacheEnabledByEnv();if(n.cached===!0&&N)return ve.error(`gjsify foreach: --cached only applies to script mode, not --exec.`),process.exit(1);let X=Y&&!N?new BuildCacheRunner({root:S,workspaces:C,script:q,args:I,targets:H.map(n=>n.name)}):void 0,Z=n.parallel===!0?cliRuntimeClosure(C):new Set,te=Z.size>0?H.filter(n=>Z.has(n.name)):[],ne=te.length>0?H.filter(n=>!Z.has(n.name)):H;try{if(te.length>0){ve.error(`[gjsify foreach] serial prefix: ${te.length} package(s) the running CLI imports — ${te.map(n=>n.name).join(`, `)}`);for(let n of te)ve.error(`[gjsify foreach] start ${n.name} (serial prefix)`),await runOne(n,q,I,!0,W,N,X)}if(n.parallel&&!n.topological&&!n[`topological-dev`]){let S=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runParallel(ne,q,I,S,W,N,X)}else if(n.parallel){let S=n.jobs&&n.jobs>0?n.jobs:cpus().length;await runTopologicalParallel(ne,q,I,S,W,n[`topological-dev`]===!0,N,X)}else await runSequential(ne,q,I,W,N,X)}catch(n){return killActiveChildren(),ve.error(n.message),process.exit(1)}process.exit(0)}}});async function runLifecycleScript(n,S,C,N={}){let F=(S.scripts??{})[C];if(typeof F!=`string`){if(N.optional!==!1)return!1;throw Error(`gjsify lifecycle-script: no "${C}" in ${n}/package.json`)}let I=findWorkspaceRoot(n),H=[js(n,`node_modules`,`.bin`)];I&&I!==n&&H.push(js(I,`node_modules`,`.bin`));let W=process.env.FORCE_COLOR!==void 0||process.env.NO_COLOR!==void 0?{}:{FORCE_COLOR:`1`},q={...process.env,...W,PATH:[...H,process.env.PATH??``].filter(Boolean).join(Bs),npm_lifecycle_event:C,npm_package_name:S.name??``,npm_package_version:S.version??``,...N.env};if(N.stdio===`ignore`)throw Error(`gjsify lifecycle-script: stdio "ignore" is not supported — see utils/spawn.ts`);let Y=await spawnToCompletion(F,[],{completion:`return`,cwd:n,env:q,shell:!0,stdio:N.stdio===`inherit-stderr`?`inherit-stderr`:N.stdio===`pipe`?`pipe`:`inherit`});if(Y.code!==0)throw Error(`gjsify lifecycle-script: "${C}" in ${n} exited with ${describeExit(Y)}`);return!0}var CB=__esmMin(()=>{Hs(),_P(),qM()});async function packWorkspace(n,S={}){let C=js(n,`package.json`);if(!existsSync(C))throw Error(`gjsify pack: no package.json at ${n}`);let N=readFileSync(C,`utf-8`),F=JSON.parse(N),I=typeof F.name==`string`?F.name:``,H=typeof F.version==`string`?F.version:`0.0.0`;if(!I)throw Error(`gjsify pack: package.json at ${n} has no "name"`);let W=S.lifecycleScripts??[`prepack`];for(let C of W)await runLifecycleScript(n,F,C,{optional:!0,stdio:S.lifecycleStdio});let q=readFileSync(C,`utf-8`),Y=q===N?F:JSON.parse(q),X=S.skipWorkspaceRewrite?Y:rewriteWorkspaceDeps(Y,n),Z=JSON.stringify(X,null,indentOf(q))+`
|
|
1121
1124
|
`,te=collectPackedFiles(n,Y);assertTypeDeclarationsShipped(n,Y,te);let ne=[{name:`package/`,directory:!0,mode:493}],re=[],ie=0;for(let S of te){let C;C=S===`package.json`?new TextEncoder().encode(Z):new Uint8Array(readFileSync(js(n,S)));let N=statSync(js(n,S)).mode&511;ne.push({name:`package/${S}`,body:C,mode:N,mtime:0}),re.push({path:S,size:C.byteLength,mode:N}),ie+=C.byteLength}let ae=await gzip(createTarball(ne)),oe=`${I.startsWith(`@`)?I.slice(1).replace(`/`,`-`):I}-${H}.tgz`,se=createHash(`sha1`).update(ae).digest(`hex`),Q=`sha512-${createHash(`sha512`).update(ae).digest(`base64`)}`,ce=S.destination?Os(S.destination):n,le=js(ce,oe);return S.dryRun||(mkdirSync(ce,{recursive:!0}),writeFileSync(le,ae)),{filename:oe,name:I,version:H,size:ae.byteLength,unpackedSize:ie,shasum:se,integrity:Q,entryCount:re.length,files:re,absolutePath:S.dryRun?null:le}}function collectPackedFiles(n,S){let C=forceIncluded(S),N=Array.isArray(S.files)?S.files.filter(n=>typeof n==`string`):null,F=new Set;if(N)for(let S of expandFilesPatterns(n,N))F.add(S);else{let S=loadIgnore(n);for(let C of walkAll(n))S(C)||F.add(C)}for(let S of C)existsSync(js(n,S))&&F.add(S);return[...F].sort()}function collectTypeDeclarationRefs(n){let S=new Set,add=n=>{if(typeof n!=`string`)return;let C=n.replace(/^\.\//,``);C.includes(`*`)||S.add(C)};for(let S of[`types`,`typings`])add(n[S]);let walk=n=>{if(!(!n||typeof n!=`object`)){if(Array.isArray(n)){for(let S of n)walk(S);return}for(let[S,C]of Object.entries(n))S===`types`||S===`typings`?add(C):walk(C)}};return walk(n.exports),[...S]}function assertTypeDeclarationsShipped(n,S,C){let N=new Set(C),F=collectTypeDeclarationRefs(S).filter(S=>{let C=js(n,S);return existsSync(C)&&statSync(C).isFile()&&!N.has(S)});if(F.length===0)return;let I=typeof S.name==`string`?S.name:`(unnamed)`,H=Array.isArray(S.files)?JSON.stringify(S.files):`(none)`;throw Error(`gjsify pack: ${I} references TypeScript declaration file(s) via "exports"/"types" that exist on disk but are excluded from the tarball by the "files" allowlist (${H}):\n`+F.map(n=>` - ${n}`).join(`
|
|
1122
1125
|
`)+`
|
|
1123
|
-
Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(n){let S=new Set;S.add(`package.json`);for(let n of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])S.add(n);let C=typeof n.main==`string`?n.main:null;C&&S.add(C.replace(/^\.\//,``));let N=n.bin;if(typeof N==`string`)S.add(N.replace(/^\.\//,``));else if(N&&typeof N==`object`)for(let n of Object.values(N))typeof n==`string`&&S.add(n.replace(/^\.\//,``));return[...S]}function walkAll(n,S=``){let C=[],N=S?js(n,S):n,F;try{F=readdirSync(N,{withFileTypes:!0})}catch{return C}for(let N of F){if(
|
|
1124
|
-
`);for(let S of n){let n=S.trim();!n||n.startsWith(`#`)||n.startsWith(`!`)||N.push(globToRegex(n))}}return n=>{for(let S of N)if(S.test(n))return!0;return!1}}function globToRegex(n){let S=n.replace(/^\//,``);return S=S.replace(/[.+^${}()|[\]\\]/g,`\\$&`),S=S.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),S=S.replace(/\?/g,`[^/]`),RegExp(`^${S}($|/)`)}function collectWorkspaceProtocolDeps(n){let S=[];for(let C of
|
|
1126
|
+
Add the missing path(s) to package.json "files" so type resolution isn't silently broken for consumers.`)}function forceIncluded(n){let S=new Set;S.add(`package.json`);for(let n of[`README`,`README.md`,`LICENSE`,`LICENSE.md`,`NOTICE`,`NOTICE.md`])S.add(n);let C=typeof n.main==`string`?n.main:null;C&&S.add(C.replace(/^\.\//,``));let N=n.bin;if(typeof N==`string`)S.add(N.replace(/^\.\//,``));else if(N&&typeof N==`object`)for(let n of Object.values(N))typeof n==`string`&&S.add(n.replace(/^\.\//,``));return[...S]}function walkAll(n,S=``){let C=[],N=S?js(n,S):n,F;try{F=readdirSync(N,{withFileTypes:!0})}catch{return C}for(let N of F){if(TB.has(N.name)||N.name.startsWith(`.tsbuildinfo`))continue;let F=S?`${S}/${N.name}`:N.name;N.isDirectory()?C.push(...walkAll(n,F)):N.isFile()&&C.push(F)}return C}function expandFilesPatterns(n,S){let C=new Set,N=null;for(let F of S){let S=F.replace(/^\.\//,``).replace(/\/$/,``);if(!S)continue;if(!/[*?[\]]/.test(S)){let N=js(n,S);if(!existsSync(N))continue;let F=statSync(N);if(F.isDirectory())for(let N of walkAll(n,S))C.add(N);else F.isFile()&&C.add(S);continue}N??=walkAll(n);let I=filesGlobToRegExp(S),H=filesGlobToRegExp(`${S}/**`);for(let n of N)(I.test(n)||H.test(n))&&C.add(n)}return[...C]}function filesGlobToRegExp(n){let S=`^`;for(let C=0;C<n.length;C++){let N=n[C];if(N===`*`)n[C+1]===`*`?(S+=`.*`,C++,n[C+1]===`/`&&C++):S+=`[^/]*`;else if(N===`?`)S+=`[^/]`;else if(N===`[`){let N=C+1,F=`[`;for(n[N]===`!`&&(F+=`^`,N++);N<n.length&&n[N]!==`]`;N++)F+=n[N];N<n.length?(S+=`${F}]`,C=N):S+=`\\[`}else".+^${}()|\\]".includes(N)?S+=`\\${N}`:S+=N}return RegExp(`${S}$`)}function loadIgnore(n){let S=js(n,`.npmignore`),C=js(n,`.gitignore`),N=[],F=existsSync(S)?S:existsSync(C)?C:null;if(F){let n=readFileSync(F,`utf-8`).split(`
|
|
1127
|
+
`);for(let S of n){let n=S.trim();!n||n.startsWith(`#`)||n.startsWith(`!`)||N.push(globToRegex(n))}}return n=>{for(let S of N)if(S.test(n))return!0;return!1}}function globToRegex(n){let S=n.replace(/^\//,``);return S=S.replace(/[.+^${}()|[\]\\]/g,`\\$&`),S=S.replace(/\*\*/g,`__DOUBLESTAR__`).replace(/\*/g,`[^/]*`).replace(/__DOUBLESTAR__/g,`.*`),S=S.replace(/\?/g,`[^/]`),RegExp(`^${S}($|/)`)}function collectWorkspaceProtocolDeps(n){let S=[];for(let C of EB){let N=n[C];if(N)for(let[n,F]of Object.entries(N))typeof F==`string`&&F.startsWith(`workspace:`)&&S.push(`${C}.${n}`)}return S}function findPackWorkspaceRoot(n){let S=findWorkspaceRoot(n);if(S)return S;let C=n;for(let n=0;n<12;n++){let n=js(C,`package.json`);if(existsSync(n)&&readPackageJson$2(n)?.workspaces!==void 0)return C;let S=Os(C,`..`);if(S===C)break;C=S}return null}function rewriteWorkspaceDeps(n,S){let C=findPackWorkspaceRoot(S);if(!C){let C=collectWorkspaceProtocolDeps(n);if(C.length>0)throw Error(`gjsify pack: ${String(n.name)} declares workspace: ranges (${C.join(`, `)}) but ${S} is not inside a monorepo (no ancestor package.json declares "workspaces"). A workspace: range cannot be published — replace it with a real npm range, or pack from within the monorepo.`);return n}let N=new Map;for(let n of discoverWorkspaces(C))n.name&&n.version&&N.set(n.name,n.version);let F=JSON.parse(JSON.stringify(n));for(let n of EB){let S=F[n];if(S)for(let[I,H]of Object.entries(S)){if(typeof H!=`string`||!H.startsWith(`workspace:`))continue;let W=N.get(I);if(!W)throw Error(`gjsify pack: ${F.name} declares ${H} on ${I} (${n}) but no sibling workspace with that name exists in the monorepo at ${C}`);let q=H.slice(10);q===`*`||q===``?S[I]=W:q===`^`||q===`~`?S[I]=`${q}${W}`:S[I]=q}}return F}function indentOf(n){let S=n.match(/\n([ \t]+)"/);return S?S[1]:` `}var wB,TB,EB,DB=__esmMin(()=>{Vl(),No(),Hs(),WP(),GM(),qM(),KM(),CB(),wB={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 S=await packWorkspace(Os(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([S],null,2)}\n`):process.stdout.write(`${S.filename}\n`)}},TB=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`]),EB=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`]});function decodeJwtPayload(n){let S=n.split(`.`);if(S.length!==3)return null;try{let n=S[1].replace(/-/g,`+`).replace(/_/g,`/`),C=typeof atob==`function`?atob(n):Buffer.from(n,`base64`).toString(`binary`);return JSON.parse(C)}catch{return null}}function hasGithubOidcEnv(){return!!(process.env.ACTIONS_ID_TOKEN_REQUEST_URL&&process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN)}async function fetchGithubOidcToken(n,S){let C=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,N=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!C||!N)throw new OidcUnavailableError("GitHub Actions OIDC env vars (ACTIONS_ID_TOKEN_REQUEST_{URL,TOKEN}) not set. The calling workflow needs `permissions: id-token: write`.",`no-env`);let F=`${C}${C.includes(`?`)?`&`:`?`}audience=${encodeURIComponent(n)}`;S?.(`gjsify oidc: GET ${F.replace(N,`<bearer>`)}`);let I=await fetch(F,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${N}`}});if(!I.ok){let n=await I.text().catch(()=>`<no body>`);throw new OidcUnavailableError(`Failed to fetch GitHub OIDC id_token: ${I.status} ${I.statusText} — ${n.slice(0,200)}`,`fetch-id-token`)}let H=await I.json().catch(()=>({}));if(!H.value)throw new OidcUnavailableError("GitHub OIDC response missing `value` field",`no-id-token`);return H.value}async function exchangeOidcForNpmToken(n){let{packageName:S,registry:C,idToken:N,log:F}=n,I=`${C.endsWith(`/`)?C.slice(0,-1):C}/-/npm/v1/oidc/token/exchange/package/${S.startsWith(`@`)?(()=>{let n=S.indexOf(`/`),C=S.slice(1,n),N=S.slice(n+1);return`@${encodeURIComponent(C)}%2f${encodeURIComponent(N)}`})():encodeURIComponent(S)}`;F?.(`gjsify oidc: POST ${I}`);let H=n.maxRetries??3,W=n.retryBaseMs??1e3;for(let n=0;;n++){let C;try{C=await fetch(I,{method:`POST`,headers:{Authorization:`Bearer ${N}`,"Content-Type":`application/json`,Accept:`application/json`},body:`{}`})}catch(C){if(n<H){let C=Math.min(W*2**n,8e3);F?.(`gjsify oidc: network error for ${S} (attempt ${n+1}/${H+1}), retrying in ${C}ms`),await sleep(C);continue}throw new OidcExchangeError(`npm OIDC token exchange network error for ${S} after ${n+1} attempt(s): ${C instanceof Error?C.message:String(C)}`,0,``,S,decodeJwtPayload(N)??void 0)}let q=await C.text().catch(()=>``);if(!C.ok){if(OB.has(C.status)&&n<H){let N=Math.min(W*2**n,8e3);F?.(`gjsify oidc: transient ${C.status} ${C.statusText} for ${S} (attempt ${n+1}/${H+1}), retrying in ${N}ms`),await sleep(N);continue}throw new OidcExchangeError(`npm OIDC token exchange failed for ${S}: ${C.status} ${C.statusText} — ${q.slice(0,300)}`,C.status,q,S,decodeJwtPayload(N)??void 0)}let Y;try{Y=JSON.parse(q)}catch{throw new OidcExchangeError(`npm OIDC token exchange returned non-JSON body for ${S}: ${q.slice(0,200)}`,C.status,q,S)}if(!Y.token)throw new OidcExchangeError(`npm OIDC token exchange returned no \`token\` field for ${S}`,C.status,q,S);return Y.token}}async function getNpmTrustedToken(n){let S=`npm:${new URL(n.registry).hostname}`,C=await fetchGithubOidcToken(S,n.log);return{token:await exchangeOidcForNpmToken({...n,idToken:C}),audience:S}}var OB,sleep,OidcUnavailableError,OidcExchangeError,kB=__esmMin(()=>{OB=new Set([408,425,429,500,502,503,504]),sleep=n=>new Promise(S=>setTimeout(S,n)),OidcUnavailableError=class extends Error{reason;constructor(n,S){super(n),this.reason=S,this.name=`OidcUnavailableError`}},OidcExchangeError=class extends Error{status;body;packageName;claims;constructor(n,S,C,N,F){super(n),this.status=S,this.body=C,this.packageName=N,this.claims=F,this.name=`OidcExchangeError`}}});async function diagnose404(n){let{packageName:S,version:C,registry:N,npmrc:F}=n,I={};try{I=await whoami(N,F)}catch{return{reason:`unknown`,message:formatUnknown(S,C)}}return I.username&&I.username.length>0?{reason:`live-token-404`,username:I.username,message:formatLiveToken404(S,C,I.username)}:{reason:`dead-token`,message:formatDeadToken(S,C)}}function formatDeadToken(n,S){return[`gjsify publish: ${n}@${S} — 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(`
|
|
1125
1128
|
`)}function formatLiveToken404(n,S,C){return[`gjsify publish: ${n}@${S} — 404 Not Found`,``,`Authenticated as: ${C}`,``,`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(`
|
|
1126
|
-
`)}function formatUnknown(n,S){return`gjsify publish: ${n}@${S} — 404 Not Found`}function is404DiagnosticCandidate(n){let S=n.trim();return!!(S.length===0||/^not found$/i.test(S)||/"error"\s*:\s*"Not Found"/i.test(S))}var
|
|
1129
|
+
`)}function formatUnknown(n,S){return`gjsify publish: ${n}@${S} — 404 Not Found`}function is404DiagnosticCandidate(n){let S=n.trim();return!!(S.length===0||/^not found$/i.test(S)||/"error"\s*:\s*"Not Found"/i.test(S))}var AB=__esmMin(()=>{ep()});function backoffFor(n){return jB[Math.min(Math.max(n,0),jB.length-1)]??3e4}function probeTimeoutFor(n,S){return Math.min(n,Math.max(S,MB))}async function verifyPublishedVersion(n){let{registry:S,name:C,version:N,budgetMs:F}=n,I=n.fetchImpl??((...n)=>globalThis.fetch(...n)),H=n.sleep??(n=>new Promise(S=>setTimeout(S,n))),W=n.now??(()=>Date.now()),q=n.probeTimeoutMs??3e4,Y=`${S.endsWith(`/`)?S.slice(0,-1):S}/${escapePackageName(C)}`,X=W(),Z=0,te={state:`error`,detail:`no probe was sent`};for(let S=0;Z++,te=await probeOnce({url:Y,version:N,doFetch:I,probeTimeoutMs:probeTimeoutFor(q,F-(W()-X)),authorization:n.authorization}),n.log?.(`gjsify publish: read-back probe ${Z} of ${C}@${N} → ${te.state}`+(te.state===`present`?``:` (${te.detail})`)),te.state!==`present`;S++){let n=F-(W()-X);if(n<=0)break;await H(Math.min(backoffFor(S),n))}return{confirmed:te.state===`present`,attempts:Z,elapsedMs:W()-X,url:Y,last:te}}async function probeOnce(n){let{url:S,version:C,doFetch:N,probeTimeoutMs:F}=n,I=new AbortController,H=setTimeout(()=>I.abort(),F),W;try{W=await N(S,{headers:{accept:`application/vnd.npm.install-v1+json`,"cache-control":`no-cache`,...n.authorization?{authorization:n.authorization}:{}},signal:I.signal})}catch(n){return{state:`error`,detail:`request failed (${n instanceof Error?n.message:String(n)})`}}finally{clearTimeout(H)}if(W.status===404)return{state:`absent`,status:404,detail:`404 — the registry serves no packument for this name`};if(!W.ok)return{state:`error`,status:W.status,detail:`${W.status} ${W.statusText}`};let q;try{q=await W.json()}catch(n){let S=n instanceof Error?n.message:String(n);return{state:`error`,status:W.status,detail:`packument is not JSON (${S})`}}let Y=q?.versions,X=Y&&typeof Y==`object`?Object.keys(Y):[],Z=Y&&typeof Y==`object`?Y[C]:void 0;if(!Z){let n=X.length>0?X[X.length-1]:`(none)`;return{state:`absent`,status:W.status,detail:`packument carries ${X.length} version(s), newest ${n} — ${C} is not among them`}}let te=Z.dist?.tarball;return typeof te!=`string`||te.length===0?{state:`absent`,status:W.status,detail:`packument has ${C} but its \`dist.tarball\` is missing`}:{state:`present`,status:W.status,tarball:te}}function formatUnconfirmedPublish(n){let{name:S,version:C,putUrl:N,putStatus:F,putStatusText:I,payloadBytes:H,readback:W}=n,q=n.claim??`accepted`,Y=(W.elapsedMs/1e3).toFixed(1),X=W.last.state===`present`?`served`:W.last.detail,Z=q===`already-published`?`npm says ${C} is ALREADY PUBLISHED but the registry does not serve it.`:`npm ACCEPTED the upload but the registry does not serve it.`,te=q===`already-published`?[` A 409 is npm refusing to overwrite a version it holds, which is not the same as serving it: in`,` the v0.46.0 recovery @gjsify/node-runtime-darwin-arm64 was answered 409 at 09:48:49 and the`,` registry recorded 0.46.0 at 09:49:07, 18s later. Re-running answers the same 409, so it cannot`," fix this — wait and re-read (`npm view <name>@<version>`), or check https://status.npmjs.org/."]:[` A 2xx from npm is an ACCEPTED write, not a durable one. In the v0.46.0 release 19 of 199`,` packages were recorded by the registry 56-252s after their 2xx, and ONE was never recorded`,` at all while its job stayed green — that is the failure this check exists to name.`," Re-run this publish (`--tolerate-republish` no-ops if it landed meanwhile). If it keeps",` failing, the write was rejected downstream of the 2xx: check https://status.npmjs.org/.`];return[`gjsify publish: ${S}@${C} — ${Z}`,` PUT ${N} (${H} bytes) → ${F} ${I}`,` read-back GET ${W.url} (accept: application/vnd.npm.install-v1+json, cache-control: no-cache)`,` answered ${W.last.state}: ${X}`,` after ${W.attempts} probe(s) over ${Y}s`,...te].join(`
|
|
1130
|
+
`)}var jB,MB,NB,PB=__esmMin(()=>{np(),jB=[2e3,4e3,8e3,15e3,3e4],MB=2e3,NB=3e5});function beginPrompt(){FB++}function endPrompt(n=defaultWrite){if(FB=Math.max(0,FB-1),FB>0||IB.length===0)return;let S=IB.splice(0,IB.length);for(let C of S)n(C)}function writeAroundPrompt(n,S=defaultWrite){if(FB>0){IB.push(n);return}S(n)}function defaultWrite(n){process.stdout.write(n)}var FB,IB,LB=__esmMin(()=>{FB=0,IB=[]});function isTtyStdin(){let n=process.stdin;return!!n.isTTY&&typeof n.setRawMode==`function`}function applyKey(n,S,C){return S===`\r`||S===`
|
|
1127
1131
|
`?{buf:n,echo:`
|
|
1128
|
-
`,done:!0,interrupt:!1}:S===
|
|
1129
|
-
`,done:!1,interrupt:!0}:S===
|
|
1130
|
-
Enter OTP: `,
|
|
1131
|
-
Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(n,S=promptLine,C={}){this.promptFn=S,this.registry=C.registry;let N=n&&n.length>0?n:void 0;N?(this.cached=N,this.registry&&writeCachedOtp(this.registry,N)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(n,S){if(S!==void 0&&this.generation>S&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(n??(this.generation>0?jB:AB));try{return await this.pending}finally{this.pending=void 0}}async promptOnce(n){let S=(await this.promptFn(n)).trim();return S&&(this.cached=S,this.generation++,this.registry&&writeCachedOtp(this.registry,S)),S}invalidate(n){n!==void 0&&this.generation!==n||(this.cached=void 0,this.registry&&clearCachedOtp(this.registry))}}});async function publishWorkspace(n){let{wsDir:S,tag:C,access:N,provenance:F,tolerate:I,tolerateUntrustedNew:H,trustedFlag:W,verbose:q,json:Y,otpProvider:X}=n,Z=await packWorkspace(S,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:Y?`inherit-stderr`:`inherit`}),te=await packWorkspaceToBytes(S),ne=readFileSync(js(S,`package.json`),`utf-8`),re=await loadRewrittenManifest(S,JSON.parse(ne)),ie=await loadNpmrc(S),ae=n.registry??process.env.npm_config_registry??registryFor(Z.name,ie)??qf,oe=ae.endsWith(`/`)?ae.slice(0,-1):ae,se=`${oe}/${escapePackageName(Z.name)}`,Q=`${Z.name.includes(`/`)?Z.name.slice(Z.name.indexOf(`/`)+1):Z.name}-${Z.version}.tgz`,ce=buildPublishPayload({pkg:re,tag:C,access:N,tarballBytes:te,tarballUrl:`${oe}/${Z.name}/-/${Q}`,packed:{...Z,wireFilename:Q},provenance:F}),le=buildPublishHeaders(se,{npmrc:ie}),ue=W===!0||W===void 0&&hasGithubOidcEnv()&&!process.env.NODE_AUTH_TOKEN,de=`token`;if(ue)try{let{token:n,audience:S}=await getNpmTrustedToken({packageName:Z.name,registry:ae,log:q?n=>ve.error(n):void 0});le.authorization=`Bearer ${n}`,de=`oidc`,q&&ve.error(`gjsify publish: OIDC token obtained (audience=${S})`)}catch(n){if(n instanceof OidcExchangeError&&n.status===404&&/package not found/i.test(n.body)&&H)return{ok:!0,action:`skipped-untrusted-new`,name:Z.name,version:Z.version};if(W===!0)return{ok:!1,action:`oidc-failed`,name:Z.name,version:Z.version,error:n};if(!le.authorization)return{ok:!1,action:`oidc-no-token`,name:Z.name,version:Z.version,error:n};if(q){let S=n instanceof Error?n.message:String(n);ve.error(`gjsify publish: OIDC auto-detect failed (${S}) — falling back to token auth`)}}q&&(ve.error(`gjsify publish: PUT ${se} (${Z.name}@${Z.version})`),ve.error(` auth-mode: ${de}`),ve.error(` authorization: ${le.authorization?`(set)`:`(none)`}`),ve.error(` payload size: ${JSON.stringify(ce).length} bytes`));let fe=JSON.stringify(ce),doPut=n=>{let S={...le};return n&&(S[`npm-otp`]=n,S[`npm-auth-type`]=`legacy`),fetch(se,{method:`PUT`,headers:S,body:fe})},pe=await withOtpRetry(doPut,X,{seedFirstAttempt:n.seedOtpFirst});if(await isOtpChallenge(pe))return{ok:!1,action:`otp-required`,name:Z.name,version:Z.version,status:pe.status};if(pe.ok)return{ok:!0,action:`published`,name:Z.name,version:Z.version,filename:Z.filename,size:Z.size,integrity:Z.integrity,tag:C,registry:oe};let me=await pe.text().catch(()=>`<no body>`);if((pe.status===409||pe.status===403&&/previously published/i.test(me))&&I)return{ok:!0,action:`republish-tolerated`,name:Z.name,version:Z.version,status:pe.status};if(pe.status===404&&de===`token`&&is404DiagnosticCandidate(me)){let n=await diagnose404({packageName:Z.name,version:Z.version,registry:oe,npmrc:ie});if(n.reason!==`unknown`)return{ok:!1,action:`diagnostic`,name:Z.name,version:Z.version,status:404,diag:n}}return{ok:!1,action:`error`,name:Z.name,version:Z.version,status:pe.status,statusText:pe.statusText,text:me}}function reportPublishOutcome(n,S){switch(n.action){case`published`:{let C={ok:!0,name:n.name,version:n.version,filename:n.filename,size:n.size,integrity:n.integrity,tag:n.tag,registry:n.registry};S?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${n.name}@${n.version}\n`);return}case`republish-tolerated`:{let C={ok:!0,action:`republish-tolerated`,name:n.name,version:n.version,status:n.status};S?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${n.name}@${n.version} (already published, tolerated)\n`);return}case`skipped-untrusted-new`:S?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:n.name,version:n.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${n.name}@${n.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`otp-required`:return ve.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(n.error,n.name,S),process.exit(1);case`oidc-no-token`:{let C=n.error instanceof Error?n.error.message:String(n.error);return ve.error(`gjsify publish: OIDC token exchange failed for ${n.name} (${C}) and no fallback npm token is configured — refusing to publish without credentials.`),S&&process.stdout.write(`${JSON.stringify({ok:!1,name:n.name,version:n.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return S?process.stdout.write(`${JSON.stringify({ok:!1,name:n.name,version:n.version,status:404,diagnostic:n.diag.reason,username:n.diag.username},null,2)}\n`):process.stderr.write(`${n.diag.message}\n`),process.exit(1);case`error`:return ve.error(`gjsify publish: ${n.name}@${n.version} — ${n.status} ${n.statusText}`),ve.error(n.text),process.exit(1)}}async function packWorkspaceToBytes(n){let S=js(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),C=await packWorkspace(n,{destination:S,dryRun:!1,lifecycleScripts:[]});if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let N=new Uint8Array(readFileSync(C.absolutePath));try{(await Promise.resolve().then(()=>(Vl(),Rl))).rmSync(C.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(Vl(),Rl))).rmdirSync(S)}catch{}return N}async function loadRewrittenManifest(n,S){let C=js(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),N=await packWorkspace(n,{destination:C,dryRun:!1}),{rmSync:F}=await Promise.resolve().then(()=>(Vl(),Rl));if(!N.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:I,parseTar:H}=await Promise.resolve().then(()=>(UP(),HP)),W=new Uint8Array(readFileSync(N.absolutePath));F(C,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let q=await I(W);for(let n of H(q))if(n.name===`package/package.json`&&n.body)return JSON.parse(new TextDecoder().decode(n.body));return S}function buildPublishPayload(n){let{pkg:S,tag:C,access:N,tarballBytes:F,tarballUrl:I,packed:H,provenance:W}=n,q={...S,_id:`${H.name}@${H.version}`,dist:{integrity:H.integrity,shasum:H.shasum,tarball:I}};W&&(q._hasShrinkwrap=!1);let Y={_id:H.name,name:H.name,description:typeof S.description==`string`?S.description:``,"dist-tags":{[C]:H.version},versions:{[H.version]:q},readme:``,_attachments:{[H.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(F),length:F.byteLength}}};return N&&(Y.access=N),Y}function base64Encode(n){let S=``,C=32768;for(let N=0;N<n.length;N+=C)S+=String.fromCharCode(...n.subarray(N,N+C));return btoa(S)}function handleOidcFailure(n,S,C){if(n instanceof OidcUnavailableError){let N=`gjsify publish: OIDC not available — ${n.message}`;C?process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`oidc-unavailable`,reason:n.reason,message:n.message})}\n`):process.stderr.write(`${N}\n`);return}if(n instanceof OidcExchangeError){let N=n.status===401||n.status===403?`npm rejected the OIDC exchange (${n.status}) — check that ${S} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(S)}/access pointing at this workflow.`:n.message;if(C)process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`oidc-exchange`,status:n.status,body:n.body,claims:n.claims,message:n.message})}\n`);else if(process.stderr.write(`✗ ${S}: ${N}\n`),n.body&&process.stderr.write(` ↳ npm said: ${n.body.slice(0,300)}\n`),n.claims){let S=n.claims,C=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(n=>S[n]!==void 0).map(n=>`${n}=${JSON.stringify(S[n])}`).join(`, `);C&&process.stderr.write(` ↳ JWT claims npm received: ${C}\n`)}return}let N=n instanceof Error?n.message:String(n);C?process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`unknown`,message:N})}\n`):process.stderr.write(`✗ ${S}: ${N}\n`)}var NB,PB=__esmMin(()=>{ye(),Vl(),Dm(),Hs(),ep(),np(),gB(),vB(),yB(),aI(),MB(),EB(),NB={command:`publish [path]`,description:"Pack + upload the workspace at <path> (default: cwd) to its npm registry. Drop-in for `npm publish` with workspace:^ rewrite handled automatically.",builder:n=>n.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`tag`,{description:`Dist-tag to publish under. Default: latest.`,type:`string`,default:`latest`}).option(`access`,{description:"Package access — `public` or `restricted` (required for first publish of scoped packages on the public registry).",type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as the `npm-otp` header. Required for manual publishes from a 2FA-enabled account.",type:`string`}).option(`tolerate-republish`,{description:'Treat "version already published" as success — covers both classic 409 Conflict and the npm OIDC-path 403 Forbidden + `"previously published"` body shape. Matches yarn `--tolerate-republish`.',type:`boolean`,default:!1}).option(`tolerate-untrusted-new`,{description:'Skip (exit 0) when OIDC token exchange returns `package not found` AND no fallback token is configured — i.e. a never-before-published `@scope/<name>` whose Trusted Publisher entry hasn\'t been set up on npmjs.com yet. Without this flag, one un-bootstrapped new package breaks the entire serialized `gjsify foreach publish` loop. Pair with `--tolerate-republish` in CI release workflows so a fresh-merged package gracefully skips its first CI publish, leaving the manual-bootstrap step to a maintainer (see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap").',type:`boolean`,default:!1}).option(`provenance`,{description:`Pass-through flag — recorded in the payload but no signing happens (gjsify doesn't ship a sigstore signer yet).`,type:`boolean`,default:!1}).option(`dry-run`,{description:`Pack only, do not PUT.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit publish metadata as JSON on stdout.`,type:`boolean`,default:!1}).option(`trusted`,{description:"Authenticate via npm Trusted Publishing (OIDC): exchange the GitHub Actions id-token for a short-lived npm token. Pass `--trusted` to force this mode (errors if env vars missing). Omit to auto-detect: OIDC is used iff `ACTIONS_ID_TOKEN_REQUEST_URL`+`_TOKEN` are set AND no `_authToken` is present in the resolved npmrc; otherwise the long-lived token path is used. Requires the calling workflow to declare `permissions: id-token: write` AND the target package to have a Trusted Publisher configured on npmjs.com.",type:`boolean`,default:void 0}).option(`check-trusted`,{description:"Diagnostic mode: perform the OIDC id-token request + npm token exchange, report success/failure, then exit WITHOUT publishing. Useful as a bulk-verifier (e.g. via `gjsify foreach publish --check-trusted`) to confirm Trusted Publisher config across many packages.",type:`boolean`,default:!1}),handler:async n=>{let S=Os(n.path??process.cwd()),C=n.tag??`latest`,N=n.access,F=n.otp,I=n[`tolerate-republish`]===!0,H=n[`tolerate-untrusted-new`]===!0,W=n.provenance===!0,q=n[`dry-run`]===!0,Y=n[`check-trusted`]===!0,X=n.trusted,Z=!!process.env.GJSIFY_PUBLISH_DEBUG;if(W&&ve.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),Y){let C=js(S,`package.json`),N=JSON.parse(readFileSync(C,`utf-8`));if(typeof N.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${C} has no \`name\` field\n`),process.exit(2);if(N.private===!0){let S={ok:!0,action:`check-trusted`,name:N.name,skipped:`private`};n.json?process.stdout.write(`${JSON.stringify(S)}\n`):process.stdout.write(`- ${N.name}: skipped (private package)\n`);return}let F=await loadNpmrc(S),I=process.env.npm_config_registry??registryFor(N.name,F)??qf;try{await getNpmTrustedToken({packageName:N.name,registry:I,log:Z?n=>ve.error(n):void 0});let S={ok:!0,action:`check-trusted`,name:N.name,registry:I};n.json?process.stdout.write(`${JSON.stringify(S)}\n`):process.stdout.write(`✓ ${N.name}: trusted publisher OK\n`);return}catch(S){handleOidcFailure(S,N.name,n.json===!0);return}}if(q){let C=await packWorkspace(S,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:n.json?`inherit-stderr`:`inherit`}),N={ok:!0,action:`dry-run`,name:C.name,version:C.version,filename:C.filename,size:C.size,shasum:C.shasum,integrity:C.integrity};n.json?process.stdout.write(`${JSON.stringify(N,null,2)}\n`):process.stdout.write(`+ ${C.name}@${C.version} (dry-run, ${C.size} bytes, ${C.entryCount} files)\n`);return}let te=!!(process.stdin.isTTY&&process.stdout.isTTY),ne=await loadNpmrc(S),re;try{re=JSON.parse(readFileSync(js(S,`package.json`),`utf-8`)).name}catch{}let ie=process.env.npm_config_registry??(re?registryFor(re,ne):void 0)??ne.registry??qf,ae=new OtpProvider(F,te?promptLine:async()=>``,{registry:ie});reportPublishOutcome(await publishWorkspace({wsDir:S,tag:C,access:N,provenance:W,tolerate:I,tolerateUntrustedNew:H,trustedFlag:X,verbose:Z,json:n.json===!0,otpProvider:ae,seedOtpFirst:F!==void 0}),n.json===!0)}}}),FB,IB=__esmMin(()=>{ep(),aI(),FB={command:`whoami`,description:`Print the npm-registry username for the current ~/.npmrc token. Clear failure message when the token is dead, missing, or the registry is unreachable.`,builder:n=>n.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${qf}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async n=>{let S=await loadNpmrc(process.cwd()),C=n.registry??process.env.npm_config_registry??S.registry??qf,N=C.endsWith(`/`)?C.slice(0,-1):C,F=n.json===!0;if(!hasAnyCredential(S))return F?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:N})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${N}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
|
|
1132
|
+
`,done:!0,interrupt:!1}:S===RB?{buf:n,echo:`
|
|
1133
|
+
`,done:!1,interrupt:!0}:S===zB||S===BB?n.length>0?{buf:n.slice(0,-1),echo:`\b \b`,done:!1,interrupt:!1}:{buf:n,echo:``,done:!1,interrupt:!1}:S>=` `?{buf:n+S,echo:C?`*`:S,done:!1,interrupt:!1}:{buf:n,echo:``,done:!1,interrupt:!1}}async function runRawSession(n){let S=process.stdin,C=process.stdout,N=null,cleanup=()=>{S.removeListener(`data`,onData);try{S.setRawMode(!1)}catch{}typeof S.pause==`function`&&S.pause()},onData=n=>{let S=typeof n==`string`?n:n.toString(`utf-8`);for(let n of S){if(!N)continue;let S=applyKey(N.buf,n,N.mask);if(N.buf=S.buf,S.echo&&C.write(S.echo),S.interrupt)return cleanup(),process.exit(130);if(S.done){let{resolve:n}=N;N=null,n(S.buf)}}};S.setRawMode(!0),typeof S.resume==`function`&&S.resume(),S.setEncoding(`utf-8`),S.on(`data`,onData);let read=(n,S)=>new Promise(F=>{beginPrompt(),C.write(n),N={mask:S,buf:``,resolve:n=>{endPrompt(),F(n)}}});try{return await n(read)}finally{cleanup()}}function readLine(){return new Promise(n=>{let S=``,onData=C=>{S+=typeof C==`string`?C:C.toString(`utf-8`);let N=S.search(/[\r\n]/);N>=0&&(cleanup(),n(S.slice(0,N)))},onEnd=()=>{cleanup(),n(S.replace(/\r$/,``).trim())},cleanup=()=>{process.stdin.removeListener(`data`,onData),process.stdin.removeListener(`end`,onEnd)};process.stdin.setEncoding(`utf-8`),typeof process.stdin.isPaused==`function`&&process.stdin.isPaused()&&process.stdin.resume(),process.stdin.on(`data`,onData),process.stdin.once(`end`,onEnd)})}async function promptLine(n){if(!isTtyStdin()){beginPrompt(),process.stdout.write(n);try{return await readLine()}finally{endPrompt()}}return runRawSession(S=>S(n,!1))}async function promptCredentials(n){if(!isTtyStdin()){let S=n;S||=(process.stdout.write(`Username: `),await readLine()),process.stdout.write(`Password: `);let C=await readLine();return{username:S,password:C}}return runRawSession(async S=>({username:n??await S(`Username: `,!1),password:await S(`Password: `,!0)}))}var RB,zB,BB,VB=__esmMin(()=>{LB(),RB=``,zB=``,BB=`\b`});function isOtpCacheEnabled(){let n=process.env[HB];return!(n===`1`||n===`true`||n===`yes`)}function normalizeRegistry(n){return n.endsWith(`/`)?n.slice(0,-1):n}function cacheBaseDir(n){if(n?.dir)return n.dir;let S=process.env.XDG_RUNTIME_DIR;return js(S&&S.length>0?S:tmpdir(),UB)}function cacheFileFor(n,S){let C=normalizeRegistry(n).replace(/[^a-zA-Z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120);return js(cacheBaseDir(S),`otp-${C||`default`}.json`)}function readCachedOtp(n,S){if(!isOtpCacheEnabled())return;let C=S?.now??Date.now(),N=cacheFileFor(n,S);try{if(!existsSync(N))return;let S=JSON.parse(readFileSync(N,`utf8`));if(!S||typeof S.otp!=`string`||typeof S.expiresAt!=`number`){deleteCacheFile(N);return}if(S.registry!==normalizeRegistry(n))return;if(C>=S.expiresAt){deleteCacheFile(N);return}return S.otp.length>0?S.otp:void 0}catch{deleteCacheFile(N);return}}function writeCachedOtp(n,S,C){if(!isOtpCacheEnabled()||!S||S.length===0)return;let N=C?.now??Date.now(),F=C?.ttlMs??3e4;try{mkdirSync(cacheBaseDir(C),{recursive:!0,mode:448});let I=cacheFileFor(n,C),H={otp:S,expiresAt:N+F,registry:normalizeRegistry(n)};writeFileSync(I,JSON.stringify(H),{mode:384}),chmodSync(I,384)}catch{}}function clearCachedOtp(n,S){deleteCacheFile(cacheFileFor(n,S))}function deleteCacheFile(n){try{existsSync(n)&&rmSync(n,{force:!0})}catch{}}var HB,UB,WB=__esmMin(()=>{Vl(),Dm(),Hs(),HB=`GJSIFY_NO_OTP_CACHE`,UB=`gjsify-otp`});async function isOtpChallenge(n){if(n.status!==401)return!1;if((n.headers.get(`www-authenticate`)??``).toLowerCase().includes(`otp`))return!0;let S=await n.clone().text().catch(()=>``);return/one-time pass/i.test(S)||/\bEOTP\b/.test(S)}async function withOtpRetry(n,S,C={}){let N=C.maxPrompts??2,F=C.question,I=S.current(),H=C.seedFirstAttempt===!0&&I!==void 0,W=S.epoch(),q=await n(H?I:void 0);if(!await isOtpChallenge(q))return q;if(H&&S.invalidate(W),!H&&S.current()!==void 0){if(W=S.epoch(),q=await n(S.current()),!await isOtpChallenge(q))return q;S.invalidate(W)}for(let C=0;C<N;C++){let C=await S.refresh(F,W);if(!C||(W=S.epoch(),q=await n(C),!await isOtpChallenge(q)))return q;S.invalidate(W)}return q}var GB,KB,OtpProvider,qB=__esmMin(()=>{VB(),WB(),GB=`This operation requires a one-time password.
|
|
1134
|
+
Enter OTP: `,KB=`The previous one-time password is no longer valid (npm codes last about 30 seconds).
|
|
1135
|
+
Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pending;constructor(n,S=promptLine,C={}){this.promptFn=S,this.registry=C.registry;let N=n&&n.length>0?n:void 0;N?(this.cached=N,this.registry&&writeCachedOtp(this.registry,N)):this.cached=this.registry?readCachedOtp(this.registry):void 0}current(){return this.cached}epoch(){return this.generation}async refresh(n,S){if(S!==void 0&&this.generation>S&&this.cached)return this.cached;if(this.pending)return this.pending;this.pending=this.promptOnce(n??(this.generation>0?KB:GB));try{return await this.pending}finally{this.pending=void 0}}async promptOnce(n){let S=(await this.promptFn(n)).trim();return S&&(this.cached=S,this.generation++,this.registry&&writeCachedOtp(this.registry,S)),S}invalidate(n){n!==void 0&&this.generation!==n||(this.cached=void 0,this.registry&&clearCachedOtp(this.registry))}}});async function publishWorkspace(n){let{wsDir:S,tag:C,access:N,provenance:F,tolerate:I,tolerateUntrustedNew:H,trustedFlag:W,verbose:q,json:Y,otpProvider:X}=n,Z=await packWorkspace(S,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:Y?`inherit-stderr`:`inherit`}),te=await packWorkspaceToBytes(S),ne=readFileSync(js(S,`package.json`),`utf-8`),re=await loadRewrittenManifest(S,JSON.parse(ne)),ie=await loadNpmrc(S),ae=n.registry??process.env.npm_config_registry??registryFor(Z.name,ie)??qf,oe=ae.endsWith(`/`)?ae.slice(0,-1):ae,se=`${oe}/${escapePackageName(Z.name)}`,Q=`${Z.name.includes(`/`)?Z.name.slice(Z.name.indexOf(`/`)+1):Z.name}-${Z.version}.tgz`,ce=buildPublishPayload({pkg:re,tag:C,access:N,tarballBytes:te,tarballUrl:`${oe}/${Z.name}/-/${Q}`,packed:{...Z,wireFilename:Q},provenance:F}),le=buildPublishHeaders(se,{npmrc:ie}),ue=W===!0||W===void 0&&hasGithubOidcEnv()&&!process.env.NODE_AUTH_TOKEN,de=`token`;if(ue)try{let{token:n,audience:S}=await getNpmTrustedToken({packageName:Z.name,registry:ae,log:q?n=>ve.error(n):void 0});le.authorization=`Bearer ${n}`,de=`oidc`,q&&ve.error(`gjsify publish: OIDC token obtained (audience=${S})`)}catch(n){if(n instanceof OidcExchangeError&&n.status===404&&/package not found/i.test(n.body)&&H)return{ok:!0,action:`skipped-untrusted-new`,name:Z.name,version:Z.version};if(W===!0)return{ok:!1,action:`oidc-failed`,name:Z.name,version:Z.version,error:n};if(!le.authorization)return{ok:!1,action:`oidc-no-token`,name:Z.name,version:Z.version,error:n};if(q){let S=n instanceof Error?n.message:String(n);ve.error(`gjsify publish: OIDC auto-detect failed (${S}) — falling back to token auth`)}}q&&(ve.error(`gjsify publish: PUT ${se} (${Z.name}@${Z.version})`),ve.error(` auth-mode: ${de}`),ve.error(` authorization: ${le.authorization?`(set)`:`(none)`}`),ve.error(` payload size: ${JSON.stringify(ce).length} bytes`));let fe=JSON.stringify(ce),doPut=n=>{let S={...le};return n&&(S[`npm-otp`]=n,S[`npm-auth-type`]=`legacy`),fetch(se,{method:`PUT`,headers:S,body:fe})},pe=await withOtpRetry(doPut,X,{seedFirstAttempt:n.seedOtpFirst});if(q){ve.error(` response: ${pe.status} ${pe.statusText}`);let n=await pe.clone().text().catch(()=>``);n&&ve.error(` body: ${n.slice(0,300)}`)}let readBack=async()=>{let S=n.verifyBudgetMs??3e5;if(!(S<=0))return verifyPublishedVersion({registry:oe,name:Z.name,version:Z.version,budgetMs:S,authorization:le.authorization,log:q?n=>ve.error(n):void 0})};if(await isOtpChallenge(pe))return{ok:!1,action:`otp-required`,name:Z.name,version:Z.version,status:pe.status};if(pe.ok){let n=await readBack();return n?.confirmed&&q&&ve.error(` read-back: confirmed after ${n.attempts} probe(s) in ${n.elapsedMs} ms`),n&&!n.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`accepted`,name:Z.name,version:Z.version,registry:oe,putStatus:pe.status,putStatusText:pe.statusText,putUrl:se,payloadBytes:fe.length,readback:n}:{ok:!0,action:`published`,name:Z.name,version:Z.version,filename:Z.filename,size:Z.size,integrity:Z.integrity,tag:C,registry:oe,readback:n}}let me=await pe.text().catch(()=>`<no body>`);if((pe.status===409||pe.status===403&&/previously published/i.test(me))&&I){let n=await readBack();return n&&!n.confirmed?{ok:!1,action:`publish-unconfirmed`,claim:`already-published`,name:Z.name,version:Z.version,registry:oe,putStatus:pe.status,putStatusText:pe.statusText,putUrl:se,payloadBytes:fe.length,readback:n}:{ok:!0,action:`republish-tolerated`,name:Z.name,version:Z.version,status:pe.status,readback:n}}if(pe.status===404&&de===`token`&&is404DiagnosticCandidate(me)){let n=await diagnose404({packageName:Z.name,version:Z.version,registry:oe,npmrc:ie});if(n.reason!==`unknown`)return{ok:!1,action:`diagnostic`,name:Z.name,version:Z.version,status:404,diag:n}}return{ok:!1,action:`error`,name:Z.name,version:Z.version,status:pe.status,statusText:pe.statusText,text:me}}function reportPublishOutcome(n,S,C=!1){switch(n.action){case`published`:{let C={ok:!0,name:n.name,version:n.version,filename:n.filename,size:n.size,integrity:n.integrity,tag:n.tag,registry:n.registry};S?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`+ ${n.name}@${n.version}\n`);return}case`publish-unconfirmed`:{let N=formatUnconfirmedPublish(n);if(S?process.stdout.write(`${JSON.stringify({ok:!1,action:`publish-unconfirmed`,name:n.name,version:n.version,registry:n.registry,claim:n.claim,putStatus:n.putStatus,probes:n.readback.attempts,elapsedMs:n.readback.elapsedMs,readbackUrl:n.readback.url,readbackState:n.readback.last.state,deferred:C},null,2)}\n`):process.stderr.write(`${N}\n`),C){if(process.env.GITHUB_ACTIONS){let S=n.claim===`already-published`?`was reported already published`:`was accepted`;process.stderr.write(`::warning title=Publish unconfirmed::${n.name}@${n.version} ${S} (HTTP ${n.putStatus}) but did not resolve on ${n.registry} within ${(n.readback.elapsedMs/1e3).toFixed(1)}s — the release-closure job must confirm it\n`)}return}return process.exit(1)}case`republish-tolerated`:{let C={ok:!0,action:`republish-tolerated`,name:n.name,version:n.version,status:n.status};S?process.stdout.write(`${JSON.stringify(C,null,2)}\n`):process.stdout.write(`= ${n.name}@${n.version} (already published, tolerated)\n`);return}case`skipped-untrusted-new`:S?process.stdout.write(`${JSON.stringify({ok:!0,action:`skipped-untrusted-new`,name:n.name,version:n.version,reason:`no-trusted-publisher`},null,2)}\n`):process.stdout.write(`~ ${n.name}@${n.version} (skipped — no Trusted Publisher on npm, see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap")\n`);return;case`otp-required`:return ve.error("gjsify publish: npm requires a 2FA one-time code — re-run with `--otp <code>`"),process.exit(1);case`oidc-failed`:return handleOidcFailure(n.error,n.name,S),process.exit(1);case`oidc-no-token`:{let C=n.error instanceof Error?n.error.message:String(n.error);return ve.error(`gjsify publish: OIDC token exchange failed for ${n.name} (${C}) and no fallback npm token is configured — refusing to publish without credentials.`),S&&process.stdout.write(`${JSON.stringify({ok:!1,name:n.name,version:n.version,error:`oidc-failed-no-token`},null,2)}\n`),process.exit(1)}case`diagnostic`:return S?process.stdout.write(`${JSON.stringify({ok:!1,name:n.name,version:n.version,status:404,diagnostic:n.diag.reason,username:n.diag.username},null,2)}\n`):process.stderr.write(`${n.diag.message}\n`),process.exit(1);case`error`:return ve.error(`gjsify publish: ${n.name}@${n.version} — ${n.status} ${n.statusText}`),ve.error(n.text),process.exit(1)}}async function packWorkspaceToBytes(n){let S=js(tmpdir(),`gjsify-publish-${process.pid}-${Date.now()}`),C=await packWorkspace(n,{destination:S,dryRun:!1,lifecycleScripts:[]});if(!C.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let N=new Uint8Array(readFileSync(C.absolutePath));try{(await Promise.resolve().then(()=>(Vl(),Rl))).rmSync(C.absolutePath)}catch{}try{(await Promise.resolve().then(()=>(Vl(),Rl))).rmdirSync(S)}catch{}return N}async function loadRewrittenManifest(n,S){let C=js(tmpdir(),`gjsify-publish-manifest-${process.pid}-${Date.now()}`),N=await packWorkspace(n,{destination:C,dryRun:!1}),{rmSync:F}=await Promise.resolve().then(()=>(Vl(),Rl));if(!N.absolutePath)throw Error(`gjsify publish: pack did not produce a file`);let{gunzip:I,parseTar:H}=await Promise.resolve().then(()=>(WP(),UP)),W=new Uint8Array(readFileSync(N.absolutePath));F(C,{recursive:!0,force:!0,maxRetries:3,retryDelay:100});let q=await I(W);for(let n of H(q))if(n.name===`package/package.json`&&n.body)return JSON.parse(new TextDecoder().decode(n.body));return S}function buildPublishPayload(n){let{pkg:S,tag:C,access:N,tarballBytes:F,tarballUrl:I,packed:H,provenance:W}=n,q={...S,_id:`${H.name}@${H.version}`,dist:{integrity:H.integrity,shasum:H.shasum,tarball:I}};W&&(q._hasShrinkwrap=!1);let Y={_id:H.name,name:H.name,description:typeof S.description==`string`?S.description:``,"dist-tags":{[C]:H.version},versions:{[H.version]:q},readme:``,_attachments:{[H.wireFilename]:{content_type:`application/octet-stream`,data:base64Encode(F),length:F.byteLength}}};return N&&(Y.access=N),Y}function handleOidcFailure(n,S,C){if(n instanceof OidcUnavailableError){let N=`gjsify publish: OIDC not available — ${n.message}`;C?process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`oidc-unavailable`,reason:n.reason,message:n.message})}\n`):process.stderr.write(`${N}\n`);return}if(n instanceof OidcExchangeError){let N=n.status===401||n.status===403?`npm rejected the OIDC exchange (${n.status}) — check that ${S} has a Trusted Publisher configured at https://www.npmjs.com/package/${encodeURIComponent(S)}/access pointing at this workflow.`:n.message;if(C)process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`oidc-exchange`,status:n.status,body:n.body,claims:n.claims,message:n.message})}\n`);else if(process.stderr.write(`✗ ${S}: ${N}\n`),n.body&&process.stderr.write(` ↳ npm said: ${n.body.slice(0,300)}\n`),n.claims){let S=n.claims,C=[`aud`,`iss`,`repository`,`repository_owner`,`workflow_ref`,`job_workflow_ref`,`ref`,`environment`,`sub`].filter(n=>S[n]!==void 0).map(n=>`${n}=${JSON.stringify(S[n])}`).join(`, `);C&&process.stderr.write(` ↳ JWT claims npm received: ${C}\n`)}return}let N=n instanceof Error?n.message:String(n);C?process.stdout.write(`${JSON.stringify({ok:!1,name:S,error:`unknown`,message:N})}\n`):process.stderr.write(`✗ ${S}: ${N}\n`)}var JB,YB=__esmMin(()=>{ye(),Vl(),Dm(),Hs(),Iz(),ep(),np(),DB(),kB(),AB(),PB(),oI(),qB(),VB(),JB={command:`publish [path]`,description:"Pack + upload the workspace at <path> (default: cwd) to its npm registry. Drop-in for `npm publish` with workspace:^ rewrite handled automatically.",builder:n=>n.positional(`path`,{description:`Workspace path (default: cwd).`,type:`string`}).option(`tag`,{description:`Dist-tag to publish under. Default: latest.`,type:`string`,default:`latest`}).option(`access`,{description:"Package access — `public` or `restricted` (required for first publish of scoped packages on the public registry).",type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as the `npm-otp` header. Required for manual publishes from a 2FA-enabled account.",type:`string`}).option(`tolerate-republish`,{description:'Treat "version already published" as success — covers both classic 409 Conflict and the npm OIDC-path 403 Forbidden + `"previously published"` body shape. Matches yarn `--tolerate-republish`.',type:`boolean`,default:!1}).option(`tolerate-untrusted-new`,{description:'Skip (exit 0) when OIDC token exchange returns `package not found` AND no fallback token is configured — i.e. a never-before-published `@scope/<name>` whose Trusted Publisher entry hasn\'t been set up on npmjs.com yet. Without this flag, one un-bootstrapped new package breaks the entire serialized `gjsify foreach publish` loop. Pair with `--tolerate-republish` in CI release workflows so a fresh-merged package gracefully skips its first CI publish, leaving the manual-bootstrap step to a maintainer (see AGENTS.md "New @gjsify/* package: first-publish + Trusted Publisher bootstrap").',type:`boolean`,default:!1}).option(`verify-timeout`,{description:"Seconds to keep asking the registry for the just-published version before giving up. npm answers 2xx to a write it has only ACCEPTED: in the v0.46.0 release 19 of 199 packages were recorded 56-252s after their 2xx and one was never recorded at all, so a shorter window turns normal queueing into a false red. `0` disables the read-back — for a registry with no packument read path.",type:`number`,default:NB/1e3}).option(`verify-defer`,{description:"Report an unconfirmed read-back and exit 0 instead of 1. ONLY for a caller that re-checks the same set afterwards — `gjsify run npm:publish` passes it because `scripts/verify-published-closure.mjs` sweeps the whole roster at the end of release.yml. Everywhere else an unconfirmed publish must fail the job that made it.",type:`boolean`,default:!1}).option(`provenance`,{description:`Pass-through flag — recorded in the payload but no signing happens (gjsify doesn't ship a sigstore signer yet).`,type:`boolean`,default:!1}).option(`dry-run`,{description:`Pack only, do not PUT.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit publish metadata as JSON on stdout.`,type:`boolean`,default:!1}).option(`trusted`,{description:"Authenticate via npm Trusted Publishing (OIDC): exchange the GitHub Actions id-token for a short-lived npm token. Pass `--trusted` to force this mode (errors if env vars missing). Omit to auto-detect: OIDC is used iff `ACTIONS_ID_TOKEN_REQUEST_URL`+`_TOKEN` are set AND no `_authToken` is present in the resolved npmrc; otherwise the long-lived token path is used. Requires the calling workflow to declare `permissions: id-token: write` AND the target package to have a Trusted Publisher configured on npmjs.com.",type:`boolean`,default:void 0}).option(`check-trusted`,{description:"Diagnostic mode: perform the OIDC id-token request + npm token exchange, report success/failure, then exit WITHOUT publishing. Useful as a bulk-verifier (e.g. via `gjsify foreach publish --check-trusted`) to confirm Trusted Publisher config across many packages.",type:`boolean`,default:!1}),handler:async n=>{let S=Os(n.path??process.cwd()),C=n.tag??`latest`,N=n.access,F=n.otp,I=n[`tolerate-republish`]===!0,H=n[`tolerate-untrusted-new`]===!0,W=n[`verify-timeout`]??3e5/1e3;if(!Number.isFinite(W)||W<0)return ve.error(`gjsify publish: --verify-timeout must be a non-negative number of seconds, got ${JSON.stringify(n[`verify-timeout`])}`),process.exit(2);let q=Math.round(W*1e3),Y=n[`verify-defer`]===!0,X=n.provenance===!0,Z=n[`dry-run`]===!0,te=n[`check-trusted`]===!0,ne=n.trusted,re=!!process.env.GJSIFY_PUBLISH_DEBUG;if(X&&ve.warn(`gjsify publish: --provenance recorded but not signed (no sigstore integration yet).`),te){let C=js(S,`package.json`),N=JSON.parse(readFileSync(C,`utf-8`));if(typeof N.name!=`string`)return process.stderr.write(`gjsify publish --check-trusted: ${C} has no \`name\` field\n`),process.exit(2);if(N.private===!0){let S={ok:!0,action:`check-trusted`,name:N.name,skipped:`private`};n.json?process.stdout.write(`${JSON.stringify(S)}\n`):process.stdout.write(`- ${N.name}: skipped (private package)\n`);return}let F=await loadNpmrc(S),I=process.env.npm_config_registry??registryFor(N.name,F)??qf;try{await getNpmTrustedToken({packageName:N.name,registry:I,log:re?n=>ve.error(n):void 0});let S={ok:!0,action:`check-trusted`,name:N.name,registry:I};n.json?process.stdout.write(`${JSON.stringify(S)}\n`):process.stdout.write(`✓ ${N.name}: trusted publisher OK\n`);return}catch(S){handleOidcFailure(S,N.name,n.json===!0);return}}if(Z){let C=await packWorkspace(S,{dryRun:!0,lifecycleScripts:[`prepublishOnly`,`prepack`],lifecycleStdio:n.json?`inherit-stderr`:`inherit`}),N={ok:!0,action:`dry-run`,name:C.name,version:C.version,filename:C.filename,size:C.size,shasum:C.shasum,integrity:C.integrity};n.json?process.stdout.write(`${JSON.stringify(N,null,2)}\n`):process.stdout.write(`+ ${C.name}@${C.version} (dry-run, ${C.size} bytes, ${C.entryCount} files)\n`);return}let ie=!!(process.stdin.isTTY&&process.stdout.isTTY),ae=await loadNpmrc(S),oe;try{oe=JSON.parse(readFileSync(js(S,`package.json`),`utf-8`)).name}catch{}let se=process.env.npm_config_registry??(oe?registryFor(oe,ae):void 0)??ae.registry??qf,Q=new OtpProvider(F,ie?promptLine:async()=>``,{registry:se});reportPublishOutcome(await publishWorkspace({wsDir:S,tag:C,access:N,provenance:X,tolerate:I,tolerateUntrustedNew:H,trustedFlag:ne,verbose:re,json:n.json===!0,otpProvider:Q,seedOtpFirst:F!==void 0,verifyBudgetMs:q}),n.json===!0,Y)}}}),XB,ZB=__esmMin(()=>{ep(),oI(),XB={command:`whoami`,description:`Print the npm-registry username for the current ~/.npmrc token. Clear failure message when the token is dead, missing, or the registry is unreachable.`,builder:n=>n.option(`registry`,{description:`Registry URL to probe. Default: scope-aware lookup from .npmrc (falls back to ${qf}).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` (or `{error, registry}`) as a single-line JSON object.",type:`boolean`,default:!1}),handler:async n=>{let S=await loadNpmrc(process.cwd()),C=n.registry??process.env.npm_config_registry??S.registry??qf,N=C.endsWith(`/`)?C.slice(0,-1):C,F=n.json===!0;if(!hasAnyCredential(S))return F?process.stdout.write(`${JSON.stringify({error:`no-token-configured`,registry:N})}\n`):process.stderr.write([`gjsify whoami: no npm token configured.`,``,`No \`_authToken\` found in ~/.npmrc / $NPM_CONFIG_USERCONFIG / .npmrc for ${N}.`,``,`Add one via: npm login`,`Then verify: gjsify whoami`].join(`
|
|
1132
1136
|
`)+`
|
|
1133
1137
|
`),process.exit(1);let I;try{I=await whoami(C,S)}catch(n){let S=n instanceof Error?n.message:String(n);return F?process.stdout.write(`${JSON.stringify({error:S,registry:N})}\n`):(process.stderr.write(`gjsify whoami: ${S}\n`),process.stderr.write(`Registry: ${N}\n`)),process.exit(1)}if(I.username&&I.username.length>0){F?process.stdout.write(`${JSON.stringify({username:I.username,registry:N})}\n`):(process.stdout.write(`Logged in as: ${I.username}\n`),process.stdout.write(`Registry: ${N}\n`));return}F?process.stdout.write(`${JSON.stringify({error:`dead-token`,registry:N})}\n`):process.stderr.write([`gjsify whoami: token appears dead or revoked (registry returned an empty whoami response).`,``,`Refresh via: npm login`,`Then verify: gjsify whoami`,``,`For the @gjsify scope, see AGENTS.md > "New @gjsify/* package: first-publish + Trusted Publisher bootstrap".`].join(`
|
|
1134
1138
|
`)+`
|
|
@@ -1137,12 +1141,12 @@ Enter a NEW OTP: `,OtpProvider=class{cached;promptFn;registry;generation=0;pendi
|
|
|
1137
1141
|
`)+`
|
|
1138
1142
|
`),C}function removeAuthToken(n){let S=userconfigNpmrcPath(),C=authTokenKey(n),N=readUserconfig(S);if(!N)return{path:S,removed:!1};let F=N.split(`
|
|
1139
1143
|
`),I=F.filter(n=>!n.replace(/\s+/g,``).startsWith(`${C}=`)),H=I.length!==F.length;return H&&writeUserconfig(S,I.join(`
|
|
1140
|
-
`)),{path:S,removed:H}}var
|
|
1141
|
-
Enter OTP: `),!X)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(N,X),Z=await putUser(``,X)}}if(Z.status===409){let n=await fetch(`${W}?write=true`,{headers:authHeaders(X)});if(n.ok){let S=await n.json().catch(()=>({}));for(let n of Object.keys(S))(!q[n]||n===`roles`)&&(q[n]=S[n]);q._rev&&(Z=await putUser(`/-rev/${q._rev}`,X))}}if(Z.status===400)throw new LoginError(`gjsify login: there is no user with the username "${F}" on ${N}.`);if(!Z.ok){let n=await Z.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${Z.status} ${Z.statusText} from ${N}\n${n.slice(0,400)}`)}let te=await Z.json().catch(()=>({}));if(!te.token)throw new LoginError("gjsify login: the registry accepted the login but returned no token (unexpected response shape). Your registry may require the web-OAuth flow — use `npm login`.");let ne=writeAuthToken(N,te.token);return X&&writeCachedOtp(N,X),{username:(await whoami(N,await loadNpmrc(n.cwd??process.cwd()))).username??F,registry:N,npmrcPath:ne}}var LoginError,
|
|
1142
|
-
`)[0].slice(0,200)}var
|
|
1144
|
+
`)),{path:S,removed:H}}var QB=__esmMin(()=>{Vl(),Dm(),Hs()});async function runLogin(n){let S=await loadNpmrc(n.cwd??process.cwd()),C=n.registry??process.env.npm_config_registry??(n.scope?registryFor(n.scope.startsWith(`@`)?`${n.scope}/_`:`@${n.scope}/_`,S):void 0)??qf,N=C.endsWith(`/`)?C:`${C}/`,{username:F,password:I}=await promptCredentials(n.username);if(!F)throw new LoginError(`gjsify login: a username is required.`);if(!I)throw new LoginError(`gjsify login: a password is required.`);let H=`Basic ${btoa(`${F}:${I}`)}`,W=`${N}-/user/org.couchdb.user:${encodeURIComponent(F)}`,q={_id:`org.couchdb.user:${F}`,name:F,password:I,type:`user`,roles:[],date:void 0};function authHeaders(n){let S={authorization:H,"content-type":`application/json`,accept:`*/*`};return n&&(S[`npm-otp`]=n),S}async function putUser(n,S){return fetch(`${W}${n}`,{method:`PUT`,headers:authHeaders(S),body:JSON.stringify(q)})}let Y=typeof n.otp==`string`&&n.otp.length>0,X=n.otp??readCachedOtp(N),Z=await putUser(``,X);if(Z.status===401&&!Y){let n=(Z.headers.get(`www-authenticate`)??``).toLowerCase(),S=await Z.clone().text().catch(()=>``);if(n.includes(`otp`)||/one-time pass/i.test(S)){if(clearCachedOtp(N),X=await promptLine(`This operation requires a one-time password.
|
|
1145
|
+
Enter OTP: `),!X)throw new LoginError(`gjsify login: no OTP entered.`);writeCachedOtp(N,X),Z=await putUser(``,X)}}if(Z.status===409){let n=await fetch(`${W}?write=true`,{headers:authHeaders(X)});if(n.ok){let S=await n.json().catch(()=>({}));for(let n of Object.keys(S))(!q[n]||n===`roles`)&&(q[n]=S[n]);q._rev&&(Z=await putUser(`/-rev/${q._rev}`,X))}}if(Z.status===400)throw new LoginError(`gjsify login: there is no user with the username "${F}" on ${N}.`);if(!Z.ok){let n=await Z.text().catch(()=>`<no body>`);throw new LoginError(`gjsify login: ${Z.status} ${Z.statusText} from ${N}\n${n.slice(0,400)}`)}let te=await Z.json().catch(()=>({}));if(!te.token)throw new LoginError("gjsify login: the registry accepted the login but returned no token (unexpected response shape). Your registry may require the web-OAuth flow — use `npm login`.");let ne=writeAuthToken(N,te.token);return X&&writeCachedOtp(N,X),{username:(await whoami(N,await loadNpmrc(n.cwd??process.cwd()))).username??F,registry:N,npmrcPath:ne}}var LoginError,$B,eV=__esmMin(()=>{ye(),ep(),oI(),QB(),VB(),WB(),LoginError=class extends Error{constructor(n){super(n),this.name=`LoginError`}},$B={command:`login`,description:"Log in to an npm registry (Node-free `npm login`). Prompts for username + password (hidden) and writes the token to ~/.npmrc. Use --otp for 2FA. Web-OAuth flow is not supported — this is npm's legacy credentials flow.",builder:n=>n.option(`registry`,{description:`Registry URL to log in to. Default: ${qf} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Associate the login with a scope (e.g. @gjsify) — resolves that scope's registry from .npmrc.`,type:`string`}).option(`username`,{description:`Username (prompted if omitted).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code (prompted on demand if omitted).`,type:`string`}).option(`json`,{description:"Emit `{username, registry}` JSON on success.",type:`boolean`}),handler:async n=>{try{let{username:S,registry:C,npmrcPath:N}=await runLogin({registry:n.registry,scope:n.scope,username:n.username,otp:n.otp});n.json?process.stdout.write(`${JSON.stringify({username:S,registry:C})}\n`):process.stdout.write(`Logged in as ${S} on ${C}\n(token written to ${N})\n`)}catch(n){if(n instanceof LoginError)return ve.error(n.message),process.exit(1);throw n}}}}),tV,nV=__esmMin(()=>{ep(),oI(),QB(),WB(),tV={command:`logout`,description:"Log out of an npm registry (Node-free `npm logout`). Revokes the token on the registry (best-effort) and removes it from ~/.npmrc.",builder:n=>n.option(`registry`,{description:`Registry URL to log out of. Default: ${qf} (or a --scope's registry).`,type:`string`}).option(`scope`,{description:`Log out of a scope's registry (e.g. @gjsify) — resolved from .npmrc.`,type:`string`}).option(`json`,{description:"Emit `{registry, revoked, removed}` JSON.",type:`boolean`}),handler:async n=>{let S=await loadNpmrc(process.cwd()),C=n.registry??process.env.npm_config_registry??(n.scope?registryFor(n.scope.startsWith(`@`)?`${n.scope}/_`:`@${n.scope}/_`,S):void 0)??qf,N=C.endsWith(`/`)?C:`${C}/`,F=resolveAuthForUrl(`${N}-/whoami`,S),I=!1;if(F?.startsWith(`Bearer `)){let n=F.slice(7);try{I=(await fetch(`${N}-/user/token/${encodeURIComponent(n)}`,{method:`DELETE`,headers:{authorization:F,accept:`*/*`}})).ok}catch{}}clearCachedOtp(N);let{path:H,removed:W}=removeAuthToken(N);n.json?process.stdout.write(`${JSON.stringify({registry:N,revoked:I,removed:W})}\n`):W?process.stdout.write(`Logged out of ${N}${I?` (token revoked)`:``}\n(removed from ${H})\n`):process.stdout.write(`No token for ${N} found in ${H} — nothing to remove.\n`)}}});function discoverNonWorkspacePublishables(n){let S=n,C=rV[0];for(let n=0;n<8&&!existsSync(js(S,...C));n++){let n=Ps(S);if(n===S)return[];S=n}let N=[];for(let n of rV){let C=js(S,...n);if(!existsSync(C))continue;let F;try{F=readdirSync(C,{withFileTypes:!0})}catch{continue}for(let S of F){if(!S.isDirectory())continue;let F=js(C,S.name),I=js(F,`package.json`);if(existsSync(I))try{let C=JSON.parse(readFileSync(I,`utf8`));if(!C||typeof C.name!=`string`||C.name.length===0)continue;N.push({location:F,relativeLocation:js(...n,S.name),name:C.name,version:typeof C.version==`string`?C.version:`0.0.0`,manifest:C,private:C.private===!0})}catch{}}}return N}function mergePublishables(n,S){let C=new Set(n.map(n=>n.name));return[...n,...discoverNonWorkspacePublishables(S).filter(n=>!C.has(n.name))]}var rV,iV=__esmMin(()=>{Vl(),Hs(),rV=[[`packages`,`node-gi`],[`packages`,`napi`],[`packages`,`node-runtime`]]});function trustUrl(n,S){return`${n.endsWith(`/`)?n.slice(0,-1):n}/-/package/${escapePackageName(S)}/trust`}function githubTrustBody(n){let S={repository:n.repository,workflow_ref:{file:normalizeWorkflowFile(n.workflow)}};return n.environment&&(S.environment=n.environment),[{type:`github`,claims:S,permissions:n.permissions&&n.permissions.length>0?n.permissions:[aV]}]}function normalizeWorkflowFile(n){return n.split(`/`).pop()??n}function validateRepository(n){let S=n.split(`/`);return S.length===2&&S[0].length>0&&S[1].length>0}function matchesGithubTrust(n,S){if(n.type!==`github`)return!1;let C=n.claims?.repository,N=n.claims?.workflow_ref?.file;return C===S.repository&&N===normalizeWorkflowFile(S.workflow)}function classifyTrustList(n,S,C){return n===404?`unpublished`:n===401?`auth-required`:n>=200&&n<300?(Array.isArray(S)?S:[]).some(n=>matchesGithubTrust(n,C))?`trusted`:`untrusted`:`error`}function parseRepoFromGitRemote(n){let S=n.trim();if(!S)return null;S=S.replace(/^git\+/,``),S=S.replace(/\.git$/,``);let C=S.match(/^[^/@]+@[^:]+:(.+)$/);if(C)return twoSegments(C[1]);let N=S.match(/^[a-z]+:\/\/[^/]+\/(.+)$/i);return N?twoSegments(N[1]):null}function twoSegments(n){let S=n.split(`/`).filter(n=>n.length>0);return S.length<2?null:`${S[S.length-2]}/${S[S.length-1]}`}var aV,oV=__esmMin(()=>{np(),aV=`createPackage`});function createTrustRequester(n){return async(S,C,N)=>{let doFetch=F=>{let I=buildHeaders(C,{npmrc:n.npmrc});I.accept=`application/json`,N!==void 0&&(I[`content-type`]=`application/json`),F&&(I[`npm-otp`]=F);let H={method:S,headers:I};return N!==void 0&&(H.body=JSON.stringify(N)),fetch(C,H)},F=await withOtpRetry(doFetch,n.otpProvider),I=await F.text().catch(()=>``),H;try{H=I?JSON.parse(I):void 0}catch{}return{status:F.status,json:H,text:I,headers:F.headers}}}function firstLine(n){return n.split(`
|
|
1146
|
+
`)[0].slice(0,200)}var sV,cV=__esmMin(()=>{ye(),Dh(),Vl(),Hs(),ep(),GM(),iV(),oI(),qB(),oV(),sV={command:`trust [packages..]`,description:"Configure npm Trusted Publishers (OIDC/GitHub Actions) for publishable workspace packages so release.yml can publish without a token. Native — no `npm` needed. Incremental: skips already-configured packages.",builder:n=>n.positional(`packages`,{description:`Optional package-name globs to limit the sweep (default: all publishable workspaces).`,type:`string`,array:!0}).option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${qf}).`,type:`string`}).option(`otp`,{description:"npm 2FA one-time code; sent as `npm-otp`. Prompted on demand if omitted.",type:`string`}).option(`dry-run`,{description:`List what would be configured without writing anything.`,type:`boolean`,default:!1}).option(`force`,{description:`Re-POST the config even for packages already trusted for this repo+workflow.`,type:`boolean`,default:!1}).option(`list`,{description:`Only report each package’s current trust state; configure nothing.`,type:`boolean`,default:!1}).option(`private`,{description:`Include private workspaces (default false — private packages are not publishable).`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=await loadNpmrc(S);if(!hasAnyCredential(C))return ve.error("gjsify trust: no npm token configured. Run `gjsify login` first."),process.exit(1);let N=n.registry??process.env.npm_config_registry??C.registry??qf;if(n[`dry-run`]!==!0){let n;try{n=await whoami(N,C)}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`gjsify trust: npm auth check failed (${S}).\nYour ~/.npmrc token is dead or revoked — refresh it with \`npm login\`, then re-run.
|
|
1143
1147
|
(\`gjsify trust\` uses the ~/.npmrc bearer token directly — unlike \`npm trust\`, which logs in via the browser.)`),process.exit(1)}if(!n.username)return ve.error("gjsify trust: your npm token appears dead or revoked (registry returned an empty whoami).\nRefresh it with `npm login`, then re-run."),process.exit(1);ve.log(`gjsify trust: authenticated as ${n.username}`)}let F=n.repository;if(!F){let n=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:S,encoding:`utf8`});n.status===0&&(F=parseRepoFromGitRemote(n.stdout)??void 0)}if(!F)return ve.error("gjsify trust: could not determine the GitHub repository.\nPass --repository owner/repo (no `origin` remote to infer from)."),process.exit(1);if(!validateRepository(F))return ve.error(`gjsify trust: --repository must be "owner/repo", got "${F}".`),process.exit(1);let I=normalizeWorkflowFile(n.workflow),H=n.environment,W=n.list===!0,q=n[`dry-run`]===!0,Y=n.force===!0,X=js(S,`.github`,`workflows`,I);existsSync(X)||ve.warn(`gjsify trust: note — ${X} not found; configuring trust for "${I}" anyway.`);let Z=filterWorkspaces(mergePublishables(discoverWorkspaces(S,{includeRoot:!0}),S),{noPrivate:n.private!==!0,include:n.packages&&n.packages.length>0?n.packages:void 0}).filter(n=>n.name);if(Z.length===0)return ve.error(`gjsify trust: no publishable packages matched.`),process.exit(1);ve.log(`gjsify trust: ${Z.length} package(s) | repo=${F} workflow=${I}`),q&&ve.log(`(dry-run — nothing will be written)`),ve.log();let te=createTrustRequester({npmrc:C,otpProvider:new OtpProvider(n.otp)}),ne=0,re=0,ie=0,ae=0,oe=[],se=[];for(let S of Z){let N=S.name,X=trustUrl(n.registry??registryFor(N,C)??qf,N);process.stdout.write(`→ ${N.padEnd(42)} `);let Z=await te(`GET`,X),Q=classifyTrustList(Z.status,Z.json,{repository:F,workflow:I});if(W){Q===`trusted`?ve.log(`trusted`):Q===`unpublished`?ve.log(`unpublished`):Q===`auth-required`?ve.log(`auth-required (could not read)`):Q===`untrusted`?ve.log(`not trusted`):ve.log(`error (HTTP ${Z.status})`);continue}if(Q===`trusted`&&!Y){ve.log(`already configured — skip`),re++;continue}if(Q===`unpublished`){ve.log(`not on npm yet — needs first-publish, skip`),ie++,oe.push(N);continue}if(q){ve.log(`would configure`),ne++;continue}let ce=await te(`POST`,X,githubTrustBody({repository:F,workflow:I,environment:H}));ce.status>=200&&ce.status<300?(ve.log(`configured`),ne++):ce.status===409?(ve.log(`already configured (409) — done`),re++):ce.status===404?(ve.log(`not on npm yet — needs first-publish, skip`),ie++,oe.push(N)):(ve.log(`FAILED (HTTP ${ce.status})`),ae++,se.push(`${N} — HTTP ${ce.status}${ce.text?`: ${firstLine(ce.text)}`:``}`))}if(!W){if(ve.log(),ve.log(`Done: ${ne} ${q?`would-configure`:`configured`}, ${re} already-configured, ${ie} unpublished, ${ae} failed.`),oe.length>0){ve.log("Need a first publish before they can be trust-configured (then re-run `gjsify trust`):");for(let n of oe)ve.log(` ${n}`)}if(se.length>0){ve.log("Failed (re-run `gjsify trust` — it is incremental; usually a lapsed 2FA window or rate-limit):");for(let n of se)ve.log(` ${n}`);process.exit(1)}}}}});function resolveRepoRoot(n){let S=findWorkspaceRoot(n);if(S)return S;let C=spawnSync(`git`,[`rev-parse`,`--show-toplevel`],{cwd:n,encoding:`utf8`});if(C.status===0){let n=C.stdout.trim();if(n&&existsSync(n))return n}return n}function assertEveryPatternMatches(n,S){let C=S.filter(S=>{try{return discoverWorkspaces(n,{patterns:[S]}).length===0}catch{return!0}});if(C.length===0)return;let N=[`gjsify onboard: --packages matched no package directory (${C.length} of ${S.length} pattern(s)) under ${n}:`];for(let n of C)N.push(` ${JSON.stringify(n)}`);throw N.push(" Patterns are DIRECTORY globs resolved against the repo root, and only `*` is supported",` (one path segment). A matched directory needs a package.json with a "name".`),Error(N.join(`
|
|
1144
1148
|
`))}function collectOnboardPackages(n,S,C={}){let N=[],F=[],I=new Set,take=(n,S,C)=>{let H=0;for(let n of S)!n.name||I.has(n.name)||(I.add(n.name),F.push(n),H++);N.push({kind:n,patterns:C,count:H})};if(existsSync(js(n,`package.json`)))try{take(`workspaces`,discoverWorkspaces(n,{includeRoot:!0}))}catch{}return C.patterns&&C.patterns.length>0&&take(`packages`,discoverWorkspaces(n,{patterns:[...C.patterns]}),C.patterns),take(`scanned-dirs`,mergePublishables([],S)),{packages:F,sources:N}}function describeSources(n){return n.filter(n=>n.count>0).map(n=>n.patterns?`${n.kind}(${n.patterns.join(`,`)})=${n.count}`:`${n.kind}=${n.count}`).join(` + `)}function declaredRepository(n){let S=n.manifest.repository,C=typeof S==`string`?S:S?.url;return typeof C!=`string`||C.length===0?null:parseRepoFromGitRemote(C)}function assertRepositoryAgreement(n,S){let C=S.toLowerCase(),N=n.map(n=>({ws:n,declared:declaredRepository(n)})).filter(n=>n.declared!==null&&n.declared.toLowerCase()!==C);if(N.length===0)return;let F=new Map;for(let{ws:n,declared:S}of N){let C=F.get(S)??[];C.push(n.name),F.set(S,C)}let I=[`gjsify onboard: ${N.length} selected package(s) declare a DIFFERENT repository than ${S}:`];for(let[n,S]of F){let C=S.slice(0,5).join(`, `),N=S.length>5?`, … (+${S.length-5} more)`:``;I.push(` ${n}: ${S.length} package(s) — ${C}${N}`)}throw I.push(` A Trusted Publisher scoped to the wrong repository points that package's OIDC exchange`,` at a workflow that does not publish it, which breaks the release this sweep protects.`,` Either exclude them (--exclude), select only what belongs here (--include), or point`,` --repository at the repo that actually publishes them.`),Error(I.join(`
|
|
1145
|
-
`))}var JB=__esmMin(()=>{Vl(),Dh(),GM(),Hs(),UB(),GB(),qM()});function describeRateLimitHeaders(n){if(!n)return`no headers captured`;let S=[];return n.forEach((n,C)=>{(/^retry-after$/i.test(C)||/ratelimit/i.test(C))&&S.push(`${C}: ${n}`)}),S.length>0?S.join(`, `):`npm sent no Retry-After and no rate-limit headers`}function retryAfterMs(n){let S=n?.get(`retry-after`);if(!S)return null;let C=Number.parseInt(S.trim(),10);return!Number.isFinite(C)||C<0?null:C*1e3}async function packumentExists(n,S){let C=n.endsWith(`/`)?n.slice(0,-1):n;try{let n=await fetch(`${C}/${S.replace(`/`,`%2f`)}`,{method:`GET`,headers:{accept:`application/vnd.npm.install-v1+json`}});return n.status===404?!1:n.ok?!0:null}catch{return null}}function actionForState(n){switch(n){case`trusted`:return`skip`;case`untrusted`:return`trust`;case`unpublished`:return`publish-and-trust`;default:return`blocked`}}function defaultSleep(n){return new Promise(S=>setTimeout(S,n))}async function requestWaitingOutRateLimit(n,S,C,N,F={}){let I=F.sleep??defaultSleep,H=F.maxRateLimitWaitMs??3e5,W=F.rateLimitBaseDelayMs??2e3,q=F.gate;q&&await q.wait();let Y=await n(S,C,N),X=0;for(let Z=0;Y.status===429&&X<H;Z++){let te=retryAfterMs(Y.headers),ne=Math.min(te??W*2**Z,YB),re=Math.min(ne,H-X);F.onRateLimit?.({url:C,headers:describeRateLimitHeaders(Y.headers),waitMs:re,fromRetryAfter:te!==null}),q?.penalize(re),await(q?q.wait():I(re)),X+=re,Y=await n(S,C,N)}return Y}async function probeTrustState(n,S,C,N={}){let F=C.registryOverride??registryFor(S.name,C.npmrc)??qf,I=trustUrl(F,S.name),H={repository:C.repository,workflow:C.workflow},W=N.sleep??defaultSleep,q=await requestWaitingOutRateLimit(n,`GET`,I,void 0,N),Y=classifyTrustList(q.status,q.json,H);return Y===`auth-required`&&N.retryOn401!==!1&&(await W(N.retryDelayMs??400),q=await n(`GET`,I),Y=classifyTrustList(q.status,q.json,H)),(Y===`untrusted`||Y===`auth-required`)&&await(N.exists??packumentExists)(F,S.name)===!1&&(Y=`unpublished`),{ws:S,registry:F,url:I,state:Y,httpStatus:q.status,action:actionForState(Y)}}async function probeAllTrustStates(n,S,C,N,F={}){if(S.length===0)return[];let I=S.length,H=0,report=n=>(H++,F.onProgress?.(H,I,n),n);return[report(await probeTrustState(n,S[0],N,F)),...await mapWithConcurrency(S.slice(1),Math.max(1,C),async S=>report(await probeTrustState(n,S,N,F)))]}async function mapWithConcurrency(n,S,C){let N=Array.from({length:n.length}),F=0,I=Array.from({length:Math.min(Math.max(1,S),n.length)},async()=>{for(;;){let S=F++;if(S>=n.length)return;N[S]=await C(n[S])}});return await Promise.all(I),N}var YB,RateLimitGate,XB=__esmMin(()=>{ep(),GB(),YB=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(n={}){this.now=n.now??(()=>Date.now()),this.sleeper=n.sleep??defaultSleep}async wait(){let n=this.until-this.now();n>0&&await this.sleeper(n)}penalize(n){this.until=Math.max(this.until,this.now()+n)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(n,S,C){let N=C.failed??0;if(C.asJson)process.stdout.write(`${JSON.stringify({ok:N===0,dryRun:C.dryRun,root:C.root,sources:C.sources,discovered:C.discovered,total:S.length,published:n.filter(n=>n.result===`published`||n.result===`published+trusted`).length,trusted:n.filter(n=>n.result===`trusted`||n.result===`published+trusted`).length,alreadyDone:n.filter(n=>n.result===`already-done`).length,failed:N,results:n},null,2)}\n`);else{let S=C.dryRun?N>0?`Dry-run INCOMPLETE — nothing changed, but ${N} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${n.filter(n=>n.result.includes(`published`)).length} published, ${n.filter(n=>n.result===`trusted`||n.result===`published+trusted`).length} trusted, ${n.filter(n=>n.result===`already-done`).length} already done, ${N} failed.`;process.stdout.write(`\n${S}\n`)}process.exit(+(N>0))}function statusCell(n){switch(n.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${n.httpStatus})`}}async function ensureAuthenticated(n){let{npmrc:S,registry:C,cwd:N,nonInteractive:F,dryRun:I,otp:H,log:W}=n;if(hasAnyCredential(S))try{let n=await whoami(C,S);if(n.username)return n.username}catch{}if(I){W(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(F)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");W(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:C,otp:H,cwd:N})).username}catch(n){throw n instanceof LoginError?Error(n.message):n}}async function buildIfPresent(n,S){if(typeof(n.manifest.scripts??{}).build!=`string`)return;let C=detectPackageManager(),N=[`run`,`build`];S(` $ ${C} ${N.join(` `)}`);let{code:F}=await spawnToCompletion(C,N,{completion:`return`,cwd:n.location,env:{...process.env}});if(F!==0)throw Error(`build exited with code ${F}`)}function describePublishFailure(n){switch(n.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:case`oidc-no-token`:return`OIDC/token auth failed`;case`diagnostic`:return`HTTP 404 (${n.diag.reason})`;case`error`:return`HTTP ${n.status} ${n.statusText}`;default:return`unknown`}}var ZB,QB,$B=__esmMin(()=>{ye(),Dh(),ep(),GM(),aI(),MB(),SB(),PB(),qB(),zB(),qF(),_P(),JB(),GB(),XB(),ZB=4,QB={command:`onboard`,description:`Ensure every publishable package in a monorepo is both published on npm and has a Trusted Publisher configured for its release workflow — publishing/trusting only what is missing, one shared OTP across the whole sweep. Works on npm/yarn workspaces and, via --packages, on a monorepo with no workspace manifest at all. Idempotent.`,builder:n=>n.option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish via OIDC (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${qf}).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code, used as the initial shared code. Prompted on demand (once) if omitted and a challenge occurs.`,type:`string`}).option(`packages`,{description:'Directory glob naming package folders, resolved against the repo root (repeatable). For a monorepo that is not an npm/yarn workspace — `--packages "*"` in a repo whose 703 package directories sit at the top level. Merged with the root manifest\'s own `workspaces` globs when it has any. A pattern matching NO directory is a hard error.',type:`string`,array:!0}).option(`include`,{description:`Glob pattern to include packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`access`,{description:"npm access for a FIRST publish — `public` or `restricted`. Only ever applied to a package this sweep publishes; an already-published package keeps whatever access it has.",type:`string`,choices:[`public`,`restricted`],default:`public`}).option(`build`,{description:"Run each to-be-published package's `build` script first. `--no-build` skips it, for a repo whose packages are generated artifacts with nothing to build.",type:`boolean`,default:!0}).option(`verbose`,{description:`List every package in the plan table, including the ones already published + trusted (by default only the rows needing work are listed; the counts always cover all of them).`,type:`boolean`,alias:`v`,default:!1}).option(`concurrency`,{description:`How many packages to probe (read state) in parallel (kept small so a single token does not burst npm; the first read is always serial to prompt for the shared OTP once).`,type:`number`,default:4}).option(`write-concurrency`,{description:`How many Trusted-Publisher writes to issue in parallel. It buys FEWER 2FA PROMPTS more than it buys speed: an npm code lives about 30 seconds, so a serial sweep crosses a code boundary every ~38 packages. Raising it does not beat npm's rate limit — a 429 anywhere now pauses the whole sweep, so it self-paces down to whatever the registry will serve. Publishes are unaffected: they stay serial, because publish ORDER is a correctness property.`,type:`number`,default:ZB}).option(`dry-run`,{description:`Report the plan (what would be published / trusted) without changing anything.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit a machine-readable summary object as the final line of stdout.`,type:`boolean`,default:!1}).option(`yes`,{description:`Non-interactive: never prompt. Fail clearly if a login or an OTP is required and not supplied via flags.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=n[`dry-run`]===!0,N=n.json===!0,F=n.yes===!0,log=(n=``)=>{N?process.stderr.write(`${n}\n`):writeAroundPrompt(`${n}\n`)},I=await loadNpmrc(S),H=n.registry??process.env.npm_config_registry??I.registry??qf,W;try{W=await ensureAuthenticated({npmrc:I,registry:H,cwd:S,nonInteractive:F,dryRun:C,otp:n.otp,log})}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:S})}\n`):ve.error(S),process.exit(1)}I=await loadNpmrc(S),W&&log(`gjsify onboard: authenticated as ${W}`);let q=n.repository;if(!q){let n=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:S,encoding:`utf8`});n.status===0&&(q=parseRepoFromGitRemote(n.stdout)??void 0)}if(!q||!validateRepository(q)){let n=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:n})}\n`):ve.error(n),process.exit(1)}let Y=normalizeWorkflowFile(n.workflow),X=n.environment,Z=resolveRepoRoot(S),te,ne;try{n.packages&&n.packages.length>0&&assertEveryPatternMatches(Z,n.packages);let C=collectOnboardPackages(Z,S,{patterns:n.packages});te=C.packages,ne=describeSources(C.sources)}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:S})}\n`):ve.error(S),process.exit(1)}let re=filterWorkspaces(te,{noPrivate:!0,include:n.include,exclude:n.exclude}).filter(n=>n.name);if(re.length===0){let n=`gjsify onboard: no publishable packages found under ${Z} (discovered ${te.length}${ne?` — ${ne}`:``}). `+(te.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:n})}\n`):ve.error(n),process.exit(1)}try{assertRepositoryAgreement(re,q)}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:S})}\n`):ve.error(S),process.exit(1)}log(`gjsify onboard: root=${Z} | ${ne}`),log(`gjsify onboard: ${re.length} of ${te.length} package(s) selected | repo=${q} workflow=${Y}`),C&&log(`(dry-run — nothing will be published or configured)`),log();let ie=new OtpProvider(n.otp,F?async()=>``:void 0,{registry:H}),ae=createTrustRequester({npmrc:I,otpProvider:ie}),oe=new RateLimitGate,se=!1,onRateLimit=n=>{se||(se=!0,log(` npm rate limit hit. ${n.headers}. Waiting ${Math.round(n.waitMs/1e3)}s (${n.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:oe,onRateLimit},ce=Math.max(1,Math.min(50,Math.ceil(re.length/10))),le=0,ue=0,de=0;re.length>ce&&log(`Reading trust state for ${re.length} package(s)…`);let fe=await probeAllTrustStates(ae,re,Math.max(1,n.concurrency),{registryOverride:n.registry,npmrc:I,repository:q,workflow:Y},{...Q,onProgress:(n,S,C)=>{if(C.action===`trust`||C.action===`publish-and-trust`?le++:C.action===`skip`?ue++:de++,n%ce!==0&&n!==S||S<=ce)return;let N=[`${le} to do`,`${ue} already done`];de>0&&N.push(`${de} unreadable`),log(` read ${n}/${S} — ${N.join(`, `)}`)}}),pe=fe.filter(n=>n.action===`publish-and-trust`),me=fe.filter(n=>n.action===`trust`),he=fe.filter(n=>n.action===`skip`),ge=fe.filter(n=>n.action===`blocked`);for(let S of fe)S.action===`skip`&&n.verbose!==!0||log(` ${statusCell(S)} ${S.ws.name}`);!n.verbose&&he.length>0&&log(` (${he.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${he.length} already done, ${pe.length} to publish+trust, ${me.length} to trust, ${ge.length} unreadable.`);let _e=ge.filter(n=>n.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ye=[];if(C){for(let n of fe)ye.push({name:n.ws.name,result:n.action===`skip`?`already-done`:n.action===`blocked`?`failed`:`skipped-dry-run`,detail:n.action===`publish-and-trust`?`would publish + trust`:n.action===`trust`?`would trust`:n.action===`blocked`?`state HTTP ${n.httpStatus}`:void 0});finish(ye,fe,{asJson:N,dryRun:C,failed:ge.length,root:Z,sources:ne,discovered:te.length});return}let be=githubTrustBody({repository:q,workflow:Y,environment:X}),xe=Math.max(1,n[`write-concurrency`]),Se=pe.length+me.length,Ce=Array.from({length:fe.length}),we=0,Te=0,Ee=0,configureTrust=async(n,S,C)=>{let N=await requestWaitingOutRateLimit(ae,`POST`,n.url,be,Q),F=`${++Te}/${Se}`;N.status>=200&&N.status<300?(log(` [${F}] trusted ${n.ws.name}`),Ce[S]={name:n.ws.name,result:C?`published+trusted`:`trusted`}):N.status===409?Ce[S]={name:n.ws.name,result:C?`published+trusted`:`trusted`}:N.status===404?(log(` [${F}] ${n.ws.name}: published but not yet trust-configurable (re-run onboard)`),Ce[S]={name:n.ws.name,result:C?`published`:`failed`,detail:`trust config deferred (404)`},C||we++):(log(` [${F}] trust failed (HTTP ${N.status}) — ${n.ws.name}`),Ce[S]={name:n.ws.name,result:`failed`,detail:`trust HTTP ${N.status}`},N.status===429&&Ee++,we++)},De=[];for(let S=0;S<fe.length;S++){let C=fe[S];if(C.action===`skip`){Ce[S]={name:C.ws.name,result:`already-done`};continue}if(C.action===`blocked`){log(`→ ${C.ws.name}: cannot read trust state (HTTP ${C.httpStatus}) — skipped`),Ce[S]={name:C.ws.name,result:`failed`,detail:`state HTTP ${C.httpStatus}`},we++;continue}if(C.action===`trust`){De.push({p:C,i:S});continue}log(`→ ${C.ws.name}: building + publishing…`);try{n.build!==!1&&await buildIfPresent(C.ws,log)}catch(n){let N=n instanceof Error?n.message:String(n);log(` build failed: ${N}`),Ce[S]={name:C.ws.name,result:`failed`,detail:`build: ${N}`},we++;continue}let N=await publishWorkspace({wsDir:C.ws.location,tag:`latest`,access:n.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:C.registry,verbose:!1,json:!1,otpProvider:ie,seedOtpFirst:!1});if(!N.ok){let n=describePublishFailure(N);log(` publish failed: ${n}`),Ce[S]={name:C.ws.name,result:`failed`,detail:`publish: ${n}`},we++;continue}log(` published ${N.name}@${`version`in N?N.version:``}`),await configureTrust(C,S,N.action!==`skipped-untrusted-new`)}De.length>0&&(De.length>1&&log(`→ configuring ${De.length} Trusted Publisher(s), ${xe} at a time…`),await mapWithConcurrency(De,xe,async({p:n,i:S})=>configureTrust(n,S,!1)));for(let n of Ce)n&&ye.push(n);Ee>0&&(log(),log(`${Ee} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${xe}) provokes the limit less.`)),finish(ye,fe,{asJson:N,dryRun:C,failed:we,root:Z,sources:ne,discovered:te.length})}}});function pathFor(n){return n===`win32`?Cs:xs}function isInside$1(n,S,C){let N=pathFor(C);if(!N.isAbsolute(n)||!N.isAbsolute(S))return!1;let F=S.endsWith(N.sep)?S:S+N.sep;return n===S||n.startsWith(F)}function classifyInstall(n){let S=n.env??process.env,C=n.platform??process.platform,N=pathFor(C),F=N.resolve(n.selfDir);if(S.FLATPAK_ID||isInside$1(F,tV,C)){let n=S.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:S.FLATPAK_ID?`FLATPAK_ID=${S.FLATPAK_ID}`:`running from ${tV}`,updateWith:`flatpak update ${n}`,managedElsewhere:!0}}return isInside$1(F,N.resolve(n.xdgPrefix),C)?{kind:`xdg-global`,evidence:`running from the user-global prefix ${n.xdgPrefix}`,managedElsewhere:!1}:C!==`win32`&&eV.some(n=>isInside$1(F,n,C))?{kind:`system-package`,evidence:`running from the system prefix ${F}`,updateWith:"your distribution package manager (`apt upgrade` / `dnf upgrade` / …), or install the newer package from https://github.com/gjsify/gjsify/releases/latest",managedElsewhere:!0}:F.split(N.sep).includes(`node_modules`)?{kind:`npm-global`,evidence:`running from a node_modules tree at ${F}`,updateWith:`npm install -g @gjsify/cli@latest (or switch to the Node-free bootstrap)`,managedElsewhere:!0}:{kind:`unknown`,evidence:`running from ${F}, which matches no known install layout`,managedElsewhere:!1}}var eV,tV,nV=__esmMin(()=>{Hs(),eV=[`/usr/`,`/opt/`,`/snap/`],tV=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(n){let S=n.platform??process.platform,C=S===`win32`?Cs:xs,norm=n=>S===`win32`?C.resolve(n).toLowerCase():C.resolve(n);if(n.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${n.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${n.binDir}`};if(norm(C.dirname(n.resolvedBin))===norm(n.binDir))return{ok:!0};let N=n.runningVersion?` (v${n.runningVersion})`:``;return{ok:!1,message:`BUT \`${n.binName}\` on PATH resolves to\n ${n.resolvedBin}${N}\nwhich is NOT the install that was just updated, so the next \`${n.binName}\`\nyou run will not be v${n.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${rV}\`)\n or put ${n.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${n.binName} --version\`.`}}function readSelfDir(){let n=process.env.GJSIFY_CLI_PACKAGE_JSON;if(n)return Ps(Os(n));let S=fileURLToPath(import.meta.url),C=Ps(Os(S));for(let n=0;n<8&&C!==Ps(C);n++){if(existsSync(js(C,`package.json`)))return C;C=Ps(C)}return Ps(Os(S))}function readCurrentVersion(){try{let n=process.env.GJSIFY_CLI_PACKAGE_JSON;if(n){let S=JSON.parse(readFileSync(n,`utf-8`));return S.name===rV&&typeof S.version==`string`?S.version:null}let S=Ps(Os(fileURLToPath(import.meta.url)));for(let n=0;n<8&&S!==Ps(S);n++){let n=js(S,`package.json`);if(existsSync(n)){let S=JSON.parse(readFileSync(n,`utf-8`));if(S.name===rV&&typeof S.version==`string`)return S.version}S=Ps(S)}}catch{}return null}function resolveTag(n,S){let C=n[`dist-tags`]??{};return C[S]?C[S]:n.versions&&typeof n.versions==`object`&&n.versions[S]?S:null}var rV,iV,aV,oV=__esmMin(()=>{ye(),Vl(),Hs(),gn(),ep(),yF(),nV(),CF(),lF(),tB(),rV=`@gjsify/cli`,iV={command:`self-update`,description:`Update the installed ${rV} to the latest release (or pinned --tag).`,builder:n=>n.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`,default:`latest`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async n=>{let S=defaultGlobalLayout(),C=js(js(S.prefix,`node_modules`,rV),`package.json`),N=readCurrentVersion(),F=existsSync(C);ve.log(`Current ${rV}: v${N??`(unknown)`}`);let I=classifyInstall({selfDir:readSelfDir(),xdgPrefix:S.prefix});if(I.managedElsewhere)return ve.error(`\ngjsify self-update: this gjsify is managed by something else — ${I.evidence}.\nUpdating it from here would write ${S.prefix} and leave you running two installs.\n\nUpdate with: ${I.updateWith}\n`),process.exit(1);F||ve.warn(`\nWarning: no @gjsify/cli install found under ${S.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`),ve.log(`Fetching dist-tags for ${rV}@${n.tag} ...`);let H;try{H=await fetchPackument(rV)}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`Failed to fetch packument: ${S}`),process.exit(1)}let W=resolveTag(H,n.tag);if(!W)return ve.error(`Unknown dist-tag '${n.tag}' on ${rV}. Known tags: ${Object.keys(H[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ve.log(`Latest matching --tag ${n.tag}: v${W}`);let q=F&&!hasBundlerEngineInstalled(S.prefix),Y=q&&!n.skipDeps&&!n.check;if(N===W&&!n.force&&!Y){ve.log(`Already up to date (v${W}).`),q&&n.skipDeps&&ve.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),n.check||ve.log(`Run with --force to reinstall anyway.`);return}if(Y&&N===W&&!n.force&&ve.log(`@gjsify/cli is at v${W} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),n.check)return ve.log(N?`Update available: v${N} → v${W}`:`Install required: → v${W}`),process.exit(1);let X=!n.skipDeps,Z=X?` + runtime dependencies`:` (bundle only)`;ve.log(`Installing ${rV}@${W}${Z} ...`);let te=makeProgressReporter();try{await installPackages({prefix:S.prefix,specs:[`${rV}@${W}`],verbose:!1,skipDeps:!X,progress:te})}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`self-update: install failed — ${S}`),ve.error("Re-run `gjsify self-update` to retry."),process.exit(1)}X&&await installGjsEnginePackages(S.prefix,W,{verbose:!1}),n.prune!==!1&&pruneAfterInstall(S.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let ne=linkGlobalBins([rV],S);if(ne.length===0)ve.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let n of ne)ve.log(` • ${n.link} → ${n.target}`);if(globalLayoutIsDefault()){let n=verifyPathResolution({binName:aV,binDir:S.binDir,resolvedBin:resolveBinOnPath(aV),runningVersion:N,targetVersion:W});if(!n.ok)return ve.error(`\nInstalled ${rV} v${W} at ${S.prefix}`),ve.error(n.message),process.exit(1)}ve.log(`\nUpdated ${rV} to v${W}.`),X?ve.log(`Runtime dependencies were resolved alongside the bundle.`):ve.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},aV=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1149
|
+
`))}var lV=__esmMin(()=>{Vl(),Dh(),GM(),Hs(),iV(),oV(),qM()});function describeRateLimitHeaders(n){if(!n)return`no headers captured`;let S=[];return n.forEach((n,C)=>{(/^retry-after$/i.test(C)||/ratelimit/i.test(C))&&S.push(`${C}: ${n}`)}),S.length>0?S.join(`, `):`npm sent no Retry-After and no rate-limit headers`}function retryAfterMs(n){let S=n?.get(`retry-after`);if(!S)return null;let C=Number.parseInt(S.trim(),10);return!Number.isFinite(C)||C<0?null:C*1e3}async function packumentExists(n,S){let C=n.endsWith(`/`)?n.slice(0,-1):n;try{let n=await fetch(`${C}/${S.replace(`/`,`%2f`)}`,{method:`GET`,headers:{accept:`application/vnd.npm.install-v1+json`}});return n.status===404?!1:n.ok?!0:null}catch{return null}}function actionForState(n){switch(n){case`trusted`:return`skip`;case`untrusted`:return`trust`;case`unpublished`:return`publish-and-trust`;default:return`blocked`}}function defaultSleep(n){return new Promise(S=>setTimeout(S,n))}async function requestWaitingOutRateLimit(n,S,C,N,F={}){let I=F.sleep??defaultSleep,H=F.maxRateLimitWaitMs??3e5,W=F.rateLimitBaseDelayMs??2e3,q=F.gate;q&&await q.wait();let Y=await n(S,C,N),X=0;for(let Z=0;Y.status===429&&X<H;Z++){let te=retryAfterMs(Y.headers),ne=Math.min(te??W*2**Z,uV),re=Math.min(ne,H-X);F.onRateLimit?.({url:C,headers:describeRateLimitHeaders(Y.headers),waitMs:re,fromRetryAfter:te!==null}),q?.penalize(re),await(q?q.wait():I(re)),X+=re,Y=await n(S,C,N)}return Y}async function probeTrustState(n,S,C,N={}){let F=C.registryOverride??registryFor(S.name,C.npmrc)??qf,I=trustUrl(F,S.name),H={repository:C.repository,workflow:C.workflow},W=N.sleep??defaultSleep,q=await requestWaitingOutRateLimit(n,`GET`,I,void 0,N),Y=classifyTrustList(q.status,q.json,H);return Y===`auth-required`&&N.retryOn401!==!1&&(await W(N.retryDelayMs??400),q=await n(`GET`,I),Y=classifyTrustList(q.status,q.json,H)),(Y===`untrusted`||Y===`auth-required`)&&await(N.exists??packumentExists)(F,S.name)===!1&&(Y=`unpublished`),{ws:S,registry:F,url:I,state:Y,httpStatus:q.status,action:actionForState(Y)}}async function probeAllTrustStates(n,S,C,N,F={}){if(S.length===0)return[];let I=S.length,H=0,report=n=>(H++,F.onProgress?.(H,I,n),n);return[report(await probeTrustState(n,S[0],N,F)),...await mapWithConcurrency(S.slice(1),Math.max(1,C),async S=>report(await probeTrustState(n,S,N,F)))]}async function mapWithConcurrency(n,S,C){let N=Array.from({length:n.length}),F=0,I=Array.from({length:Math.min(Math.max(1,S),n.length)},async()=>{for(;;){let S=F++;if(S>=n.length)return;N[S]=await C(n[S])}});return await Promise.all(I),N}var uV,RateLimitGate,dV=__esmMin(()=>{ep(),oV(),uV=6e4,RateLimitGate=class{until=0;now;sleeper;constructor(n={}){this.now=n.now??(()=>Date.now()),this.sleeper=n.sleep??defaultSleep}async wait(){let n=this.until-this.now();n>0&&await this.sleeper(n)}penalize(n){this.until=Math.max(this.until,this.now()+n)}remainingMs(){return Math.max(0,this.until-this.now())}}});function finish(n,S,C){let N=C.failed??0;if(C.asJson)process.stdout.write(`${JSON.stringify({ok:N===0,dryRun:C.dryRun,root:C.root,sources:C.sources,discovered:C.discovered,total:S.length,published:n.filter(n=>n.result===`published`||n.result===`published+trusted`).length,trusted:n.filter(n=>n.result===`trusted`||n.result===`published+trusted`).length,alreadyDone:n.filter(n=>n.result===`already-done`).length,failed:N,results:n},null,2)}\n`);else{let S=C.dryRun?N>0?`Dry-run INCOMPLETE — nothing changed, but ${N} package(s) had an unreadable state, so the plan above does not cover them. Authenticate (\`gjsify login\`) and re-run.`:`Dry-run complete — nothing changed.`:`Done: ${n.filter(n=>n.result.includes(`published`)).length} published, ${n.filter(n=>n.result===`trusted`||n.result===`published+trusted`).length} trusted, ${n.filter(n=>n.result===`already-done`).length} already done, ${N} failed.`;process.stdout.write(`\n${S}\n`)}process.exit(+(N>0))}function statusCell(n){switch(n.action){case`skip`:return`published✓ trusted✓`;case`trust`:return`published✓ trust… `;case`publish-and-trust`:return`publish… trust… `;case`blocked`:return`unreadable (${n.httpStatus})`}}async function ensureAuthenticated(n){let{npmrc:S,registry:C,cwd:N,nonInteractive:F,dryRun:I,otp:H,log:W}=n;if(hasAnyCredential(S))try{let n=await whoami(C,S);if(n.username)return n.username}catch{}if(I){W(`gjsify onboard: no live npm token — dry-run continues (state reads may be limited).`);return}if(F)throw Error("gjsify onboard: not authenticated and --yes was passed — run `gjsify login` first (or omit --yes to log in interactively).");W(`gjsify onboard: no live npm token — logging in…`);try{return(await runLogin({registry:C,otp:H,cwd:N})).username}catch(n){throw n instanceof LoginError?Error(n.message):n}}async function buildIfPresent(n,S){if(typeof(n.manifest.scripts??{}).build!=`string`)return;let C=detectPackageManager(),N=[`run`,`build`];S(` $ ${C} ${N.join(` `)}`);let{code:F}=await spawnToCompletion(C,N,{completion:`return`,cwd:n.location,env:{...process.env}});if(F!==0)throw Error(`build exited with code ${F}`)}function describePublishFailure(n){switch(n.action){case`otp-required`:return`npm required a 2FA code (re-run with --otp, or on a TTY)`;case`oidc-failed`:case`oidc-no-token`:return`OIDC/token auth failed`;case`diagnostic`:return`HTTP 404 (${n.diag.reason})`;case`publish-unconfirmed`:return`npm ${n.claim===`already-published`?`reported it already published`:`accepted the upload`} (HTTP ${n.putStatus}) but ${n.name}@${n.version} did not resolve on ${n.registry} after ${n.readback.attempts} probe(s) over ${(n.readback.elapsedMs/1e3).toFixed(1)}s`;case`error`:return`HTTP ${n.status} ${n.statusText}`;default:return`unknown`}}var fV,pV,mV=__esmMin(()=>{ye(),Dh(),ep(),GM(),oI(),qB(),LB(),YB(),cV(),eV(),JF(),_P(),lV(),oV(),dV(),fV=4,pV={command:`onboard`,description:`Ensure every publishable package in a monorepo is both published on npm and has a Trusted Publisher configured for its release workflow — publishing/trusting only what is missing, one shared OTP across the whole sweep. Works on npm/yarn workspaces and, via --packages, on a monorepo with no workspace manifest at all. Idempotent.`,builder:n=>n.option(`repository`,{description:"GitHub repo as `owner/repo`. Default: inferred from the `origin` git remote.",type:`string`}).option(`workflow`,{description:`Workflow filename allowed to publish via OIDC (basename only).`,type:`string`,default:`release.yml`}).option(`environment`,{description:`Optional GitHub Actions environment the workflow must run in.`,type:`string`}).option(`registry`,{description:`Registry override. Default: scope-aware lookup from .npmrc (falls back to ${qf}).`,type:`string`}).option(`otp`,{description:`npm 2FA one-time code, used as the initial shared code. Prompted on demand (once) if omitted and a challenge occurs.`,type:`string`}).option(`packages`,{description:'Directory glob naming package folders, resolved against the repo root (repeatable). For a monorepo that is not an npm/yarn workspace — `--packages "*"` in a repo whose 703 package directories sit at the top level. Merged with the root manifest\'s own `workspaces` globs when it has any. A pattern matching NO directory is a hard error.',type:`string`,array:!0}).option(`include`,{description:`Glob pattern to include packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`exclude`,{description:`Glob pattern to exclude packages by NAME (repeatable). Applied after discovery.`,type:`string`,array:!0}).option(`access`,{description:"npm access for a FIRST publish — `public` or `restricted`. Only ever applied to a package this sweep publishes; an already-published package keeps whatever access it has.",type:`string`,choices:[`public`,`restricted`],default:`public`}).option(`build`,{description:"Run each to-be-published package's `build` script first. `--no-build` skips it, for a repo whose packages are generated artifacts with nothing to build.",type:`boolean`,default:!0}).option(`verbose`,{description:`List every package in the plan table, including the ones already published + trusted (by default only the rows needing work are listed; the counts always cover all of them).`,type:`boolean`,alias:`v`,default:!1}).option(`concurrency`,{description:`How many packages to probe (read state) in parallel (kept small so a single token does not burst npm; the first read is always serial to prompt for the shared OTP once).`,type:`number`,default:4}).option(`write-concurrency`,{description:`How many Trusted-Publisher writes to issue in parallel. It buys FEWER 2FA PROMPTS more than it buys speed: an npm code lives about 30 seconds, so a serial sweep crosses a code boundary every ~38 packages. Raising it does not beat npm's rate limit — a 429 anywhere now pauses the whole sweep, so it self-paces down to whatever the registry will serve. Publishes are unaffected: they stay serial, because publish ORDER is a correctness property.`,type:`number`,default:fV}).option(`dry-run`,{description:`Report the plan (what would be published / trusted) without changing anything.`,type:`boolean`,default:!1}).option(`json`,{description:`Emit a machine-readable summary object as the final line of stdout.`,type:`boolean`,default:!1}).option(`yes`,{description:`Non-interactive: never prompt. Fail clearly if a login or an OTP is required and not supplied via flags.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=n[`dry-run`]===!0,N=n.json===!0,F=n.yes===!0,log=(n=``)=>{N?process.stderr.write(`${n}\n`):writeAroundPrompt(`${n}\n`)},I=await loadNpmrc(S),H=n.registry??process.env.npm_config_registry??I.registry??qf,W;try{W=await ensureAuthenticated({npmrc:I,registry:H,cwd:S,nonInteractive:F,dryRun:C,otp:n.otp,log})}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`auth`,message:S})}\n`):ve.error(S),process.exit(1)}I=await loadNpmrc(S),W&&log(`gjsify onboard: authenticated as ${W}`);let q=n.repository;if(!q){let n=spawnSync(`git`,[`remote`,`get-url`,`origin`],{cwd:S,encoding:`utf8`});n.status===0&&(q=parseRepoFromGitRemote(n.stdout)??void 0)}if(!q||!validateRepository(q)){let n=`gjsify onboard: could not determine the GitHub repository — pass --repository owner/repo.`;return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`repository`,message:n})}\n`):ve.error(n),process.exit(1)}let Y=normalizeWorkflowFile(n.workflow),X=n.environment,Z=resolveRepoRoot(S),te,ne;try{n.packages&&n.packages.length>0&&assertEveryPatternMatches(Z,n.packages);let C=collectOnboardPackages(Z,S,{patterns:n.packages});te=C.packages,ne=describeSources(C.sources)}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`discovery`,message:S})}\n`):ve.error(S),process.exit(1)}let re=filterWorkspaces(te,{noPrivate:!0,include:n.include,exclude:n.exclude}).filter(n=>n.name);if(re.length===0){let n=`gjsify onboard: no publishable packages found under ${Z} (discovered ${te.length}${ne?` — ${ne}`:``}). `+(te.length>0?`Every discovered package is private or was filtered out by --include/--exclude.`:`Pass --packages with a directory glob if this repo has no workspace manifest.`);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`no-packages`,message:n})}\n`):ve.error(n),process.exit(1)}try{assertRepositoryAgreement(re,q)}catch(n){let S=n instanceof Error?n.message:String(n);return N?process.stdout.write(`${JSON.stringify({ok:!1,error:`foreign-repository`,message:S})}\n`):ve.error(S),process.exit(1)}log(`gjsify onboard: root=${Z} | ${ne}`),log(`gjsify onboard: ${re.length} of ${te.length} package(s) selected | repo=${q} workflow=${Y}`),C&&log(`(dry-run — nothing will be published or configured)`),log();let ie=new OtpProvider(n.otp,F?async()=>``:void 0,{registry:H}),ae=createTrustRequester({npmrc:I,otpProvider:ie}),oe=new RateLimitGate,se=!1,onRateLimit=n=>{se||(se=!0,log(` npm rate limit hit. ${n.headers}. Waiting ${Math.round(n.waitMs/1e3)}s (${n.fromRetryAfter?`npm's Retry-After`:`our backoff — npm advised nothing`}), and holding the whole sweep back while it lasts.`))},Q={gate:oe,onRateLimit},ce=Math.max(1,Math.min(50,Math.ceil(re.length/10))),le=0,ue=0,de=0;re.length>ce&&log(`Reading trust state for ${re.length} package(s)…`);let fe=await probeAllTrustStates(ae,re,Math.max(1,n.concurrency),{registryOverride:n.registry,npmrc:I,repository:q,workflow:Y},{...Q,onProgress:(n,S,C)=>{if(C.action===`trust`||C.action===`publish-and-trust`?le++:C.action===`skip`?ue++:de++,n%ce!==0&&n!==S||S<=ce)return;let N=[`${le} to do`,`${ue} already done`];de>0&&N.push(`${de} unreadable`),log(` read ${n}/${S} — ${N.join(`, `)}`)}}),pe=fe.filter(n=>n.action===`publish-and-trust`),me=fe.filter(n=>n.action===`trust`),he=fe.filter(n=>n.action===`skip`),ge=fe.filter(n=>n.action===`blocked`);for(let S of fe)S.action===`skip`&&n.verbose!==!0||log(` ${statusCell(S)} ${S.ws.name}`);!n.verbose&&he.length>0&&log(` (${he.length} already published + trusted — pass -v to list)`),log(),log(`Plan: ${he.length} already done, ${pe.length} to publish+trust, ${me.length} to trust, ${ge.length} unreadable.`);let _e=ge.filter(n=>n.httpStatus===429).length;_e>0&&log(` ${_e} of those are npm rate limits (HTTP 429) that outlasted the backoff — lower --concurrency and re-run; the sweep is idempotent and picks up where it left off.`);let ye=[];if(C){for(let n of fe)ye.push({name:n.ws.name,result:n.action===`skip`?`already-done`:n.action===`blocked`?`failed`:`skipped-dry-run`,detail:n.action===`publish-and-trust`?`would publish + trust`:n.action===`trust`?`would trust`:n.action===`blocked`?`state HTTP ${n.httpStatus}`:void 0});finish(ye,fe,{asJson:N,dryRun:C,failed:ge.length,root:Z,sources:ne,discovered:te.length});return}let be=githubTrustBody({repository:q,workflow:Y,environment:X}),xe=Math.max(1,n[`write-concurrency`]),Se=pe.length+me.length,Ce=Array.from({length:fe.length}),we=0,Te=0,Ee=0,configureTrust=async(n,S,C)=>{let N=await requestWaitingOutRateLimit(ae,`POST`,n.url,be,Q),F=`${++Te}/${Se}`;N.status>=200&&N.status<300?(log(` [${F}] trusted ${n.ws.name}`),Ce[S]={name:n.ws.name,result:C?`published+trusted`:`trusted`}):N.status===409?Ce[S]={name:n.ws.name,result:C?`published+trusted`:`trusted`}:N.status===404?(log(` [${F}] ${n.ws.name}: published but not yet trust-configurable (re-run onboard)`),Ce[S]={name:n.ws.name,result:C?`published`:`failed`,detail:`trust config deferred (404)`},C||we++):(log(` [${F}] trust failed (HTTP ${N.status}) — ${n.ws.name}`),Ce[S]={name:n.ws.name,result:`failed`,detail:`trust HTTP ${N.status}`},N.status===429&&Ee++,we++)},De=[];for(let S=0;S<fe.length;S++){let C=fe[S];if(C.action===`skip`){Ce[S]={name:C.ws.name,result:`already-done`};continue}if(C.action===`blocked`){log(`→ ${C.ws.name}: cannot read trust state (HTTP ${C.httpStatus}) — skipped`),Ce[S]={name:C.ws.name,result:`failed`,detail:`state HTTP ${C.httpStatus}`},we++;continue}if(C.action===`trust`){De.push({p:C,i:S});continue}log(`→ ${C.ws.name}: building + publishing…`);try{n.build!==!1&&await buildIfPresent(C.ws,log)}catch(n){let N=n instanceof Error?n.message:String(n);log(` build failed: ${N}`),Ce[S]={name:C.ws.name,result:`failed`,detail:`build: ${N}`},we++;continue}let N=await publishWorkspace({wsDir:C.ws.location,tag:`latest`,access:n.access,provenance:!1,tolerate:!0,tolerateUntrustedNew:!1,trustedFlag:void 0,registry:C.registry,verbose:!1,json:!1,otpProvider:ie,seedOtpFirst:!1});if(!N.ok){let n=describePublishFailure(N);log(` publish failed: ${n}`),Ce[S]={name:C.ws.name,result:`failed`,detail:`publish: ${n}`},we++;continue}log(` published ${N.name}@${`version`in N?N.version:``}`),await configureTrust(C,S,N.action!==`skipped-untrusted-new`)}De.length>0&&(De.length>1&&log(`→ configuring ${De.length} Trusted Publisher(s), ${xe} at a time…`),await mapWithConcurrency(De,xe,async({p:n,i:S})=>configureTrust(n,S,!1)));for(let n of Ce)n&&ye.push(n);Ee>0&&(log(),log(`${Ee} of the failures are npm rate limits (HTTP 429) that outlasted the wait, not a problem with those packages.`),log(` Re-run to pick them up — the sweep is idempotent and skips everything already configured. A lower --write-concurrency (currently ${xe}) provokes the limit less.`)),finish(ye,fe,{asJson:N,dryRun:C,failed:we,root:Z,sources:ne,discovered:te.length})}}});function pathFor(n){return n===`win32`?Cs:xs}function isInside$1(n,S,C){let N=pathFor(C);if(!N.isAbsolute(n)||!N.isAbsolute(S))return!1;let F=S.endsWith(N.sep)?S:S+N.sep;return n===S||n.startsWith(F)}function classifyInstall(n){let S=n.env??process.env,C=n.platform??process.platform,N=pathFor(C),F=N.resolve(n.selfDir);if(S.FLATPAK_ID||isInside$1(F,gV,C)){let n=S.FLATPAK_ID??`io.github.gjsify.Cli`;return{kind:`flatpak`,evidence:S.FLATPAK_ID?`FLATPAK_ID=${S.FLATPAK_ID}`:`running from ${gV}`,updateWith:`flatpak update ${n}`,managedElsewhere:!0}}return isInside$1(F,N.resolve(n.xdgPrefix),C)?{kind:`xdg-global`,evidence:`running from the user-global prefix ${n.xdgPrefix}`,managedElsewhere:!1}:C!==`win32`&&hV.some(n=>isInside$1(F,n,C))?{kind:`system-package`,evidence:`running from the system prefix ${F}`,updateWith:"your distribution package manager (`apt upgrade` / `dnf upgrade` / …), or install the newer package from https://github.com/gjsify/gjsify/releases/latest",managedElsewhere:!0}:F.split(N.sep).includes(`node_modules`)?{kind:`npm-global`,evidence:`running from a node_modules tree at ${F}`,updateWith:`npm install -g @gjsify/cli@latest (or switch to the Node-free bootstrap)`,managedElsewhere:!0}:{kind:`unknown`,evidence:`running from ${F}, which matches no known install layout`,managedElsewhere:!1}}var hV,gV,_V=__esmMin(()=>{Hs(),hV=[`/usr/`,`/opt/`,`/snap/`],gV=`/app/`,__name$1(isInside$1,`isInside`)});function verifyPathResolution(n){let S=n.platform??process.platform,C=S===`win32`?Cs:xs,norm=n=>S===`win32`?C.resolve(n).toLowerCase():C.resolve(n);if(n.resolvedBin===null)return{ok:!1,message:`BUT nothing named \`${n.binName}\` is on PATH, so the update cannot take effect.\n\n Add the bin dir to PATH:\n ${n.binDir}`};if(norm(C.dirname(n.resolvedBin))===norm(n.binDir))return{ok:!0};let N=n.runningVersion?` (v${n.runningVersion})`:``;return{ok:!1,message:`BUT \`${n.binName}\` on PATH resolves to\n ${n.resolvedBin}${N}\nwhich is NOT the install that was just updated, so the next \`${n.binName}\`\nyou run will not be v${n.targetVersion}.\n\n If that is another install, remove it (e.g. \`npm uninstall -g ${vV}\`)\n or put ${n.binDir} ahead of it on PATH.\n If you ran this through npx/dlx, that temporary copy owns the name only for\n this run — open a new shell and check \`${n.binName} --version\`.`}}function readSelfDir(){let n=process.env.GJSIFY_CLI_PACKAGE_JSON;if(n)return Ps(Os(n));let S=fileURLToPath(import.meta.url),C=Ps(Os(S));for(let n=0;n<8&&C!==Ps(C);n++){if(existsSync(js(C,`package.json`)))return C;C=Ps(C)}return Ps(Os(S))}function readCurrentVersion(){try{let n=process.env.GJSIFY_CLI_PACKAGE_JSON;if(n){let S=JSON.parse(readFileSync(n,`utf-8`));return S.name===vV&&typeof S.version==`string`?S.version:null}let S=Ps(Os(fileURLToPath(import.meta.url)));for(let n=0;n<8&&S!==Ps(S);n++){let n=js(S,`package.json`);if(existsSync(n)){let S=JSON.parse(readFileSync(n,`utf-8`));if(S.name===vV&&typeof S.version==`string`)return S.version}S=Ps(S)}}catch{}return null}function resolveTag(n,S){let C=n[`dist-tags`]??{};return C[S]?C[S]:n.versions&&typeof n.versions==`object`&&n.versions[S]?S:null}var vV,yV,bV,xV=__esmMin(()=>{ye(),Vl(),Hs(),gn(),ep(),bF(),_V(),wF(),uF(),fB(),vV=`@gjsify/cli`,yV={command:`self-update`,description:`Update the installed ${vV} to the latest release (or pinned --tag).`,builder:n=>n.option(`check`,{description:`Only check whether a newer version is available; do not install.`,type:`boolean`,default:!1}).option(`force`,{description:`Reinstall even when the current version already matches the target tag.`,type:`boolean`,default:!1}).option(`tag`,{description:"npm dist-tag or pinned version to install (e.g. `latest`, `next`, `0.5.0`).",type:`string`,default:`latest`}).option(`prune`,{description:`After updating, remove packages an earlier install left behind that this host cannot use (foreign os/cpu/libc). Use --no-prune to disable.`,type:`boolean`,default:!0}).option(`skip-deps`,{description:`Update only the @gjsify/cli bundle itself; do not pull its runtime dependencies (rolldown, lightningcss, @gjsify/tsc, the native gi:// bridges, …). Faster, but can leave the on-disk runtime deps stale relative to the new bundle.`,type:`boolean`,default:!1}),handler:async n=>{let S=defaultGlobalLayout(),C=js(js(S.prefix,`node_modules`,vV),`package.json`),N=readCurrentVersion(),F=existsSync(C);ve.log(`Current ${vV}: v${N??`(unknown)`}`);let I=classifyInstall({selfDir:readSelfDir(),xdgPrefix:S.prefix});if(I.managedElsewhere)return ve.error(`\ngjsify self-update: this gjsify is managed by something else — ${I.evidence}.\nUpdating it from here would write ${S.prefix} and leave you running two installs.\n\nUpdate with: ${I.updateWith}\n`),process.exit(1);F||ve.warn(`\nWarning: no @gjsify/cli install found under ${S.prefix}.\nself-update only manages installs created by install.mjs or \`gjsify install -g\`.\nIf you installed via \`npm install -g\`, remove that and use:\n curl -fsSL https://github.com/gjsify/gjsify/releases/latest/download/install.mjs -o /tmp/g.mjs && gjs -m /tmp/g.mjs && rm /tmp/g.mjs`),ve.log(`Fetching dist-tags for ${vV}@${n.tag} ...`);let H;try{H=await fetchPackument(vV)}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`Failed to fetch packument: ${S}`),process.exit(1)}let W=resolveTag(H,n.tag);if(!W)return ve.error(`Unknown dist-tag '${n.tag}' on ${vV}. Known tags: ${Object.keys(H[`dist-tags`]??{}).join(`, `)||`(none)`}`),process.exit(1);ve.log(`Latest matching --tag ${n.tag}: v${W}`);let q=F&&!hasBundlerEngineInstalled(S.prefix),Y=q&&!n.skipDeps&&!n.check;if(N===W&&!n.force&&!Y){ve.log(`Already up to date (v${W}).`),q&&n.skipDeps&&ve.log("Note: the GJS bundler engine @gjsify/rolldown-native is not installed — re-run without --skip-deps to repair it (`gjsify build` needs it under GJS)."),n.check||ve.log(`Run with --force to reinstall anyway.`);return}if(Y&&N===W&&!n.force&&ve.log(`@gjsify/cli is at v${W} but the GJS bundler engine @gjsify/rolldown-native is missing — repairing.`),n.check)return ve.log(N?`Update available: v${N} → v${W}`:`Install required: → v${W}`),process.exit(1);let X=!n.skipDeps,Z=X?` + runtime dependencies`:` (bundle only)`;ve.log(`Installing ${vV}@${W}${Z} ...`);let te=makeProgressReporter();try{await installPackages({prefix:S.prefix,specs:[`${vV}@${W}`],verbose:!1,skipDeps:!X,progress:te})}catch(n){let S=n instanceof Error?n.message:String(n);return ve.error(`self-update: install failed — ${S}`),ve.error("Re-run `gjsify self-update` to retry."),process.exit(1)}X&&await installGjsEnginePackages(S.prefix,W,{verbose:!1}),n.prune!==!1&&pruneAfterInstall(S.prefix,resolveHostPlatform({env:{}}),{hint:`gjsify prune -g --dry-run`});let ne=linkGlobalBins([vV],S);if(ne.length===0)ve.warn("self-update: install completed but no bins were linked — package.json may be missing a `bin` field.");else for(let n of ne)ve.log(` • ${n.link} → ${n.target}`);if(globalLayoutIsDefault()){let n=verifyPathResolution({binName:bV,binDir:S.binDir,resolvedBin:resolveBinOnPath(bV),runningVersion:N,targetVersion:W});if(!n.ok)return ve.error(`\nInstalled ${vV} v${W} at ${S.prefix}`),ve.error(n.message),process.exit(1)}ve.log(`\nUpdated ${vV} to v${W}.`),X?ve.log(`Runtime dependencies were resolved alongside the bundle.`):ve.log(`Bundle-only update (--skip-deps): on-disk runtime dependencies were left unchanged.`)}},bV=`gjsify`});function loadInstallerTemplate(){return`#!/usr/bin/env -S gjs -m
|
|
1146
1150
|
/**
|
|
1147
1151
|
* gjsify universal installer — bootstraps \`@gjsify/cli\` (or any GJS app on npm)
|
|
1148
1152
|
* on a system that has only \`gjs\` and libsoup: no Node, no npm. Decision and
|
|
@@ -1667,22 +1671,22 @@ async function main() {
|
|
|
1667
1671
|
}
|
|
1668
1672
|
|
|
1669
1673
|
await main();
|
|
1670
|
-
`}function pickDefaultBinName(n,S){let C=n?.gjsify?.bin;if(C&&typeof C==`object`){let n=Object.keys(C)[0];if(n)return n}let N=n?.bin;if(N&&typeof N==`object`){let n=Object.keys(N)[0];if(n)return n}return S.startsWith(`@`)?S.slice(S.indexOf(`/`)+1):S}var
|
|
1671
|
-
`).find(n=>/^exec (?:gjs -m )?'/.test(n));if(!C)continue;let I=C.match(/'([^']+)'/);if(!I)continue;let H=I[1];if(isInside(S,H)){N.push(F);for(let n of[`.cmd`,`.ps1`])existsSync(F+n)&&N.push(F+n)}}catch(n){C&&ve.warn(` ? could not inspect ${F}: ${n.message}`)}}return N}var
|
|
1672
|
-
No packages removed.`),process.exit(1))}}});function handleInit({cwd:n,force:S}){let writeOne=(C,N)=>{let F=Os(n,C);if(existsSync(F)&&!S){ve.log(`[gjsify format] ${C} exists at ${F} — pass --force to overwrite.`);return}writeFileSync(F,N,`utf-8`),ve.log(`[gjsify format] wrote ${F}`)};writeOne(`.oxlintrc.json`,loadOxlintTemplate()),writeOne(`.oxfmtrc.json`,loadOxfmtTemplate()),ve.log("[gjsify format] Run `gjsify format` to apply the formatter to the project.")}var
|
|
1673
|
-
[gjsify upgrade --align] --dry-run: no files changed.`);return}let F=applyToFiles(N,S.exact);ve.log(`\n✏️ updated ${N.length} dep(s) across ${F} package.json file(s).`)}async function resolveCandidateGroups(n,S,C,N){let F=[],I=0;async function worker(){for(;;){let H=I++;if(H>=n.length)return;let W=n[H];try{let n=(await fetchPackument(W.name,{npmrc:S}))[`dist-tags`]?.latest;if(!n){C&&ve.warn(` ${W.name}: no dist-tags.latest, skipping`);continue}let I=W.highestVersion;if(!I){C&&ve.warn(` ${W.name}: unable to parse any current range`);continue}let H=classifyDiff(I,n);if(H===`none`||N===`minor`&&H===`major`||N===`patch`&&(H===`major`||H===`minor`))continue;F.push({...W,latestVersion:n,diff:H})}catch(n){C&&ve.warn(` ${W.name}: fetch failed (${n.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),F.sort((n,S)=>n.name.localeCompare(S.name)),F}function classifyDiff(n,S){let C=parse(n),N=parse(S);return!C||!N?`none`:C.major===N.major?C.minor===N.minor?C.patch===N.patch?(C.prerelease??[]).join(`.`)===(N.prerelease??[]).join(`.`)?`none`:`prerelease`:N.patch>C.patch?`patch`:`none`:N.minor>C.minor?`minor`:`none`:N.major>C.major?`major`:`none`}function colorForDiff(n){switch(n){case`major`:return
|
|
1674
|
-
Select upgrades: comma- or space-separated indices, `+
|
|
1674
|
+
`}function pickDefaultBinName(n,S){let C=n?.gjsify?.bin;if(C&&typeof C==`object`){let n=Object.keys(C)[0];if(n)return n}let N=n?.bin;if(N&&typeof N==`object`){let n=Object.keys(N)[0];if(n)return n}return S.startsWith(`@`)?S.slice(S.indexOf(`/`)+1):S}var SV,CV,wV=__esmMin(()=>{ye(),Vl(),Hs(),SV=`https://github.com/gjsify/gjsify/releases/latest/download/cli.gjs.mjs`,CV={command:`generate-installer [target]`,description:`Scaffold an install.mjs in the current directory for a GJS-runnable npm package.`,builder:n=>n.positional(`target`,{description:`Npm package name to install (default: current package.json name).`,type:`string`}).option(`bin-name`,{description:"Bin name produced by the installer (default: first key of `gjsify.bin` or `bin`).",type:`string`}).option(`bootstrap-url`,{description:`Override the cli.gjs.mjs bootstrap bundle URL (default: gjsify GitHub releases/latest).`,type:`string`}).option(`output`,{description:`Where to write the generated installer.`,type:`string`,default:`install.mjs`}).option(`force`,{description:`Overwrite an existing output file.`,type:`boolean`,default:!1}),handler:n=>{let S=Os(process.cwd(),n.output);if(existsSync(S)&&!n.force)return ve.error(`${n.output} already exists. Re-run with --force to overwrite.`),process.exit(1);let C=Os(process.cwd(),`package.json`),N=null;if(existsSync(C))try{N=JSON.parse(readFileSync(C,`utf-8`))}catch{}let F=n.target??N?.name;if(!F)return ve.error("No target package: pass `gjsify generate-installer <pkg>` or run inside a directory with a package.json."),process.exit(1);let I=n[`bin-name`]??pickDefaultBinName(N,F),H=n[`bootstrap-url`]??SV;writeFileSync(S,loadInstallerTemplate().replace(/const DEFAULT_TARGET = '[^']+';/,`const DEFAULT_TARGET = ${JSON.stringify(F)};`).replace(/const DEFAULT_BIN_NAME = '[^']+';/,`const DEFAULT_BIN_NAME = ${JSON.stringify(I)};`).replace(/const DEFAULT_BOOTSTRAP_URL =\s*'[^']+';/,`const DEFAULT_BOOTSTRAP_URL = ${JSON.stringify(H)};`),{mode:493}),ve.log(`Wrote ${n.output} (target=${F}, bin=${I}).`),ve.log(``),ve.log(`Install one-liner for your README:`),ve.log(` curl -fsSL https://github.com/<you>/<repo>/raw/main/${n.output} -o /tmp/i.mjs \\`),ve.log(` && gjs -m /tmp/i.mjs && rm /tmp/i.mjs`)}}}),TV,EV=__esmMin(()=>{ye(),Vl(),eF(),wF(),uF(),fB(),TV={command:`prune`,description:`Remove installed packages this host cannot use (foreign os/cpu/libc). Reads each package manifest — a package that declares no platform is never touched.`,builder:n=>n.option(`global`,{description:"Prune the user-global XDG prefix (the `install -g` target) instead of the project.",type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Report what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`List every package rather than the first few.`,type:`boolean`,default:!1}).option(`os`,{description:`Prune AS IF the host were this OS (linux, darwin, win32). Defaults to this host.`,type:`string`}).option(`cpu`,{description:`Prune AS IF the host were this architecture (x64, arm64, …). Defaults to this host.`,type:`string`}).option(`libc`,{description:`Prune AS IF the host used this libc (glibc, musl). Defaults to this host.`,type:`string`}),handler:async n=>{let S=n.global?defaultGlobalLayout():null,C=S?S.prefix:process.cwd();if(!existsSync(`${C}/node_modules`)){ve.log(`gjsify prune: nothing installed at ${C}`);return}let N=resolveHostPlatform({env:{...n.os?{npm_config_os:n.os}:{},...n.cpu?{npm_config_cpu:n.cpu}:{},...n.libc?{npm_config_libc:n.libc}:{}}}),F=await acquireInstallLock(C,{}),I;try{I=executePrune(planPrune({prefix:C,target:N}),{dryRun:n.dryRun})}finally{F.release()}if(ve.log(formatPruneReport(I,{dryRun:n.dryRun,verbose:n.verbose})),I.failed.length>0)return process.exit(1)}}});function isInside(n,S){let C=Ms(n,S);return C===``?!0:C!==`..`&&!C.startsWith(`..${zs}`)&&!As(C)}function findBinShimsForPackage(n,S,C){if(!existsSync(n))return[];let N=[],F;try{F=readdirSync(n)}catch{return[]}for(let I of F){let F=js(n,I);try{if(!statSync(F).isFile())continue;let n=readFileSync(F,`utf-8`);if(!n.startsWith(`#!/bin/sh`))continue;let C=n.split(`
|
|
1675
|
+
`).find(n=>/^exec (?:gjs -m )?'/.test(n));if(!C)continue;let I=C.match(/'([^']+)'/);if(!I)continue;let H=I[1];if(isInside(S,H)){N.push(F);for(let n of[`.cmd`,`.ps1`])existsSync(F+n)&&N.push(F+n)}}catch(n){C&&ve.warn(` ? could not inspect ${F}: ${n.message}`)}}return N}var DV,OV=__esmMin(()=>{ye(),Vl(),Hs(),wF(),DV={command:`uninstall <packages..>`,description:"Uninstall a previously installed package. Currently only `--global` mode is supported.",builder:n=>n.positional(`packages`,{description:`Package(s) to uninstall (npm names, optionally with version).`,type:`string`,array:!0,demandOption:!0}).option(`global`,{description:`Uninstall from the user-global XDG location (the install -g target).`,type:`boolean`,alias:`g`,default:!1}).option(`dry-run`,{description:`Show what would be removed without touching the filesystem.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Verbose logging.`,type:`boolean`,default:!1}),handler:n=>{if(!n.global)return ve.error("gjsify uninstall currently only supports --global. For project-local removal, edit package.json + re-run `gjsify install`."),process.exit(1);let S=defaultGlobalLayout(),C=n[`dry-run`]??!1,N=n.verbose??!1,F=`gjsify uninstall${C?` (dry-run)`:``} --global`;ve.log(`${F} ← ${S.prefix}`),ve.log(`${` `.repeat(F.length)} bins ← ${S.binDir}`);let I=!1;for(let F of n.packages){let n=specToPackageName(F),H=js(S.prefix,`node_modules`,n);if(!existsSync(H)){ve.warn(` ✗ ${n} — not installed at ${H}`);continue}let W=findBinShimsForPackage(S.binDir,H,N);if(C){ve.log(` • would remove ${H}`);for(let n of W)ve.log(` • would remove ${n}`)}else{rmSync(H,{recursive:!0,force:!0}),ve.log(` • removed ${H}`);for(let n of W)unlinkSync(n),ve.log(` • removed ${n}`)}I=!0}I||(ve.error(`
|
|
1676
|
+
No packages removed.`),process.exit(1))}}});function handleInit({cwd:n,force:S}){let writeOne=(C,N)=>{let F=Os(n,C);if(existsSync(F)&&!S){ve.log(`[gjsify format] ${C} exists at ${F} — pass --force to overwrite.`);return}writeFileSync(F,N,`utf-8`),ve.log(`[gjsify format] wrote ${F}`)};writeOne(`.oxlintrc.json`,loadOxlintTemplate()),writeOne(`.oxfmtrc.json`,loadOxfmtTemplate()),ve.log("[gjsify format] Run `gjsify format` to apply the formatter to the project.")}var kV,AV=__esmMin(()=>{ye(),Vl(),Hs(),XI(),kV={command:`format [paths..]`,description:`Format JS/TS source files via oxfmt (CSS/JSON formatting is not supported).`,builder:n=>n.positional(`paths`,{description:"Files or directories to format. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Modify files in place (default: true). Pass --no-write to report drift instead.`,type:`boolean`,default:!0}).option(`check`,{description:`Report formatting drift without modifying files; exit non-zero if any file is unformatted. Useful for CI.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxfmtrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`init`,{description:`Write recommended .oxlintrc.json + .oxfmtrc.json into cwd (skips existing files unless --force).`,type:`boolean`,default:!1}).option(`force`,{description:`Overwrite existing .oxlintrc.json / .oxfmtrc.json with --init.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Echo the resolved oxfmt launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd();if(n.init){handleInit({cwd:S,force:n.force??!1});return}let C=n.paths?.length?n.paths:[`.`],N=[];n.check?N.push(`--check`):n.write===!1?N.push(`--list-different`):N.push(`--write`);let F=n.configPath??findOxfmtConfig(S)??void 0;F&&N.push(`--config`,Os(F)),N.push(...C);try{setOxcExitCode(await runOxfmt(N,{cwd:S,verbose:n.verbose}))}catch(n){if(n instanceof OxcNotFoundError){printOxcNotFound(n),setOxcExitCode(1);return}throw n}}}}),jV,MV=__esmMin(()=>{Hs(),XI(),jV={command:`lint [paths..]`,description:`Run oxlint diagnostics (spawned via its Node launcher to support JS plugins).`,builder:n=>n.positional(`paths`,{description:"Files or directories to lint. Default: `.`",type:`string`,array:!0}).option(`fix`,{description:`Apply safe lint fixes in place.`,type:`boolean`,default:!1}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxlint launcher + args before spawning.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=n.paths?.length?n.paths:[`.`],N=[];n.fix&&N.push(`--fix`);let F=n.configPath??findOxlintConfig(S)??void 0;F&&N.push(`--config`,Os(F)),N.push(...C);try{setOxcExitCode(await runOxlint(N,{cwd:S,verbose:n.verbose}))}catch(n){if(n instanceof OxcNotFoundError){printOxcNotFound(n),setOxcExitCode(1);return}throw n}}}}),NV,PV=__esmMin(()=>{Hs(),XI(),NV={command:`fix [paths..]`,description:`Run oxfmt --write then oxlint --fix — format + safe lint fixes in one pass.`,builder:n=>n.positional(`paths`,{description:"Files or directories to fix. Default: `.`",type:`string`,array:!0}).option(`write`,{description:`Apply fixes in place (default: true). Pass --no-write to report only.`,type:`boolean`,default:!0}).option(`config-path`,{description:`Path to an .oxlintrc.json. Default: walks up from cwd to find one.`,type:`string`,normalize:!0}).option(`verbose`,{description:`Echo the resolved oxc launchers + args before spawning.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=n.paths?.length?n.paths:[`.`],N=n.verbose??!1,F=n.write!==!1;try{let I=[F?`--write`:`--list-different`],H=n.configPath??findOxfmtConfig(S)??void 0;H&&I.push(`--config`,Os(H)),I.push(...C);let W=await runOxfmt(I,{cwd:S,verbose:N}),q=[];F&&q.push(`--fix`);let Y=n.configPath??findOxlintConfig(S)??void 0;Y&&q.push(`--config`,Os(Y)),q.push(...C);let X=await runOxlint(q,{cwd:S,verbose:N});setOxcExitCode(W||X)}catch(n){if(n instanceof OxcNotFoundError){printOxcNotFound(n),setOxcExitCode(1);return}throw n}}}});function createInterface(n,S){return typeof n==`object`&&n&&!(`read`in n&&typeof n.read==`function`)?new Interface(n):new Interface({input:n,output:S})}var Interface,FV=__esmMin(()=>{Ml(),Interface=class extends Interface$1{question(n,S){return new Promise(S=>{super.question(n,S)})}}});function semverGt(n,S){try{return compare(n,S)===1}catch{return!1}}function groupByDependency(n){let S=new Map;for(let C of n){let n=S.get(C.name);n||(n={name:C.name,occurrences:[],declaredRanges:new Set,dominantRange:C.currentRange,highestVersion:C.currentVersion},S.set(C.name,n)),n.occurrences.push(C),n.declaredRanges.add(C.currentRange),C.currentVersion&&(!n.highestVersion||semverGt(C.currentVersion,n.highestVersion))&&(n.highestVersion=C.currentVersion)}for(let n of S.values()){let S=new Map;for(let C of n.occurrences)S.set(C.currentRange,(S.get(C.currentRange)??0)+1);let C=n.occurrences[0].currentRange,N=-1,F=null;for(let[n,I]of S.entries()){let S=parse(n.replace(/^[\^~>=<]+/,``))?.version??null;(I>N||I===N&&S&&F&&semverGt(S,F)||I===N&&n<C)&&(C=n,N=I,F=S)}n.dominantRange=C}return[...S.values()].sort((n,S)=>n.name.localeCompare(S.name))}function isInconsistent(n){return n.declaredRanges.size>1}function findInconsistencies(n){return n.filter(isInconsistent)}var IV=__esmMin(()=>{zP()});function discoverContext(n){let S=findWorkspaceRoot(n);if(S)return{root:S,workspaces:discoverWorkspaces(S,{includeRoot:!0}),isMonorepo:!0};let C=js(n,`package.json`);if(!existsSync(C))throw Error(`[gjsify upgrade] no package.json at ${C}`);let N=JSON.parse(readFileSync(C,`utf-8`));return{root:n,workspaces:[{name:N.name??`<root>`,location:n,relativeLocation:`.`,version:N.version??`0.0.0`,manifest:N,private:N.private===!0}],isMonorepo:!1}}function applyWorkspaceFilter(n,S,C){let N=S?.split(`,`).map(n=>n.trim()).filter(Boolean),F=C?.split(`,`).map(n=>n.trim()).filter(Boolean);return(!N||N.length===0)&&(!F||F.length===0)?n:filterWorkspaces(n,{include:N,exclude:F})}function parseFilterList(n){return n?n.split(`,`).map(n=>n.trim().toLowerCase()).filter(Boolean):[]}function collectAllDeclarations(n,S){let C=[];for(let N of n)for(let n of collectFromWorkspace(N,S))C.push(n);return C}function collectFromWorkspace(n,S){let C=[],N=n.manifest;for(let F of RV){let I=N[F];if(!(!I||typeof I!=`object`))for(let[N,H]of Object.entries(I)){if(typeof H!=`string`||S.length&&!S.some(n=>N.toLowerCase().includes(n))||H.startsWith(`workspace:`)||H.startsWith(`file:`)||H.startsWith(`link:`)||H.startsWith(`git+`)||H.startsWith(`git:`)||H.startsWith(`http:`)||H.startsWith(`https:`)||H.startsWith(`npm:`)||H.startsWith(`portal:`))continue;let{prefix:I,version:W}=splitRange(H);C.push({workspace:n.name,workspaceLocation:n.location,name:N,field:F,currentRange:H,currentVersion:W,prefix:I})}}return C}function splitRange(n){let S=n.match(/^(\^|~|>=|<=|>|<|=)?\s*([0-9].*)$/);if(!S)return{prefix:``,version:null};let C=S[1]??``,N=S[2]?.split(/\s|[|&,]/)[0]??null;return{prefix:C,version:(N?parse(N):null)?.version??null}}function reportInexactRanges(n){let S=n.map(n=>({name:n.name,loose:n.occurrences.filter(n=>n.prefix!==``)})).filter(n=>n.loose.length>0);if(S.length===0)return 0;let C=S.reduce((n,S)=>n+S.loose.length,0);ve.error(`gjsify upgrade --check --exact: FAIL. ${C} declaration(s) across ${S.length} dep(s) carry a range operator:\n`);for(let n of S){let S=new Map;for(let C of n.loose){let n=S.get(C.currentRange)??[];n.push(C.workspace),S.set(C.currentRange,n)}ve.error(` ${zV.bold}${n.name}${zV.reset}`);for(let[n,C]of S.entries()){let S=C.length>6?`${C.slice(0,6).join(`, `)} … +${C.length-6}`:C.join(`, `);ve.error(` ${n.padEnd(16)} — ${S}`)}}return C}function runCheckMode(n,S=!1){let C=S?reportInexactRanges(n):0,N=findInconsistencies(n);if(N.length===0&&C>0)return ve.error("\nFix: run `gjsify upgrade --align --exact` (offline; drops the operator and keeps the version)."),process.exit(1);if(N.length===0){ve.log(`gjsify upgrade --check: OK. ${n.length} dep(s) consistently declared across workspaces`+(S?`, every declaration pinned exactly.`:`.`));return}ve.error(`gjsify upgrade --check: FAIL. ${N.length} dep(s) declared at inconsistent ranges:\n`);for(let n of N){let S=new Map;for(let C of n.occurrences){let n=S.get(C.currentRange)??[];n.push(C.workspace),S.set(C.currentRange,n)}ve.error(` ${zV.bold}${n.name}${zV.reset}`);for(let[n,C]of S.entries())ve.error(` ${n.padEnd(16)} — ${C.join(`, `)}`)}ve.error("\nFix: run `gjsify upgrade --align` (offline; aligns each dep to its highest declared range)."),process.exit(1)}function runAlignMode(n,S){let C=findInconsistencies(n);if(C.length===0){ve.log(`gjsify upgrade --align: nothing to do. ${n.length} dep(s) already consistent.`);return}let N=[];for(let n of C){if(!n.highestVersion)continue;let S=n.occurrences.find(S=>S.currentRange===n.dominantRange)?.prefix||`^`;N.push({...n,latestVersion:n.highestVersion,diff:`none`,occurrences:n.occurrences.map(n=>({...n,prefix:S}))})}if(N.length===0){ve.log(`gjsify upgrade --align: inconsistencies present but no parseable target version. No-op.`);return}ve.log(`gjsify upgrade --align: aligning ${N.length} inconsistent dep(s) to their highest declared version:\n`);for(let n of N){let C=n.occurrences[0]?.prefix??`^`;ve.log(` ${n.name.padEnd(28)} ranges: ${[...n.declaredRanges].join(`, `)} → ${targetRange(C,n.latestVersion,S.exact??!1)}`)}if(S.dryRun){ve.log(`
|
|
1677
|
+
[gjsify upgrade --align] --dry-run: no files changed.`);return}let F=applyToFiles(N,S.exact);ve.log(`\n✏️ updated ${N.length} dep(s) across ${F} package.json file(s).`)}async function resolveCandidateGroups(n,S,C,N){let F=[],I=0;async function worker(){for(;;){let H=I++;if(H>=n.length)return;let W=n[H];try{let n=(await fetchPackument(W.name,{npmrc:S}))[`dist-tags`]?.latest;if(!n){C&&ve.warn(` ${W.name}: no dist-tags.latest, skipping`);continue}let I=W.highestVersion;if(!I){C&&ve.warn(` ${W.name}: unable to parse any current range`);continue}let H=classifyDiff(I,n);if(H===`none`||N===`minor`&&H===`major`||N===`patch`&&(H===`major`||H===`minor`))continue;F.push({...W,latestVersion:n,diff:H})}catch(n){C&&ve.warn(` ${W.name}: fetch failed (${n.message})`)}}}return await Promise.all(Array.from({length:8},()=>worker())),F.sort((n,S)=>n.name.localeCompare(S.name)),F}function classifyDiff(n,S){let C=parse(n),N=parse(S);return!C||!N?`none`:C.major===N.major?C.minor===N.minor?C.patch===N.patch?(C.prerelease??[]).join(`.`)===(N.prerelease??[]).join(`.`)?`none`:`prerelease`:N.patch>C.patch?`patch`:`none`:N.minor>C.minor?`minor`:`none`:N.major>C.major?`major`:`none`}function colorForDiff(n){switch(n){case`major`:return zV.red;case`minor`:return zV.yellow;case`patch`:return zV.green;case`prerelease`:return zV.cyan;default:return``}}function printTable(n){let S=Math.max(...n.map(n=>n.name.length),4),C=Math.max(...n.map(n=>`${n.occurrences.length}`.length+2),3),N=Math.max(...n.map(n=>declaredCellWidth(n)),7),F=Math.max(...n.map(n=>n.latestVersion.length),6),I=String(n.length).length+2,H=` `.repeat(I+2)+zV.bold+`name`.padEnd(S)+` `+`fan`.padEnd(C)+` `+`declared`.padEnd(N)+` `+`latest`.padEnd(F)+` kind`+zV.reset;ve.log(H),ve.log(` `.repeat(I+2)+zV.dim+`─`.repeat(S+C+N+F+16)+zV.reset);for(let H=0;H<n.length;H++){let W=n[H],q=`${H+1}.`.padEnd(I),Y=W.declaredRanges.size>1?`${zV.magenta}⚠ ${zV.reset}`:` `,X=colorForDiff(W.diff);ve.log(q+Y+W.name.padEnd(S)+` `+zV.dim+`${W.occurrences.length}`.padEnd(C)+zV.reset+` `+zV.dim+renderDeclaredCell(W).padEnd(N)+zV.reset+` `+X+W.latestVersion.padEnd(F)+zV.reset+` `+X+W.diff+zV.reset)}let W=n.filter(n=>n.declaredRanges.size>1).length;W>0&&ve.log(`\n${zV.magenta}⚠${zV.reset} ${W} dep(s) declared at inconsistent ranges across workspaces.`)}function declaredCellWidth(n){return renderDeclaredCell(n).length}function renderDeclaredCell(n){if(n.declaredRanges.size===1)return[...n.declaredRanges][0];let S=[...n.declaredRanges].sort().join(`, `);return S.length<=32?S:S.slice(0,29)+`…`}function printChangePlan(n,S=!1){for(let C of n)for(let n of C.occurrences)ve.log(` ${n.workspace.padEnd(38)} ${C.name.padEnd(28)} ${n.currentRange.padEnd(12)} → ${targetRange(n.prefix,C.latestVersion,S)}`)}async function promptSelection(n){if(!process.stdin.isTTY)return ve.log(`[gjsify upgrade] non-TTY stdin: pass --latest / --minor / --patch (or --yes for interactive-all) to upgrade non-interactively.`),[];let S=createInterface({input:process.stdin,output:process.stdout});try{ve.log(`
|
|
1678
|
+
Select upgrades: comma- or space-separated indices, `+zV.bold+`a`+zV.reset+` for all, ranges like `+zV.bold+`1-3`+zV.reset+`, or `+zV.bold+`ENTER`+zV.reset+` to skip:`);let C=(await S.question(`> `)).trim();if(!C)return[];if(C.toLowerCase()===`a`||C.toLowerCase()===`all`)return[...n];let N=new Set;for(let n of C.split(/[\s,]+/).filter(Boolean)){let S=n.match(/^(\d+)-(\d+)$/);if(S){let n=Number(S[1]),C=Number(S[2]);for(let S=Math.min(n,C);S<=Math.max(n,C);S++)N.add(S-1)}else/^\d+$/.test(n)&&N.add(Number(n)-1)}return[...N].filter(S=>S>=0&&S<n.length).map(S=>n[S])}finally{S.close()}}function targetRange(n,S,C){return C?S:`${n}${S}`}function applyToFiles(n,S=!1){let C=new Map;for(let S of n)for(let n of S.occurrences){let N=C.get(n.workspaceLocation)??[];N.push({...S,occurrences:[n]}),C.set(n.workspaceLocation,N)}let N=0;for(let[n,F]of C.entries()){let C=js(n,`package.json`),I=readFileSync(C,`utf-8`),H=JSON.parse(I),W=!1,q=[];for(let n of F){let C=n.occurrences[0],N=H[C.field];if(!N)continue;let F=targetRange(C.prefix,n.latestVersion,S);N[n.name]!==F&&(N[n.name]=F,W=!0,q.push(n.name))}if(W){let n=detectIndent(I);writeFileSync(C,keepUntouchedLines(I,JSON.stringify(H,null,n)+(I.endsWith(`
|
|
1675
1679
|
`)?`
|
|
1676
1680
|
`:``),q),`utf-8`),N++}}return N}function keepUntouchedLines(n,S,C){let N=n.split(`
|
|
1677
1681
|
`),F=S.split(`
|
|
1678
1682
|
`);return N.length===F.length?F.map((n,S)=>C.some(S=>n.includes(`"${S}"`))?n:N[S]).join(`
|
|
1679
|
-
`):S}function uniqueLocations(n){let S=new Set;for(let C of n)for(let n of C.occurrences)S.add(n.workspaceLocation);return[...S]}function detectIndent(n){let S=n.match(/^\{\n( +)/);return S?S[1].length:2}async function loadNpmrcLight(n){let S={registry:qf,scopes:{},authTokens:{},basicAuth:{}};for(let C of[js(homedir(),`.npmrc`),js(n,`.npmrc`)])if(existsSync(C))try{let n=parseNpmrc(readFileSync(C,`utf-8`));S={...S,...n,scopes:{...S.scopes,...n.scopes}}}catch{}return process.env.npm_config_registry&&(S.registry=process.env.npm_config_registry),S}var
|
|
1683
|
+
`):S}function uniqueLocations(n){let S=new Set;for(let C of n)for(let n of C.occurrences)S.add(n.workspaceLocation);return[...S]}function detectIndent(n){let S=n.match(/^\{\n( +)/);return S?S[1].length:2}async function loadNpmrcLight(n){let S={registry:qf,scopes:{},authTokens:{},basicAuth:{}};for(let C of[js(homedir(),`.npmrc`),js(n,`.npmrc`)])if(existsSync(C))try{let n=parseNpmrc(readFileSync(C,`utf-8`));S={...S,...n,scopes:{...S.scopes,...n.scopes}}}catch{}return process.env.npm_config_registry&&(S.registry=process.env.npm_config_registry),S}var LV,RV,zV,BV=__esmMin(()=>{ye(),Vl(),Hs(),Dm(),FV(),zP(),ep(),GM(),qM(),IV(),LV={command:`upgrade`,description:"Workspace-aware dependency upgrades. Walks every package.json in the monorepo, groups by dep, flags inconsistencies. `--latest` / `--minor` / `--patch` for bulk-mode, `--align` for offline consistency-only mode, `--check` for CI drift detection.",builder:n=>n.option(`latest`,{description:`Non-interactive: bump every dependency to its latest version (allows major).`,type:`boolean`,default:!1}).option(`minor`,{description:`Non-interactive: bump every dependency to the latest within the same major (semver-minor + semver-patch).`,type:`boolean`,default:!1}).option(`patch`,{description:`Non-interactive: bump every dependency to the latest within the same minor (semver-patch only).`,type:`boolean`,default:!1}).option(`filter`,{description:`Only consider deps whose name matches this substring (case-insensitive). Repeatable; comma-separated values are split.`,type:`string`}).option(`workspace`,{alias:`p`,description:`Restrict to a subset of workspaces. Patterns are matched against the workspace package name AND its directory path (substring + glob). Repeatable; comma-separated values are split.`,type:`string`}).option(`exclude-workspace`,{description:`Skip workspaces matching this pattern (glob-shaped; matched against workspace package name AND directory path). Repeatable; comma-separated values are split. Use for workspaces with intentional dependency drift — e.g. integration tests pinned to specific upstream versions.`,type:`string`}).option(`align`,{description:`Offline consistency mode: find deps declared at multiple ranges across the workspace and align them to the highest. No registry calls.`,type:`boolean`,default:!1}).option(`check`,{description:"CI gate: exit non-zero when any dep is declared inconsistently across workspaces. Implies offline (no registry calls). Pairs with `--align` as the fix.",type:`boolean`,default:!1}).option(`exact`,{description:"Pin without a range operator. When writing, emits `1.2.3` instead of `^1.2.3`; with `--check`, fails on any matched dep that carries one. Pair with `--filter` — a repository-wide exactness check fails on every ordinary caret dep by design.",type:`boolean`,default:!1}).option(`dry-run`,{description:`Print the upgrade plan without writing package.json files.`,type:`boolean`,default:!1}).option(`cwd`,{description:`Project directory. Default: process.cwd(). When inside a workspace, walks up to the monorepo root.`,type:`string`}).option(`yes`,{alias:`y`,description:`Interactive mode: select all without prompting.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Print extra resolution details.`,type:`boolean`,default:!1}),handler:async n=>{let S=discoverContext(Os(n.cwd??process.cwd())),C=applyWorkspaceFilter(S.workspaces,n.workspace,n.excludeWorkspace);if(C.length===0){ve.log(`[gjsify upgrade] no matching workspaces.`);return}let N=collectAllDeclarations(C,parseFilterList(n.filter));if(N.length===0){ve.log(`[gjsify upgrade] no external npm dependencies to check.`);return}let F=groupByDependency(N);if(n.check)return runCheckMode(F,n.exact);if(n.align)return runAlignMode(F,n);let I=await loadNpmrcLight(S.root),H=n.latest?`latest`:n.minor?`minor`:n.patch?`patch`:`interactive`;ve.log(`[gjsify upgrade] checking ${F.length} unique deps across ${C.length} workspace(s) against ${I.registry}…`);let W=await resolveCandidateGroups(F,I,n.verbose??!1,H);if(W.length===0){ve.log(`✅ all dependencies are up to date`);let n=findInconsistencies(F);n.length>0&&ve.log(`\n⚠ ${n.length} dep(s) declared at inconsistent ranges across workspaces. Run \`gjsify upgrade --align\` to fix.`);return}printTable(W);let q;if(H===`interactive`&&!n.yes?q=await promptSelection(W):(n.yes&&H===`interactive`&&ve.log(`[gjsify upgrade] -y / --yes: selecting all`),q=W),q.length===0){ve.log(`[gjsify upgrade] nothing selected; no files changed.`);return}if(n.dryRun){let S=uniqueLocations(q).length;ve.log(`[gjsify upgrade] --dry-run: would update ${q.length} deps across ${S} package.json file(s).`),printChangePlan(q,n.exact);return}let Y=applyToFiles(q,n.exact);ve.log(`✏️ updated ${q.length} dep(s) across ${Y} package.json file(s). Run \`gjsify install\` to apply.`)}},RV=[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`],zV={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,green:`\x1B[32m`,cyan:`\x1B[36m`,magenta:`\x1B[35m`}});async function generateBarrels(n){let S=n.singleQuotes?`'`:`"`,C=n.noSemicolon?``:`;`,N=n.extension===`none`?``:`.${n.extension}`,F=0;for(let I of n.paths){let H=Os(n.baseDir,I),W=Fs(H)===`types`,q;try{q=(await readdir$1(H,{withFileTypes:!0})).filter(n=>n.isFile()).filter(n=>HV.test(n.name)).filter(n=>n.name!==`index.ts`).filter(S=>!n.exclude.some(n=>n.test(S.name))).sort((n,S)=>n.name.localeCompare(S.name))}catch(S){n.verbose&&ve.error(`[gjsify barrels] skip ${H}: ${S.message}`);continue}let Y=q.map(n=>{let F=Fs(n.name,Is(n.name));return`${W?`export type *`:`export *`} from ${S}./${F}${N}${S}${C}`}),X=Y.length?`${Y.join(`
|
|
1680
1684
|
`)}\n`:`export {};
|
|
1681
|
-
`,Z=`${n.header}\n\n${X}`,te=js(H,`index.ts`);if(await readFile$1(te,`utf-8`).catch(()=>``)===Z){n.verbose&&ve.log(`[gjsify barrels] up-to-date: ${te}`);continue}n.check?(ve.error(`[gjsify barrels] drift: ${te}`),F++):(await writeFile$1(te,Z,`utf-8`),n.verbose&&ve.log(`[gjsify barrels] wrote: ${te}`))}return F}var
|
|
1682
|
-
`).map(n=>n.trim()).filter(Boolean)}var
|
|
1685
|
+
`,Z=`${n.header}\n\n${X}`,te=js(H,`index.ts`);if(await readFile$1(te,`utf-8`).catch(()=>``)===Z){n.verbose&&ve.log(`[gjsify barrels] up-to-date: ${te}`);continue}n.check?(ve.error(`[gjsify barrels] drift: ${te}`),F++):(await writeFile$1(te,Z,`utf-8`),n.verbose&&ve.log(`[gjsify barrels] wrote: ${te}`))}return F}var VV,HV,UV=__esmMin(()=>{ye(),Cl(),Hs(),VV=[`\\.test\\.`,`\\.spec\\.`,`\\.test-data\\.`],HV=/\.(ts|tsx|mts|cts)$/}),WV,GV=__esmMin(()=>{ye(),UV(),WV={command:`barrels [paths..]`,description:"Regenerate `index.ts` barrel files for the given directories. Drop-in replacement for `barrelsby`.",builder:n=>n.positional(`paths`,{description:"Directories whose `index.ts` to (re)generate. May also be passed via `--paths`.",type:`string`,array:!0}).option(`paths`,{alias:`p`,description:`Alternative to positional — repeatable list of directories.`,type:`string`,array:!0}).option(`ext`,{description:"Import-specifier extension. Default: `none` (bundler-mode resolution).",type:`string`,choices:[`js`,`ts`,`none`],default:`none`}).option(`base-dir`,{alias:`b`,description:"Resolve `paths` against this directory. Default: cwd.",type:`string`}).option(`exclude`,{description:"Regex(es) of file names to skip. Repeatable. Defaults: `\\.test\\.`, `\\.spec\\.`, `\\.test-data\\.`.",type:`string`,array:!0}).option(`header`,{description:`Header comment prepended to every generated file.`,type:`string`}).option(`semicolon`,{description:"Emit trailing `;` on each export line. Negate with `--no-semicolon`. Default: omitted.",type:`boolean`,default:!1}).option(`single-quotes`,{description:"Use `'` for import specifiers. Default: true. Pass `--no-single-quotes` for `\"`.",type:`boolean`,default:!0}).option(`check`,{description:`Report drift without modifying files; exit non-zero if any barrel is stale.`,type:`boolean`,default:!1}).option(`verbose`,{description:`Log each file scanned + written.`,type:`boolean`,default:!1}),handler:async n=>{let S=Array.from(new Set((n.paths??[]).filter(Boolean)));if(S.length===0){ve.error(`[gjsify barrels] no paths provided. Pass directories as positional arguments or via --paths.`),process.exitCode=1;return}let C=n.exclude?.length?n.exclude:[...VV],N=await generateBarrels({paths:S,extension:n.ext??`none`,baseDir:n.baseDir??process.cwd(),exclude:C.map(n=>new RegExp(n)),header:n.header??"// Auto-generated by `gjsify barrels` — do not edit by hand.",noSemicolon:n.semicolon===!1||n.semicolon===void 0,singleQuotes:n.singleQuotes!==!1,check:n.check??!1,verbose:n.verbose??!1});n.check&&N>0&&(ve.error(`[gjsify barrels] ${N} barrel file(s) drifted. Run without --check to fix.`),process.exitCode=1)}}}),KV,qV=__esmMin(()=>{ye(),gs(),Hs(),gn(),gN(),dN(),Vl(),uB(),xP(),qM(),_P(),KV={command:`tsc [tscArgs..]`,description:"Run TypeScript compiler (tsc) under GJS via the @gjsify/tsc bundle. All arguments are passed through to tsc. Equivalent to `gjsify-tsc <args>` from the @gjsify/tsc bin.",builder:n=>n.parserConfiguration({"unknown-options-as-args":!0}).version(!1).help(!1).positional(`tscArgs`,{description:"Arguments forwarded verbatim to tsc (e.g. `--version`, `-p tsconfig.json`).",type:`string`,array:!0,default:[]}),handler:async n=>{let S=(n._??[]).slice(1).map(String),C=n.tscArgs??[],N=S.length>0?S:C,F=process.cwd(),I=[pathToFileURL(`${findWorkspaceRoot(F)??F}/__gjsify_tsc__.js`).href,import.meta.url],H;for(let n of I)try{H=createRequire(n).resolve(`@gjsify/tsc/bundle`);break}catch{}let W;for(let n of I)try{W=js(Ps(createRequire(n).resolve(`typescript/package.json`)),`lib`,`tsc.js`);break}catch{}if(!H&&!W)return ve.error("gjsify tsc: neither @gjsify/tsc (GJS bundle) nor npm `typescript` (Node) is installed."),ve.error(" Install with: gjsify install --save-dev @gjsify/tsc (or add `typescript`)."),forceExit(1);let q=buildNativeEnv(detectNativePackages(F)),Y={...process.env,...q},runNodeTsc=async()=>{let n=nodeBinary();if(!(n.includes(`/`)||n.includes(`\\`)?existsSync(n):isOnPath(n)))return ve.error(`gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and \`${n}\` cannot be run, so upstream \`typescript\` cannot run either.`),ve.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`),ve.error(" …or install Node.js so the upstream `typescript` fallback can be spawned."),forceExit(1);try{await new Promise((S,C)=>{spawnToCompletion(n,[W,...N],{completion:`exit`,env:Y,onSpawn:n=>{let S=!1;n.on(`error`,()=>{S=!0}),n.on(`close`,n=>{S||forceExit(n??1)})}}).catch(C)})}catch(n){let S=n;return S.code===`ENOENT`?(ve.error("gjsify tsc: the @gjsify/tsc GJS bundle is unavailable and `node` is not on PATH, so upstream `typescript` cannot run either."),ve.error(` Build the bundle with: gjsify workspace @gjsify/tsc build`)):ve.error(`gjsify tsc (node typescript): ${S.message}`),forceExit(1)}};if(H)try{await new Promise((n,S)=>{spawnToCompletion(`gjs`,[`-m`,H,...N],{completion:`exit`,env:Y,onSpawn:n=>{let S=!1;n.on(`error`,()=>{S=!0}),n.on(`close`,n=>{S||forceExit(n??1)})}}).catch(S)})}catch(n){let S=n;return S.code===`ENOENT`&&W?await runNodeTsc():(S.code===`ENOENT`?(ve.error("gjsify tsc: `gjs` not found on PATH and no npm `typescript` fallback."),ve.error(" Install GJS (e.g. `dnf install gjs`), or add `typescript` to the project.")):ve.error(`gjsify tsc: ${S.message}`),forceExit(1))}else await runNodeTsc()}}});function readStdinText(){return readFileSync(0,`utf-8`)}function readStdinLines(){return splitStdinLines(readStdinText())}function splitStdinLines(n){return n.split(`
|
|
1686
|
+
`).map(n=>n.trim()).filter(Boolean)}var JV=__esmMin(()=>{Vl()});function classifyAndExpand(n,S){let C=S.map(n=>n.replace(/\\/g,`/`)).filter(n=>n.length>0);if(C.length===0)return{global:!1,reason:`empty-diff`,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};let N=[];for(let n of C)XV.some(S=>S.test(n))||N.push(n);if(N.length===0)return{global:!1,reason:`ignored-only`,workspaces:[],runE2E:!1,runIntegration:!1,skipAll:!0};for(let S of N)for(let C of YV)if(C.test(S))return{global:!0,reason:`global-trigger ${C.source} matched ${S}`,workspaces:n.map(n=>n.name),runE2E:!0,runIntegration:!0,skipAll:!1};let{matched:F,unmatched:I}=workspacesForChangedFiles(n,N),H=new Set(n.map(n=>n.name)),W=new Set,q=new Set,Y=!1;for(let S of QV){let C=N.filter(n=>S.match.test(n));if(C.length!==0){for(let n of C)q.add(n);for(let C of S.seeds){if(!H.has(C))return{global:!0,reason:`script-coupling seed ${C} is not a workspace (${S.match.source} → ${S.why}); SCRIPT_COUPLINGS in commands/affected.ts is stale`,workspaces:n.map(n=>n.name),runE2E:!0,runIntegration:!0,skipAll:!1};W.add(C)}S.runE2E&&(Y=!0)}}let X=I.filter(n=>!q.has(n));if(X.length>0)return{global:!0,reason:`unmatched files (${X.length}): ${X.slice(0,3).join(`, `)}${X.length>3?`…`:``}`,workspaces:n.map(n=>n.name),runE2E:!0,runIntegration:!0,skipAll:!1};for(let n of W)F.add(n);if(W.size===0&&N.every(n=>ZV.some(S=>S.test(n)))&&F.size===1){let n=[...F][0],S=N.some(n=>n.startsWith(`tests/e2e/`)),C=N.some(n=>n.startsWith(`tests/integration/`));return{global:!1,reason:`test-only (${N.length} file(s) in ${n})`,workspaces:[n],runE2E:S||Y,runIntegration:C||isIntegrationWorkspace(n),skipAll:!1}}let Z=affectedClosure(buildReverseDependencyGraph(n,{includeDev:!1}),[...F]),te=buildDependencyGraph(n,{includeDev:!0}),ne=!1;for(let[n,S]of te.edges)if(isIntegrationWorkspace(n)){for(let C of S)if(Z.has(C)){Z.add(n),ne=!0;break}}let re=N.some(n=>n.startsWith(`tests/e2e/`))||Y;return{global:!1,reason:`closure (${Z.size} ws from ${F.size} seed(s))`+(W.size>0?`, ${W.size} via script-coupling`:``),workspaces:[...Z].sort(),runE2E:re,runIntegration:ne,skipAll:!1}}function isIntegrationWorkspace(n){return n.startsWith(`@gjsify/integration-`)}var YV,XV,ZV,QV,$V=__esmMin(()=>{GM(),YV=[/^packages\/infra\/workspace\//,/^packages\/infra\/cli\//,/^packages\/infra\/rolldown-plugin-gjsify\//,/^packages\/infra\/resolve-npm\//,/^packages\/gjs\/unit\//,/^\.github\/actions\//,/^gjsify-lock\.json$/,/^package\.json$/,/^tsconfig[^/]*\.json$/,/^\.github\/workflows\/main\.yml$/,/^scripts\/audit-runtimes\.mjs$/],XV=[/\.md$/i,/^refs\//,/^website\//,/^docs\//,/^\.github\/workflows\/(deploy-docs|commitlint|release|release-cut|audit-runtimes|prebuilds|node-gi|napi|cli-cross-platform|build-ci-image|cancel-pr-runs)\.yml$/,/^\.github\/prebuild-toolchain\//,/^scripts\/manifest-conformance\//,/^status\//,/^scripts\/generate-status\.mjs$/,/^packages\/node-gi\//,/^packages\/napi\//,/^flatpak\//,/^LICENSE/,/^\.gitignore$/,/^\.gjsify-[^/]*\.md$/,/^STATUS\.md$/,/^CHANGELOG\.md$/,/^AGENTS\.md$/,/^CLAUDE\.md$/,/^README\.md$/],ZV=[/\.spec\.[mc]?[tj]sx?$/,/^tests\/(e2e|integration)\//],QV=[{match:/^\.githooks\//,seeds:[],runE2E:!0,why:`tests/e2e/git-hooks-cli-bundle-staleness drives .githooks/pre-commit`},{match:/^templates\//,seeds:[`@gjsify/create-app`],runE2E:!0,why:`@gjsify/create-app build → node scripts/process-template.mjs reads templates/`},{match:/^packages\/framework\/react-native\//,seeds:[],runE2E:!0,why:`tests/e2e/react-native-devtools is the only external observer of AppRegistry.runApplication`}]});function runGitDiff(n,S,C){let N=spawnSync(`git`,[`diff`,`--name-only`,`${S}...${C}`],{cwd:n,encoding:`utf8`});if(N.status!==0)throw process.stderr.write(`gjsify affected: git diff failed (${N.status}): ${N.stderr.trim()}\n`),process.exit(2),Error(`gjsify affected: git diff failed (${N.status})`);return N.stdout.split(`
|
|
1683
1687
|
`).filter(Boolean)}function emit(n,S){if(n===`json`){process.stdout.write(JSON.stringify(S)+`
|
|
1684
1688
|
`);return}if(n===`globs`){for(let n of S.workspaces)process.stdout.write(`${n}\n`);return}if(n===`github-actions`){let n=S.global?``:S.workspaces.map(n=>`--include ${assertShellSafeWorkspaceName(n)}`).join(` `),C=process.env.GITHUB_OUTPUT,N=[`skip-all=${S.skipAll}`,`global=${S.global}`,`include-args=${n}`,`run-integration=${S.runIntegration}`,`run-e2e=${S.runE2E}`,`reason=${S.reason}`];if(C)for(let n of N)appendFileSync(C,`${n}\n`);else for(let n of N)process.stdout.write(`${n}\n`);return}process.stdout.write(`affected:
|
|
1685
|
-
`),process.stdout.write(` reason: ${S.reason}\n`),process.stdout.write(` global: ${S.global}\n`),process.stdout.write(` skip-all: ${S.skipAll}\n`),process.stdout.write(` run-integration: ${S.runIntegration}\n`),process.stdout.write(` run-e2e: ${S.runE2E}\n`),process.stdout.write(` workspaces (${S.workspaces.length}):\n`);for(let n of S.workspaces)process.stdout.write(` - ${n}\n`)}function assertShellSafeWorkspaceName(n){if(
|
|
1689
|
+
`),process.stdout.write(` reason: ${S.reason}\n`),process.stdout.write(` global: ${S.global}\n`),process.stdout.write(` skip-all: ${S.skipAll}\n`),process.stdout.write(` run-integration: ${S.runIntegration}\n`),process.stdout.write(` run-e2e: ${S.runE2E}\n`),process.stdout.write(` workspaces (${S.workspaces.length}):\n`);for(let n of S.workspaces)process.stdout.write(` - ${n}\n`)}function assertShellSafeWorkspaceName(n){if(tH.test(n))return n;throw process.stderr.write(`gjsify affected: workspace name ${JSON.stringify(n)} is not shell-safe, so it cannot be emitted as an\n \`include-args\` token (the value is consumed by an UNQUOTED $INCLUDE_ARGS expansion — see the\n contract at the top of commands/affected.ts). Rename the workspace, or teach this command a\n transport the consumers can unquote. Refusing to emit a filter that would silently mis-match.\n`),process.exit(2),Error(`gjsify affected: unsafe workspace name ${n}`)}var eH,tH,nH=__esmMin(()=>{Dh(),Vl(),JV(),GM(),$V(),qM(),eH={command:`affected`,description:"Classify changed files against the workspace tree and print the set of workspaces affected (seeds + transitive dependents). Designed for CI to gate `gjsify foreach test --include …` so unrelated workspaces are not re-tested on every PR.",builder:n=>n.option(`base`,{description:"Diff base. Default: `origin/main`. Resolved via `git rev-parse`. On a PR set this to `${{ github.event.pull_request.base.sha }}`.",type:`string`}).option(`head`,{description:"Diff head. Default: `HEAD`.",type:`string`,default:`HEAD`}).option(`format`,{description:`Output shape.`,choices:[`text`,`json`,`globs`,`github-actions`],default:`text`}).option(`changed-from-stdin`,{description:"Skip `git diff`. Read a newline-separated list of repo-relative paths from stdin instead. Lets callers — tests, ad-hoc scripts — control the input exactly.",type:`boolean`,default:!1}).option(`cwd`,{description:"Workspace root. Default: discovered from `process.cwd()`.",type:`string`}),handler:async n=>{let S=n.cwd??findWorkspaceRoot(process.cwd())??process.cwd(),C=classifyAndExpand(discoverWorkspaces(S,{includeRoot:!0}),n[`changed-from-stdin`]?readStdinLines():runGitDiff(S,n.base??`origin/main`,n.head??`HEAD`));emit(n.format,C)}},tH=/^[A-Za-z0-9@][A-Za-z0-9@._/-]*$/}),rH=__exportAll$4({isSelfWrite:()=>isSelfWrite,runWatchLoop:()=>runWatchLoop,spawnBundleSupervised:()=>spawnBundleSupervised,spawnSupervised:()=>spawnSupervised});function spawnSupervised(n,S,C){return new Promise((N,F)=>{spawnToCompletion(n,S,{completion:`daemon`,env:C,onSpawn:N}).catch(F)})}async function spawnBundleSupervised(n,S,C,N){if(n!==`gjs`){let{bundleRequiresNodeGi:F,resolveNodeGiForBundle:I}=await Promise.resolve().then(()=>(xP(),bP));if(F(S)&&!I(S,C))throw Error(`Cannot run ${N} on ${n}: \`@gjsify/node-gi\` is not installed. Add @gjsify/node-gi as a dependency to run ${N} on ${n}.`)}let{computeNativeEnvForBundle:F}=await Promise.resolve().then(()=>(yP(),vP)),{env:I}=F(S,C),H={...process.env,...I};if(n===`gjs`)return spawnSupervised(`gjs`,[`-m`,S],H);if(n===`node`){let{nodeBinary:n}=await Promise.resolve().then(()=>(xP(),bP));return spawnSupervised(n(),[S],H)}let[W,q]=kh[n].launch(S);return spawnSupervised(W,q,H)}function isSelfWrite(n,S,C){if(S===void 0||C===null)return!1;let N=Os(n,C),F=Os(n,S);if(N===F||N.startsWith(`${F}.`))return!0;let I=Ps(F);return I===Os(n)?!1:N===I||N.startsWith(`${I}${zs}`)}async function runWatchLoop(n){let{dir:S,label:C,prepare:N,build:F,spawnChild:I,output:H,debounceMs:W=200}=n;markDaemonCommand();let q=null,Y=!1,X=!1,rebuild=async()=>{if(Y){X=!0;return}Y=!0;try{N&&await N(),q&&=(q.kill(),null),await F(),I&&(q=await I())}catch(n){ve.error(`[${C}] rebuild failed: ${n.message}`)}finally{Y=!1,X&&(X=!1,rebuild())}};await rebuild();let Z=null,te=watch(S,{recursive:!0},(n,C)=>{isSelfWrite(S,H,typeof C==`string`?C:null)||(Z&&clearTimeout(Z),Z=setTimeout(()=>void rebuild(),W))});holdMainLoop();let ne=!1,shutdown=()=>{ne||(ne=!0,Z&&clearTimeout(Z),q?.kill(),te.close(),process.exit(0))};process.on(`SIGINT`,shutdown),process.on(`SIGTERM`,shutdown),ve.log(`[${C}] watching ${n.dirLabel??S} — press Ctrl+C to stop`)}var iH=__esmMin(()=>{ye(),Vl(),Hs(),Ie(),jF(),_P(),Ah()});function readPackage$3(n){try{return JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{return{}}}function deriveAppId(n){return n?`org.gjsify.storybook.${n.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function findStoryFiles(n){let S=[];if(!existsSync(n))return S;for(let C of readdirSync(n,{withFileTypes:!0})){if(C.name===`node_modules`||C.name.startsWith(`.`))continue;let N=js(n,C.name);C.isDirectory()?S.push(...findStoryFiles(N)):/\.story\.(ts|js|mts|mjs)$/.test(C.name)&&S.push(N)}return S}function generateEntry$2(n,S,C){let N=n.map((n,S)=>`import * as m${S} from ${JSON.stringify(n)};`).join(`
|
|
1686
1690
|
`),F=n.map((n,S)=>`m${S}`).join(`, `),I=C?`\n title: ${JSON.stringify(C)},`:``;return`// Auto-generated by \`gjsify storybook\` — do not edit by hand.
|
|
1687
1691
|
import { collectStoryModules, runStorybook } from '@gjsify/storybook';
|
|
1688
1692
|
${N}
|
|
@@ -1691,7 +1695,7 @@ await runStorybook({
|
|
|
1691
1695
|
applicationId: ${JSON.stringify(S)},${I}
|
|
1692
1696
|
stories: collectStoryModules([${F}]),
|
|
1693
1697
|
});
|
|
1694
|
-
`}var
|
|
1698
|
+
`}var aH,oH=__esmMin(()=>{ye(),Vl(),Hs(),th(),__name$1(readPackage$3,`readPackage`),__name$1(generateEntry$2,`generateEntry`),aH={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(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle (gi:// → @gjsify/node-gi) and require @gjsify/node-gi installed in the project.",type:`string`,choices:[`gjs`,`node`,`bun`,`deno`],defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`watch`,{description:`Rebuild and relaunch when a story file changes`,type:`boolean`,default:!1}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=readPackage$3(S),N=C.gjsify?.storybook??{},F=Os(S,n.stories??N.stories??`src`),I=n.appId??N.applicationId??deriveAppId(C.name),H=n.title??N.title,W=n.globals??N.globals??`auto`,q=n.runtime??N.runtime??hostRuntime$1(),Y=q===`gjs`?`gjs`:`node`,X=js(S,`node_modules`,`.cache`,`gjsify-storybook`);mkdirSync(X,{recursive:!0});let Z=js(X,`entry.ts`),te=n.out?Os(S,n.out):js(X,`storybook.${Y}.mjs`),writeEntry=()=>{let n=findStoryFiles(F).sort();return writeFileSync(Z,generateEntry$2(n,I,H)),n.length},ne=writeEntry();if(ne===0)return ve.error(`No *.story.ts files found under ${Ms(S,F)||F}\n\n \`gjsify storybook\` renders the stories of the CURRENT project: it discovers\n \`*.story.ts\` files and launches a component browser over them. Point it at a\n different directory with --stories <dir> (or \`gjsify.storybook.stories\` in\n package.json) if yours live elsewhere.\n\n To SEE a storybook without authoring one first, run the curated Libadwaita\n component browser — it is a showcase, so it needs no project at all:\n\n gjsify showcase adwaita-storybook`),process.exit(1);ve.log(`Found ${ne} story file(s) under ${Ms(S,F)||`.`} (runtime: ${q})`);let{runCli:re}=await Promise.resolve().then(()=>(gH(),hH)),buildBundle=()=>re([`build`,Z,`--app`,Y,`--globals`,W,`--outfile`,te]),launch=async()=>{if(q===`gjs`){let{runGjsBundle:n}=await Promise.resolve().then(()=>(yP(),vP));await n(te,[],{completion:`exit`,exitOnSuccess:!0})}else if(q===`node`){let{runNodeBundle:n}=await Promise.resolve().then(()=>(xP(),bP));await n(te,[],{completion:`exit`,exitOnSuccess:!0})}else{let{runRuntimeBundle:n}=await Promise.resolve().then(()=>(xP(),bP));await n(q,te,[],{completion:`exit`,exitOnSuccess:!0})}};if(!n.watch){if(await buildBundle(),n.buildOnly)return;await launch();return}let{runWatchLoop:ie,spawnBundleSupervised:ae}=await Promise.resolve().then(()=>(iH(),rH));await ie({dir:F,dirLabel:Ms(S,F)||`.`,label:`storybook`,prepare:()=>{writeEntry()},build:buildBundle,spawnChild:n.buildOnly?null:()=>ae(q,te,S,`the storybook`),output:te})}}});function readFlag(n,S){let C=`--${S}`;for(let S=0;S<n.length;S++){let N=n[S];if(N===C)return n[S+1];if(N.startsWith(`${C}=`))return N.slice(C.length+1)}}function withFlag(n,S,C){let N=`--${S}`,F=[...n];for(let n=0;n<F.length;n++){let S=F[n];if(S===N)return F[n+1]=C,F;if(S.startsWith(`${N}=`))return F[n]=`${N}=${C}`,F}return F.push(N,C),F}function buildEntryPoint(n){let S=n[1];if(!(S===void 0||S.startsWith(`-`)))return S}function noEntryError(n,S){let C=S?`\`${n}\` is not a plain \`gjsify build <entry> …\` command, so its entry point cannot be read`:`this package declares no \`${n}\` script`;return Error(`gjsify dev: nothing to build — ${C}.\n Name the entry point directly: gjsify dev src/index.ts\n or point at another script: gjsify dev --script <name>`)}function planDev(n){let S=n.scripts[n.scriptName],C=typeof S==`string`?gjsifyCommandArgv(S):null,N=C&&C[0]===`build`?C:null,F=n.entry??(N?buildEntryPoint(N):void 0);if(F===void 0)throw noEntryError(n.scriptName,typeof S==`string`);let I;return N?(I=[...N],buildEntryPoint(N)===void 0?I.splice(1,0,F):I[1]=F):I=[`build`,F],I=withFlag(I,`app`,n.app),n.globals!==void 0&&(I=withFlag(I,`globals`,n.globals)),n.outfile!==void 0&&(I=withFlag(I,`outfile`,n.outfile)),{buildArgv:I,bundle:readFlag(I,`outfile`)??n.declaredBundle,watchDir:n.watchDir??Ps(F)}}function noBundleError(n,S){return Error(`gjsify dev: nothing to launch — neither \`${n}\` nor --outfile names an output file, and this package declares no ${S===`gjs`?"`gjsify.main`":"`gjsify.example.node`"}.\n Pass one: gjsify dev --outfile dist/index.${S}.mjs\n or rebuild without launching: gjsify dev --build-only`)}var sH=__esmMin(()=>{Hs(),kF()});function readPackage$2(n){try{return JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{return{}}}var cH,lH=__esmMin(()=>{ye(),Vl(),Hs(),sH(),Ah(),th(),__name$1(readPackage$2,`readPackage`),cH={command:`dev [entry]`,description:`Watch this project, rebuild on change and relaunch the app.`,builder:n=>n.positional(`entry`,{description:"Entry point to build (default: the one the build script names, e.g. src/index.ts from `build:gjs`).",type:`string`}).option(`runtime`,{description:"Runtime to build for and launch on: gjs | node | bun | deno (default: the host runtime). node/bun/deno build the same `--app node` bundle.",type:`string`,choices:Oh,defaultDescription:`host runtime (gjs on gjs, else node/bun/deno)`}).option(`script`,{description:`package.json script the build flags are read from (default: build:gjs, or build:node for node/bun/deno).`,type:`string`}).option(`globals`,{description:"Override the build script `--globals` value.",type:`string`}).option(`outfile`,{description:"Override the build script `--outfile` path.",type:`string`}).option(`watch-dir`,{description:`Directory watched recursively (default: the directory of the entry point).`,type:`string`}).option(`debounce`,{description:`Quiet window in ms after a change before rebuilding.`,type:`number`,default:200}).option(`build-only`,{description:`Rebuild on every change but never launch the app.`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=readPackage$2(S),N=n.runtime??hostRuntime$1(),F=buildAppForRuntime(N),I=n.script??(F===`gjs`?`build:gjs`:`build:node`),H;try{H=planDev({scripts:C.scripts??{},scriptName:I,app:F,declaredBundle:F===`gjs`?C.gjsify?.main:C.gjsify?.example?.node,entry:n.entry,globals:n.globals,outfile:n.outfile,watchDir:n.watchDir})}catch(n){return ve.error(n.message),process.exit(1)}let W=H.bundle===void 0?void 0:Os(S,H.bundle);if(W===void 0&&!n.buildOnly)return ve.error(noBundleError(I,F).message),process.exit(1);let q=Os(S,H.watchDir);if(!existsSync(q))return ve.error(`gjsify dev: nothing to watch — ${Ms(S,q)||q} does not exist.\n Point the loop at your sources: gjsify dev --watch-dir <dir>`),process.exit(1);let Y=W===void 0?`\`${I}\` output`:Ms(S,W);ve.log(`Watching ${Ms(S,q)||`.`} → ${Y} (runtime: ${N})`);let{runCli:X}=await Promise.resolve().then(()=>(gH(),hH)),{runWatchLoop:Z,spawnBundleSupervised:te}=await Promise.resolve().then(()=>(iH(),rH));await Z({dir:q,dirLabel:Ms(S,q)||`.`,label:`dev`,build:()=>X(H.buildArgv),spawnChild:n.buildOnly||W===void 0?null:()=>te(N,W,S,`this project`),output:W,debounceMs:n.debounce})}}});function readPackage$1(n){try{return JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{return{}}}function deriveStorybookAppId(n){return n?`org.gjsify.storybook.${n.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Storybook`}function deriveBrowserAppId$1(n){return n?`org.gjsify.browser.${n.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function hasDep(n,S){return!!(n.dependencies?.[S]||n.devDependencies?.[S])}function generateEntry$1(n,S,C,N,F){let I=JSON.stringify(S),H=F?`, { address: ${JSON.stringify(F)} }`:``;return n===`storybook`?`// Auto-generated by \`gjsify debug\` — do not edit by hand.
|
|
1695
1699
|
import { runDevtoolsMcp, storybookProfile } from '@gjsify/devtools-mcp';
|
|
1696
1700
|
|
|
1697
1701
|
await runDevtoolsMcp(storybookProfile(${I}${H}));
|
|
@@ -1711,10 +1715,10 @@ await runDevtoolsMcp({
|
|
|
1711
1715
|
version: ${JSON.stringify(N)},
|
|
1712
1716
|
busNameBase: ${I},${F?`\n address: ${JSON.stringify(F)},`:``}
|
|
1713
1717
|
});
|
|
1714
|
-
`}var
|
|
1718
|
+
`}var uH,dH=__esmMin(()=>{ye(),Vl(),Hs(),__name$1(readPackage$1,`readPackage`),__name$1(deriveBrowserAppId$1,`deriveBrowserAppId`),__name$1(generateEntry$1,`generateEntry`),uH={command:`debug`,description:`Launch an MCP bridge for a devtools-enabled gjsify app (org.gjsify.Devtools).`,builder:n=>n.option(`bus-name`,{description:`App DBus base name (default: gjsify.devtools.busNameBase, or the storybook app-id)`,type:`string`}).option(`address`,{description:`Peer D-Bus address of the app (unix:path=… / nonce-tcp:…) instead of the session bus — for macOS/Windows, which have no session bus. Default: GJSIFY_DEVTOOLS_ADDRESS, then the address file the app publishes, then the session bus`,type:`string`}).option(`profile`,{description:`Tool profile: generic | storybook | browser | cdp (default: auto — storybook if @gjsify/storybook is a dep, browser if @gjsify/devtools-browser is, cdp if @gjsify/devtools-cdp is, else generic)`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-debug)`,type:`string`}).option(`build-only`,{description:`Build the bridge bundle but do not launch it (for a .mcp.json command pointing at the bundle)`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=readPackage$1(S),N=C.gjsify?.devtools??{},F=n.profile??N.profile??(hasDep(C,`@gjsify/storybook`)?`storybook`:hasDep(C,`@gjsify/devtools-browser`)?`browser`:hasDep(C,`@gjsify/devtools-cdp`)?`cdp`:`generic`),I=n.busName??N.busNameBase??(F===`storybook`?C.gjsify?.storybook?.applicationId??deriveStorybookAppId(C.name):F===`browser`||F===`cdp`?C.gjsify?.browse?.applicationId??deriveBrowserAppId$1(C.name):void 0);if(!I)return ve.error(`gjsify debug: no bus name — set package.json#gjsify.devtools.busNameBase or pass --bus-name <org.example.App>`),process.exit(1);let H=n.globals??N.globals??`auto`,W=C.name?`${C.name}-devtools`:`gjsify-devtools`,q=js(S,`node_modules`,`.cache`,`gjsify-debug`);mkdirSync(q,{recursive:!0});let Y=js(q,`entry.ts`),X=n.out?Os(S,n.out):js(q,`bridge.gjs.mjs`),Z=n.address??N.address;writeFileSync(Y,generateEntry$1(F,I,W,`0.8.0`,Z)),ve.error(`[gjsify debug] profile=${F} bus=${I}${Z?` address=${Z}`:``}`);let{runCli:te}=await Promise.resolve().then(()=>(gH(),hH));if(await te([`build`,Y,`--app`,`gjs`,`--shebang`,`--globals`,H,`--outfile`,X]),n.buildOnly){ve.error(`[gjsify debug] built ${X}`);return}let{runGjsBundle:ne}=await Promise.resolve().then(()=>(yP(),vP));await ne(X,[],{completion:`exit`,exitOnSuccess:!0})}}});function readPackage(n){try{return JSON.parse(readFileSync(js(n,`package.json`),`utf8`))}catch{return{}}}function deriveBrowserAppId(n){return n?`org.gjsify.browser.${n.replace(/^@/,``).replace(/[^a-zA-Z0-9]+/g,`.`).replace(/^\.+|\.+$/g,``)}`:`org.gjsify.Browser`}function generateEntry(n,S,C,N,F){let I=C?`\n title: ${JSON.stringify(C)},`:``,H=S?`\n homeUrl: ${JSON.stringify(S)},`:``,W=N===void 0?``:`\n inspectorPort: ${N},`,q=F?`\n screenshot: ${JSON.stringify(F)},`:``;return`// Auto-generated by \`gjsify browse\` — do not edit by hand.
|
|
1715
1719
|
import { runBrowserDevtools } from '@gjsify/devtools-browser';
|
|
1716
1720
|
|
|
1717
1721
|
await runBrowserDevtools({
|
|
1718
1722
|
applicationId: ${JSON.stringify(n)},${I}${H}${W}${q}
|
|
1719
1723
|
});
|
|
1720
|
-
`}var
|
|
1724
|
+
`}var fH,pH=__esmMin(()=>{ye(),Vl(),Hs(),fH={command:`browse [url]`,description:`Launch the Adwaita web browser, optionally pointed at a URL.`,builder:n=>n.positional(`url`,{description:`Initial URL to load (default: page:welcome)`,type:`string`}).option(`app-id`,{description:`GApplication id (default: gjsify.browse.applicationId or derived from the package name)`,type:`string`}).option(`title`,{description:`Window title`,type:`string`}).option(`globals`,{description:"Value for `gjsify build --globals` (default: auto,dom — WebKit/iframe need DOM globals)",type:`string`}).option(`out`,{description:`Output bundle path (default: node_modules/.cache/gjsify-browse)`,type:`string`}).option(`devtools`,{description:`Enable the MCP devtools control plane (sets GJSIFY_DEVTOOLS=1)`,type:`boolean`,default:!1}).option(`inspector-port`,{description:`Enable WebKit's remote inspector protocol on this port + the Cdp* methods (implies --devtools)`,type:`number`}).option(`screenshot`,{description:`One-shot: load the URL, capture a WebKit screenshot to this path, and exit (CI / quick captures).`,type:`string`}).option(`build-only`,{description:`Build the bundle but do not launch it`,type:`boolean`,default:!1}),handler:async n=>{let S=process.cwd(),C=readPackage(S),N=C.gjsify?.browse??{},F=n.appId??N.applicationId??deriveBrowserAppId(C.name),I=n.title??N.title,H=n.globals??N.globals??`auto,dom`,W=n.url,q=n.inspectorPort??N.inspectorPort,Y=n.devtools||q!==void 0,X=js(S,`node_modules`,`.cache`,`gjsify-browse`);mkdirSync(X,{recursive:!0});let Z=js(X,`entry.ts`),te=n.out?Os(S,n.out):js(X,`browse.gjs.mjs`);writeFileSync(Z,generateEntry(F,W,I,q,n.screenshot?Os(S,n.screenshot):void 0)),ve.log(`[gjsify browse] app=${F}${W?` url=${W}`:``}${Y?` devtools=1`:``}${q===void 0?``:` inspector-port=${q}`}`);let{runCli:ne}=await Promise.resolve().then(()=>(gH(),hH));if(await ne([`build`,Z,`--app`,`gjs`,`--globals`,H,`--outfile`,te]),n.buildOnly){ve.log(`[gjsify browse] built ${te}`);return}Y&&(process.env.GJSIFY_DEVTOOLS=`1`),q!==void 0&&(process.env.WEBKIT_INSPECTOR_HTTP_SERVER=`127.0.0.1:${q}`);let{runGjsBundle:re}=await Promise.resolve().then(()=>(yP(),vP));await re(te,[],{completion:`exit`,exitOnSuccess:!0})}}}),mH=__esmMin(()=>{iP(),sP(),uP(),CP(),NF(),FF(),LF(),XF(),lI(),DI(),AI(),PI(),LI(),bL(),lB(),aI(),_B(),SB(),JF(),DB(),YB(),ZB(),eV(),nV(),cV(),mV(),xV(),wV(),EV(),OV(),AV(),MV(),PV(),BV(),GV(),qV(),nH(),oH(),lH(),dH(),pH()}),hH=__exportAll$4({runCli:()=>runCli});function runtimeLabel(){let n=gjsSystemVersion();if(n!==void 0){let S=Number(n);return`GJS ${Math.floor(S/1e4)}.${Math.floor(S%1e4/100)}.${S%100} (SpiderMonkey)`}return isBun()?`Bun ${globalThis.Bun?.version??process.versions.bun??``}`.trim():isDeno()?`Deno ${globalThis.Deno?.version?.deno??``}`.trim():isNode()?`Node.js ${process.version}`:`unknown runtime`}async function runCli(n){ensureGjsifyShimOnPath();let S=Hf(n);await S.scriptName(rp).version(cliVersion()).strict().fail((n,C)=>{let N=classifyCliFailure(n,C);if(N.kind===`usage`)throw S.showHelp(`error`),Error(N.message,{cause:C})}).wrap(S.terminalWidth()).command(EI.command,EI.description,EI.builder,EI.handler).command(hB.command,hB.description,hB.builder,hB.handler).command(rP.command,rP.description,rP.builder,rP.handler).command(oP.command,oP.description,oP.builder,oP.handler).command(lP.command,lP.description,lP.builder,lP.handler).command(SP.command,SP.description,SP.builder,SP.handler).command(MF.command,MF.description,MF.builder,MF.handler).command(iI.command,iI.description,iI.builder,iI.handler).command(PF.command,PF.description,PF.builder,PF.handler).command(IF.command,IF.description,IF.builder,IF.handler).command(YF.command,YF.description,YF.builder,YF.handler).command(cI.command,cI.description,cI.builder,cI.handler).command(kI.command,kI.description,kI.builder,kI.handler).command(NI.command,NI.description,NI.builder,NI.handler).command(II.command,II.description,II.builder,II.handler).command(yL.command,yL.description,yL.builder,yL.handler).command(cB.command,cB.description,cB.builder,cB.handler).command(xB.command,xB.description,xB.builder,xB.handler).command(qF.command,qF.description,qF.builder,qF.handler).command(wB.command,wB.description,wB.builder,wB.handler).command(JB.command,JB.description,JB.builder,JB.handler).command(XB.command,XB.description,XB.builder,XB.handler).command($B.command,$B.description,$B.builder,$B.handler).command(tV.command,tV.description,tV.builder,tV.handler).command(sV.command,sV.description,sV.builder,sV.handler).command(pV.command,pV.description,pV.builder,pV.handler).command(yV.command,yV.description,yV.builder,yV.handler).command(CV.command,CV.description,CV.builder,CV.handler).command(DV.command,DV.description,DV.builder,DV.handler).command(TV.command,TV.description,TV.builder,TV.handler).command(LV.command,LV.description,LV.builder,LV.handler).command(kV.command,kV.description,kV.builder,kV.handler).command(jV.command,jV.description,jV.builder,jV.handler).command(NV.command,NV.description,NV.builder,NV.handler).command(WV.command,WV.description,WV.builder,WV.handler).command(KV.command,KV.description,KV.builder,KV.handler).command(eH.command,eH.description,eH.builder,eH.handler).command(aH.command,aH.description,aH.builder,aH.handler).command(cH.command,cH.description,cH.builder,cH.handler).command(uH.command,uH.description,uH.builder,uH.handler).command(fH.command,fH.description,fH.builder,fH.handler).demandCommand(1).epilogue(`Running on ${runtimeLabel()}`).help().parseAsync()}var gH=__esmMin(()=>{Uf(),Wf(),np(),mH(),ip(),th(),OF()});ye(),gH(),th();try{await runCli(hideBin(process.argv))}catch(n){let S=typeof n==`object`&&n&&typeof n.code==`string`?n.code:``,C=n instanceof Error?n.message:String(n);ve.error(S&&!C.includes(S)?`${S}: ${C}`:C),process.env.GJSIFY_DEBUG&&n instanceof Error&&n.stack&&ve.error(n.stack),process.exitCode=1,gjsExit(1)}
|